The Fetch API Cheatsheet: Nine of the Most Common API Requests

As a web developer, interacting with APIs is a crucial part of building dynamic, data-driven applications. The Fetch API provides a clean, modern way to make HTTP requests in JavaScript. Once you understand the basics of how it works, fetch can be a powerful tool in your dev toolkit.

In this post, I‘ll share a cheatsheet of 9 of the most common API request patterns I use on a regular basis. I‘ll provide clear examples of the syntax for each request type, and share some tips I‘ve learned to make working with Fetch easier. Let‘s dive in!

Fetch API Basics

Before we look at different request examples, let‘s quickly review how the fetch() method works. Fetch allows you to make HTTP requests to a server and process the response.

The basic syntax looks like this:

fetch(‘https://api.example.com/data‘)
.then(response => {
  // Process response
})
.catch(error => {
  // Handle any errors
});

Fetch returns a promise that resolves to the Response object representing the response to your request. You can then handle the response using .then() promise chaining. Or starting from ES2017, you can use async/await for cleaner-looking code.

One important thing to understand is that fetch won‘t automatically throw an error for HTTP error status codes (like 404 or 500). The promise will only reject on actual network failures. To handle HTTP errors, you need to manually check the response.ok or response.status properties.

With those key concepts in mind, let‘s look at 9 common fetch request examples you‘re likely to need in real-world apps.

1. Simple GET Request

The most basic fetch request is a GET to retrieve a resource from an API. For example, let‘s say we want to fetch a list of posts from a /posts endpoint:

fetch(‘https://api.example.com/posts‘)
.then(response => response.json())
.then(data => {
  console.log(data);
});

Here we make a simple GET request to the /posts URL. When the response comes back, we use response.json() to parse the response body as JSON. This returns another promise which resolves to the actual response data, which we then log to the console.

2. GET Request with Request Headers

Many APIs require you to send authorization or other headers with your requests. With fetch, you can easily add headers using the headers option:

fetch(‘https://api.example.com/profile‘, {
  headers: {
    ‘Authorization‘: ‘Bearer my-access-token‘  
  }
})
.then(response => response.json())
.then(data => {
  console.log(data);
});  

In this example, we set the Authorization header to a bearer token value to authenticate the request. You can include any custom headers the API expects here.

3. GET Request with Query Parameters

To pass query parameters to a fetch GET request, simply include them in the URL:

fetch(‘https://api.example.com/search?q=JavaScript&sort=desc‘)  
.then(response => response.json())
.then(data => {
  console.log(data);
});

Here the URL includes two query parameters, q and sort, to perform a search. The API will parse those query params and return the matching results.

4. Simple POST Request

To send data to an API, you‘ll make a POST request. With fetch, you need to specify the HTTP method, as well as provide the request body. Here‘s a simple example:

fetch(‘https://api.example.com/users‘, {
  method: ‘POST‘,
  body: JSON.stringify({ 
    name: ‘John‘,
    email: ‘[email protected]‘
  })
})
.then(response => response.json())
.then(data => {
  console.log(data);
});

We set the method to POST and pass a JSON request body containing the data for the new user we want to create. The body needs to be a string, so we use JSON.stringify() to serialize our object.

5. POST Request with JSON Body

When sending JSON data, we need to set the Content-Type header so the server knows how to interpret the request body:

fetch(‘https://api.example.com/users‘, {
  method: ‘POST‘, 
  headers: {
    ‘Content-Type‘: ‘application/json‘
  },
  body: JSON.stringify({ 
    name: ‘John‘,
    email: ‘[email protected]‘  
  })
})
.then(response => response.json()) 
.then(data => {
  console.log(data);
});

By setting Content-Type to application/json, we tell the API that the request body is in JSON format. This way it can be parsed correctly on the server.

6. POST Request with Form Data

To send data as a set of key-value pairs (like an HTML form submission), you can use a FormData object as the request body:

const formData = new FormData();
formData.append(‘name‘, ‘John‘);  
formData.append(‘email‘, ‘[email protected]‘);

