Introduction:
- The Fetch API is a powerful JavaScript tool used to interact with Web APIs.
- Learn how to make GET, POST, PUT, PATCH, and DELETE requests.
- This tutorial also covers async/await with Fetch and handling API responses.
How the Fetch API Works:
- The
fetch()
function takes:- A URL (required).
- An options object (optional), where you define request method, headers, and body.
- It returns a Promise, allowing you to handle responses with
.then()
and errors with.catch()
.
Video Tutorial: Visit YouTube
Example:
fetch('<Your URL>')
.then((response) => {
// Handle success
})
.catch((error) => {
// Handle error
})
Sending Requests:
1. GET Request:
- Used to fetch data from an API. Example:
fetch('https://jsonplaceholder.typicode.com/users/1')
.then((response) => response.json())
.then((data) => console.log(data))
- Converts the response to JSON using
.json()
and logs user data likename
andemail
.
2. POST Request:
- Can be used to send data to an API (e.g., creating a new user).
To send a "POST"
request using fetch, you need to define the second argument as an options object containing the following:
- Method: Set the method property to "POST".
- Headers: Include a Content-Type header set to "application/json".
- Body: Use JSON.stringify() to convert the data you want to send into JSON format and assign it to the body property.
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John', email: 'john@example.com' }),
})
.then((response) => response.json())
.then((data) => console.log(data))
3. PUT Request:
- Replaces existing data or creates new data.
- Similar to POST, but used to overwrite resources. Example:
fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Jane', email: 'jane@example.com' }),
})
.then((response) => response.json())
.then((data) => console.log(data))
4. PATCH Request:
- Partially updates data for a specific resource.
- To update an existing user's name, you can use the PATCH.
Example:
fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Jane' }),
})
.then((response) => response.json())
.then((data) => console.log(data))
5. DELETE Request:
- Removes a resource permanently.
- To run a DELETE request with Fetch, you only need to specify the URL for the resource to delete and the method: 'DELETE' property as follows: Example:
fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'DELETE',
}).then((response) => console.log('Deleted:', response))
Difference Between PUT and PATCH Methods
The PUT
method replaces the entire resource with the updated data, while the PATCH
method modifies only the specified fields in the resource.
- Use
PUT
for complete updates. - Use
PATCH
for partial updates.
Using Async/Await with Fetch:
- Async/await simplifies working with Promises:
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/2')
const data = await response.json()
console.log(data)
} catch (error) {
console.log(error)
}
}
fetchData()
Video Tutorial: Visit YouTube
Using Fetch API to Display Data in HTML
Here’s an example that demonstrates fetching and displaying user details on a webpage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fetch API Example</title>
</head>
<body>
<h1>User Information</h1>
<div id="user-info">
<p id="user-name">Name: Loading...</p>
<p id="user-email">Email: Loading...</p>
</div>
<script>
// Fetch user data
fetch('https://jsonplaceholder.typicode.com/users/1')
.then((response) => response.json())
.then((data) => {
document.getElementById(
'user-name'
).textContent = `Name: ${data.name}`
document.getElementById(
'user-email'
).textContent = `Email: ${data.email}`
})
.catch((error) => console.error('Error:', error))
</script>
</body>
</html>
Tips for Working with APIs:
- Always check the API documentation for required request methods, headers, and formats.
- Understand whether the API returns JSON, arrays, or other data structures.
- Practice with free APIs like
https://jsonplaceholder.typicode.com
.
Video Tutorial: Visit YouTube
Conclusion:
- The Fetch API is versatile for making HTTP requests in JavaScript.
- Use
.then()
/.catch()
or async/await for handling responses. - Master GET, POST, PUT, PATCH, and DELETE to interact with any API effectively.
Top comments (0)