Simplified HTTP Requests With Fetch API

Idan Zonshein
Tech at Power
Published in
3 min readAug 10, 2020

--

Overview:

  1. Concept and Usage
  2. Breakdown
  3. Fetch Interfaces
  4. HTTP examples
  5. Conclusion

Concept and Usage

In a lot of today’s web applications, a common practice is to request or show some sort of data from an existing server. This could include pulling such information like users, posts, comments, etc. and then manipulating it by using CRUD (create, read, update or delete) actions. To do this using JavaScript, we can turn our attention to the Fetch API.

The Fetch API provides a JavaScript interface for retrieving and manipulating parts of the HTTP process, such as requests and responses. It also provides a global fetch() method that provides an easy and convenient way to fetch resources asynchronously.

While this type of task used to be done using XMLHttpRequest or XHR for short, current-day practices using Fetch provides a much better alternative. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback issues, and overall is less verbose. Fetch also provides a single place to define other HTTP-related concepts such as CORS and extensions to HTTP.

Breakdown

The basic structure of fetch() works like this…

The fetch() makes a network request to a URL and returns a promise. The promise resolves with a response object when the remote server responds with headers, but before the full response is downloaded. This will result in a status of successful or not. Next we need a way to access the content of the fetch. To read the response body, we have to call a response method on it, like text() or json(), which will return another promise whose resolve value is the body of the response. This can be done using the .then() handler (callback). Lastly, adding a .catch to the end of the fetch request allows the console to read out any errors that might have arisen during the callback.

If this sounds confusing, that is okay, we will dive into some examples in the next section.

So in short, we first define the path (Fetch), secondly request data from the server (Request), thirdly define the content type (Body), and last but not least, we access the data (Response).

Basic fetch() blueprintfetch(url)
.then(response => {
// handle the response
})
.catch(error => {
// handle the error
})

Fetch Interfaces

The Fetch API has the following interfaces

  • fetch(): The fetch() method used to fetch a resource.
  • Headers: Represents response/request headers, allowing you to query them and take different actions depending on the results and declare its content type.
  • body: Provides methods relating to the body of the response/request.
  • Request: Represents a resource request.
  • Response: Represents the response to a request.

HTTP examples

fetch() can go to any URL, including your own server. To visit your site’s own files, just give a relative path name instead of a URL. If fetch() fails to see “http”, it will assume you are going from your root directory.

Below are some examples of how to implement fetching from a URL. It is important to note that your site must be able to handle incoming data on the backend for certain CRUD actions to work.

Our examples path will be
https://jsonplaceholder.typicode.com/todos
This will return dummy JSON files that follow REST conventions.
  1. Getting a list of all todos
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(data => console.log(data))

2. Creating a new todo task

fetch('https://jsonplaceholder.typicode.com/todos', {
headers: { "Content-Type": "application/json; charset=utf-8" },
method: 'POST',
body: JSON.stringify({
title: 'Clean dishes',
completed: false
})
})

3. Deleting a task with an id of 1

fetch('https://jsonplaceholder.typicode.com/todos/1', { 
method: 'DELETE'
});

4. Updating a task

fetch('https://jsonplaceholder.typicode.com/todos/2', {
headers: { "Content-Type": "application/json; charset=utf-8" },
method: 'PUT',
body: JSON.stringify({
complete: true
})
})

Conclusion

The next time you need to load information from a remote server with a network request, remember to use the quick and easy Fetch API. Its short syntax will save you the time and headache and will allow future developers to quickly pick up where you left off by understanding each request to the server easily.

This post is written by a Power Code Academy Student Developer.

--

--