Make fetch GET, POST, PUT and DELETE requests in a single line

Reading Time: 2 minutes 🕑

Last updated: April 8, 2022.

Do you use JavaScript’s Fetch API for making HTTP requests?

If so, you may have noticed that it can involve writing a lot of code.

But you can also make fetch GET, POST, PUT and DELETE requests using the fetch in a single line by creating a custom fetch function.

Creating a custom fetch function

The custom function works by making a fetch request. But instead of the (i) API endpoint, (ii) request type and (iii) any data to be sent being hardcoded, these are dynamically inserted by the arguments inserted into the custom function.

Several if statements are used to determine if the request is a GET, POST, PUT or DELETE request. The type of fetch request made (e.g. whether the data object sent has a body property containing sent data) varies depending upon this outcome.

The custom fetch function

/* Custom fetch function that returns a promise */

function myFetch(url, type, data) {

    /* GET */
    if (type === "GET") {
    return fetch(url, {
    method: type,
    headers: {
        'Content-type': 'application/json'
    }
    })
    .then(res => {
        if (res.ok) { console.log("HTTP request successful") }
        else { console.log("HTTP request unsuccessful") }
        return res
    })
    .then(res => res.json())
    .then(data => data)
    .catch(error => error)
    }
 
    /* DELETE */
    if (type === "DELETE") {
    return fetch(url, {
    method: type,
    headers: {
        'Content-type': 'application/json'
    }
    })
    .then(res => {
        if (res.ok) { console.log("HTTP request successful") }
        else { console.log("HTTP request unsuccessful") }
        return res
    })
    .catch(error => error)
    }
 
    /* POST or PUT */
    if (type === "POST" | type === "PUT") {
    return fetch(url, {
    method: type,
    headers: {
        'Content-type': 'application/json'
    },
    body: JSON.stringify(data)
    })
    .then(res => {
        if (res.ok) { console.log("HTTP request successful") }
        else { console.log("HTTP request unsuccessful") }
        return res
    })
    .then(res => res.json())
    .then(data => data)
    .catch(error => error)
    }
}

Example usage

Assuming you have defined the myFetch function in your code, you can now make GET, POST, PUT and DELETE requests by simply changing the argument passed into it on a single line:

/* Example HTTP requests using the custom fetch function */

// GET:
myFetch('https://reqres.in/api/users/2', "GET").then(res => console.log(res));
// POST:
myFetch('https://reqres.in/api/users', "POST", { name: "John"} ).then(res => console.log(res));
// PUT:
myFetch('https://reqres.in/api/users/2', "PUT", { name: "Sally"} ).then(res => console.log(res));
// DELETE:
myFetch('https://reqres.in/api/users/2', "DELETE").then(res => console.log(res));

Related links

MDN Mozilla Web Docs: Using the Fetch API