Consuming APIs with Fetch in JavaScript
Discover how to fetch data from servers and bring dynamic content to your websites using JavaScript's powerful Fetch API.
/* Starting our data journey... */
What is an API?
An API (Application Programming Interface) is like a restaurant menu for a server. It lists the requests you can make (e.g., "get user data") and the format of the response you'll receive, typically as JSON data.
Making a Request with `fetch()`
The fetch()
function is your tool to order from the API. You give it a URL, and it sends an HTTP request to that server. By default, it's a GET request, which means you're asking to retrieve information.
Handling Responses with Promises
Network requests aren't instant. fetch()
immediately returns a Promise—a placeholder for a future value. You use the .then()
method to specify what to do once the server responds.
Catching Errors
What if the network is down or the URL is wrong? The Promise will be "rejected." You can handle these failures gracefully by adding a .catch()
block at the end of your chain. This prevents your application from crashing.
Practice Zone
Interactive Test 1: Order the Chain
Drag the methods into the correct order to handle a successful API request and a potential error.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Build the Request
Rellena los huecos en cada casilla.
('api/data') .(res => res.json()) .(data => console.log(data)) .(error => console.error(error));
Practice Example: Live API Call
Fetch data from 'https://jsonplaceholder.typicode.com/todos/1'
and log the resulting data object to the console.
Modern Fetch Patterns
While .then()
is fundamental, modern JavaScript offers a cleaner syntax called async/await
for handling asynchronous code.
1. The `async/await` Syntax
You can declare a function as async
, which allows you to use the await
keyword. await
pauses the function execution until a Promise settles, making your asynchronous code look synchronous and easier to read.
// .then() chain
fetch(URL)
.then(res => res.json())
.then(data => {
console.log(data);
});
// async/await
async function getData() {
const res = await fetch(URL);
const data = await res.json();
console.log(data);
}
2. Sending Data with a POST Request
To send data, you pass a second argument to fetch
: an options object. You specify the method
as 'POST', add headers
to describe the content, and put your data in the body
(usually as a JSON string).
const newPost = { title: 'My new article', userId: 1 };
fetch('api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newPost),
});
3. Displaying Fetched Data in the DOM
Once you have the data, you can use standard DOM manipulation to display it on your webpage. This is how you create dynamic, data-driven user interfaces.
// HTML: <h1 id="title">Loading...</h1>
const titleElement = document.getElementById('title');
fetch('api/post/1')
.then(res => res.json())
.then(data => {
titleElement.textContent = data.title;
});
Fetched Post Title!
Practical Takeaway: Master thefetch
chain with.then()
and.catch()
first, then adoptasync/await
for cleaner, more readable code, especially when handling complex sequences of asynchronous operations.
Fetch API Glossary
- API
- Application Programming Interface. A set of rules and protocols that allows different software applications to communicate with each other.
- fetch()
- A modern JavaScript interface for making network (HTTP) requests. It is a more powerful and flexible replacement for `XMLHttpRequest`.
- Promise
- An object representing the eventual completion (or failure) of an asynchronous operation. It can be in one of three states: pending, fulfilled, or rejected.
- .then()
- A method that takes a callback function to be executed when a Promise is successfully resolved. It is the primary way to get the value out of a Promise.
- .catch()
- A method that takes a callback function to be executed when a Promise is rejected (i.e., an error occurs).
- JSON
- JavaScript Object Notation. A lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is the most common format for API data.
- async / await
- Syntactic sugar built on top of Promises that makes asynchronous code look and behave more like synchronous code, improving readability.