Marian
Marian's Security Blog

Marian's Security Blog

JavaScript Fetch Api

JavaScript Fetch Api

Marian's photo
Marian
·May 5, 2022·

3 min read

What is The Fetch API?

Fetch is a promise based javascript api for making asynchronous http requests.

Fetch is a simple, powerful and flexible way to get or send data from/to a server.

Even if the name implies that you can only "fetch" data, you can actually make any type of request: GET, POST, PUT, PATCH, DELETE. Each fetch call returns a promise. This allows you to easily handle the data that you receive and the errors you might get. Let's take a look at how it works!

Basis Example: GET

Let's say we need to get a list of users from the server:

fetch('https://placeholder.url.com/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err))

We call fetch( and give it a request url as its parameter. Since we know that fetch will return a promise, we use then() to access the server's response. The response object returned on line 2 contains all of the response's data, including headers, status code, status message. Since we know that we're expecting a json response, we can call the . Json() method to be able to acces the actual data in the chained . Then() call. We can also use a . Catch() block to handle possible errors thrown by the server.

Possible Response Types

Not all calls will return json responses, so it's useful to be aware that the response object returned by fetch has multiple methods you can use:

// create a clone of the response
response.clone()

// create a new response with a different URL
response.redirect()

// returns a promise that resolves with Array Buffer
response.arrayBuffer()

//returns a promise that resolve with a DormData Object
response.formData()

// returns a promise that returns with a Blob
response.blob()

// returns a promise that resolve with a string
response.text()

// returns a promise that resolves with JSON
response.json()

Accessing Response Info

Besides the methods we use to manipulate the data in our response, we also have access to some other fields that might hold useful information:

fetch('https://placeholder.url.com/users')
.then(response => {
// accessing response headers
console.log(response.headers.get('content-type'));

// the HTTP response status code
console.log(response.status)

//true if status code is between 200 and 299
console.log(response.ok)

// status message of the response e.g. 'Not-Found'
console.log(response.statusText)

// true if there was a redirect
console.log(response.redirected)

// the response type (e.g., 'basic', 'cors')
console.log(response.type)

// the full url of the request
console.log(response.url)
});

Making Write Requests

You can make POST, PUT or PATCH requests using fetch by adding a second parameter, an object that will contain the necessary details. Here's how:

// the data we want to send
const user = {
userName: 'ElevenSpins'
password: 'secret'
} ;

// specify the HTTP Method we want to use, add headers to the object
const requestData = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(user),
}

fetch('https://placeholder.url.com/users', requestData)
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err))

Done 🥳 you've just made a http post request to the server using fetch!

Making Delete Requests

You can also delete resources with fetch by using delete as the method, like so:

// specify the HTTP Method we want to use, add headers to the object
const requestData = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}

fetch('https://placeholder.url.com/users/6', requestData)
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err))

Here we add the user's id in the url so that the server knows which user we want to delete and make the request. Now you're more than ready to work with apis using javascript's fetch!

If you found some mistakes please let me know in a comment! Happy to discuss with you.

 
Share this