fetch(‘https://api.example.com/users‘, {
  method: ‘POST‘,
  body: formData
})
.then(response => response.json())
.then(data => {  
  console.log(data);
});

We create a new FormData instance, append key-value pairs to it, and pass it directly as the fetch body. Note that you don‘t need to set Content-Type manually in this case. The browser will automatically add the correct multipart/form-data Content-Type and encoding.

7. PUT Request to Update a Resource

To update an existing resource, make a PUT request to the resource URL:

fetch(‘https://api.example.com/posts/123‘, {  
  method: ‘PUT‘,
  headers: {
    ‘Content-Type‘: ‘application/json‘  
  },
  body: JSON.stringify({
    title: ‘Updated post title‘
  })  
})
.then(response => response.json())
.then(data => {
  console.log(data);  
});

This will fully replace the resource at the specified URL with the data provided in the request body. Alternatively, you can use the PATCH method to partially update a resource.

8. DELETE Request to Delete a Resource

To delete a resource, make a DELETE request to its URL:

fetch(‘https://api.example.com/posts/123‘, { 
  method: ‘DELETE‘
})
.then(response => response.json())
.then(data => {
  console.log(data);
});  

Successful DELETE requests usually return a response with a 204 No Content status.

9. Handling Errors and Checking Response Status Codes

As I mentioned before, fetch won‘t automatically throw an error for HTTP error statuses. To properly handle errors and check the response status, you can use code like this:

fetch(‘https://api.example.com/posts/123‘)
.then(response => {
  if (!response.ok) { 
    throw new Error(‘Network response was not ok‘);
  }
  return response.json();
})
.then(data => {
  console.log(data); 
})
.catch(error => {
  console.error(‘There was a problem fetching data:‘, error);
});

First we check if response.ok is false, which means the status code is not in the 200-299 range. If so, we throw an error to reject the promise chain.

Otherwise, we return response.json() to parse the response data. Any errors, including the one we threw for a bad status, will be caught in the final .catch() block.

To check for specific status codes, you can use response.status and handle them based on your app logic:

fetch(‘https://api.example.com/posts/123‘)
.then(response => {
  if (response.status === 404) {
    throw new Error(‘Resource not found‘);  
  } else if (response.status === 401) {
    throw new Error(‘Unauthorized request‘); 
  }
  return response.json();
})
...

Using Async/Await with Fetch

To avoid long promise chains, you can use async/await with fetch to write more synchronous-looking code:

async function getUsers() {
  try {
    const response = await fetch(‘https://api.example.com/users‘);

    if (!response.ok) {
      throw new Error(‘Network response was not ok‘);
    }

    const data = await response.json();
    console.log(data);

  } catch (error) {
    console.error(‘There was a problem fetching data:‘, error);
  }
}

With async/await, we can assign the await fetch() promise directly to a variable. This pauses execution until the promise resolves.

We still need to await response.json() to parse the response body. And we can wrap the code in a try/catch block to handle any thrown errors.

Best Practices for Fetch

To wrap up, here are a few tips and best practices to keep in mind when using Fetch:

  • Always check for errors and bad response statuses. Don‘t assume the happy path!
  • Use try/catch or .catch() to handle errors and log them for debugging.
  • Take advantage of async/await to simplify promise handling.
  • Set the Content-Type header when sending JSON or other non-default data types.
  • Abstract common logic for making API requests into reusable functions.
  • Consider using a library like Axios for more advanced functionality and better error handling out of the box.

Conclusion

The Fetch API is a powerful, flexible way to interact with web services directly from your JavaScript code. I hope these nine common request patterns, along with the syntax examples and tips I‘ve shared, will help you become more productive when working with Fetch.

Remember, practice makes perfect. The more you use these request types in your own projects, the more comfortable you‘ll get with the fetch() method and its nuances. Don‘t be afraid to experiment and consult documentation as you learn.

Now go forth and build some amazing things by unlocking the power of APIs with Fetch! Let me know how it goes—I‘d love to hear about the creative ways you use this cheatsheet in your own work.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *