| JavaScript Modules | JavaScript question answers 241-260 | |
๐ Connecting JavaScript with REST APIs |
Connecting JavaScript with RESTful APIs involves making HTTP requests to retrieve or send data to a server. The most modern and recommended method is the Fetch API, which uses Promises to handle asynchronous operations. Other options include using the third-party library Axios or the older XMLHttpRequest (XHR) method
A REST (Representational State Transfer) API allows communication between client and server using HTTP methods like GET, POST, PUT, and DELETE. It typically returns data in JSON format.
fetch()// GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Hello',
body: 'This is a test post',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
async/awaitasync function getPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
getPost();
The fetch() method is a browser-native, Promise-based function for making network requests.
To fetch data, you simply pass the API endpoint URL to fetch(). The request is asynchronous, so you must use .then() to handle the response when it arrives.
javascript
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the JSON data from the response
return response.json();
})
.then(data => {
console.log(data); // Process and use the data
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
For a POST request, you must provide a second argument, an options object, to specify the HTTP method, headers, and body.
javascript
const newUserData = {
name: 'John Doe',
username: 'johndoe',
email: 'johndoe@example.com'
};
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUserData)
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
Using async/await provides a cleaner, more readable way to handle promises, especially when dealing with multiple asynchronous calls.
javascript
async function fetchUser(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const user = await response.json();
return user;
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchUser(1).then(user => console.log(user));
Axios is a popular third-party library known for simplifying HTTP requests and offering additional features like request/response interceptors and better error handling out of the box.
You can install Axios via npm or include it from a CDN.
bash
npm install axios
javascript
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
javascript
import axios from 'axios';
const newUserData = {
name: 'Jane Doe',
username: 'janedoe',
email: 'janedoe@example.com'
};
axios.post('https://jsonplaceholder.typicode.com/users', newUserData)
.then(response => {
console.log('Success:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
try/catch or .catch()async/await for cleaner syntaxContent-Type)Many APIs require authentication using tokens:
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
});
fetch() | JavaScript Modules | JavaScript question answers 241-260 | |