Published: September 20 2021

Fetch - HTTP PUT Request Examples

Below is a quick set of examples to show how to send HTTP PUT requests to an API using fetch() which comes bundled with all modern browsers.

Other HTTP examples available:


Simple PUT request with a JSON body using fetch

This sends an HTTP PUT request to the Reqres api which is a fake online REST api that includes a generic /api/<resource> route that responds to PUT requests for any <resource> with the contents of the request body and an updatedAt property with the current date. This example sends an article object to the /api/articles/1 route and then writes the updatedAt property from the response to the #put-request .date-updated element so it's displayed on the page.

// Simple PUT request with a JSON body using fetch
const element = document.querySelector('#put-request .date-updated');
const requestOptions = {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Fetch PUT Request Example' })
};
fetch('https://reqres.in/api/articles/1', requestOptions)
    .then(response => response.json())
    .then(data => element.innerHTML = data.updatedAt );

Example Fetch PUT request at https://stackblitz.com/edit/fetch-http-put-request-examples?file=put-request.js


PUT request using fetch with async/await

This sends the same PUT request using fetch, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

(async () => {
    // PUT request using fetch with async/await
    const element = document.querySelector('#put-request-async-await .date-updated');
    const requestOptions = {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'Fetch PUT Request Example' })
    };
    const response = await fetch('https://reqres.in/api/articles/1', requestOptions);
    const data = await response.json();
    element.innerHTML = data.updatedAt;
})();

Example Fetch PUT request at https://stackblitz.com/edit/fetch-http-put-request-examples?file=put-request-async-await.js


PUT request using fetch with error handling

This sends a PUT request with fetch to an invalid url on the api then writes the error message to the parent of the #put-request-error-handling .date-updated element and logs the error to the console.

// PUT request using fetch with error handling
const element = document.querySelector('#put-request-error-handling .date-updated');
const requestOptions = {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ title: 'Fetch PUT Request Example' })
};
fetch('https://reqres.in/invalid-url', requestOptions)
    .then(async response => {
        const isJson = response.headers.get('content-type')?.includes('application/json');
        const data = isJson && await response.json();

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        element.innerHTML = data.updatedAt;
    })
    .catch(error => {
        element.parentElement.innerHTML = `Error: ${error}`;
        console.error('There was an error!', error);
    });

Example Fetch PUT request at https://stackblitz.com/edit/fetch-http-put-request-examples?file=put-request-error-handling.js


PUT request using fetch with set HTTP headers

This sends the same PUT request again using fetch with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.

// PUT request using fetch with set headers
const element = document.querySelector('#put-request-set-headers .date-updated');
const requestOptions = {
    method: 'PUT',
    headers: { 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my-token',
        'My-Custom-Header': 'foobar'
    },
    body: JSON.stringify({ title: 'Fetch PUT Request Example' })
};
fetch('https://reqres.in/api/articles/1', requestOptions)
    .then(response => response.json())
    .then(data => element.innerHTML = data.updatedAt);

Example Fetch PUT request at https://stackblitz.com/edit/fetch-http-put-request-examples?file=put-request-set-headers.js

 


Need Some Fetch Help?

Search fiverr for freelance Fetch developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by