Day 13: Working with APIs in JavaScript

Welcome back to our JavaScript series! Today, we’ll dive into working with APIs in JavaScript. APIs (Application Programming Interfaces) allow your application to interact with other software and services. We’ll cover what APIs are, how to make HTTP requests using the Fetch API and XMLHttpRequest, and how to handle the responses.
What is an API?
An API, or Application Programming Interface, is a set of rules and protocols for building and interacting with software applications. APIs allow different software systems to communicate with each other. In web development, APIs are often used to fetch data from a server or send data to a server.
Making HTTP Requests
To interact with APIs, you’ll need to make HTTP requests. JavaScript provides several ways to do this:
Fetch API
XMLHttpRequest
1. Fetch API
The Fetch API provides a modern and flexible way to make HTTP requests. It returns a promise that resolves to the response of the request.
Basic Syntax
fetch(url)
.then(response => {
// Process the response
})
.catch(error => {
// Handle errors
});
Example: Fetching Data
fetch('https://api.github.com/usersName')
.then(response => response.json()) // Parse the JSON from the response
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Example: Sending Data (POST Request)
fetch('https://api.github.com/usersName', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error sending data:', error);
});
2. XMLHttpRequest
The older way to make HTTP requests in JavaScript is using XMLHttpRequest. While it's less modern than Fetch, it’s still widely used, especially for legacy support.
Basic Syntax
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// Process the response
} else {
// Handle errors
}
};
xhr.onerror = function() {
// Handle network errors
};
xhr.send();
Example: Fetching Data
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/usersName', true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
let data = JSON.parse(xhr.responseText);
console.log('Data received:', data);
} else {
console.error('Error fetching data:', xhr.statusText);
}
};
xhr.onerror = function() {
console.error('Network error');
};
xhr.send();
Handling Responses
When you make an HTTP request, you need to handle the response appropriately.
Response Status
Always check the status of the response to ensure the request was successful.
fetch('https://api.github.com/userName')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Parsing JSON
Most APIs return data in JSON format. Use response.json() to parse the JSON from the response.
fetch('https://api.github.com/userName')
.then(response => response.json())
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Error Handling
Proper error handling is crucial when working with APIs. Handle both network errors and errors returned by the API.
fetch('https://api.github.com/userName')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Asynchronous and Await
The async and await keywords can be used to write asynchronous code that looks synchronous. This makes it easier to work with promises.
Example: Using Async/Await
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
let data = await response.json();
console.log('Data received:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
Summary
Today, we explored about the working of APIs in JavaScript. We covered making HTTP requests using the Fetch API and XMLHttpRequest, handling responses, and error handling. From next day onwards , we’ll continue with more advanced JavaScript topics.




