Fetch

Call a REST API from JavaScript with the built-in fetch function: GET, POST, PUT and DELETE, checking response.ok before using the result.

Apprentice · JavaScript · REST API · Updated

By

Both Fetch and the Axios library serve the same purpose, which is to give us the ability to load data that isn't already in memory. Let's compare them.

The Fetch API is built directly into JavaScript, so there is no dependency on an external library.

Below are examples for the various REST CRUD operations.

GET

Note that we check response.ok, which is true for any success status (200 to 299). If it is false, we throw an error so the caller knows the request failed.

const baseUrl = 'http://localhost:8080/api/categories';

function getAllCategories()
{
    return fetch(baseUrl).then(response => {
        if (!response.ok) {
            throw new Error(response.statusText);
        }
        return response.json();
    });
}

POST

Note that we must modify the request to change the method to POST. We must also specify the content type, and add the category to the body of the request.

const baseUrl = 'http://localhost:8080/api/categories';

function addNewCategory(category)
{
    return fetch(baseUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(category)
    }).then(response => {
        if (!response.ok) {
            throw new Error(response.statusText);
        }
        return response.json();
    });
}

PUT

Note that like in the POST method, we must modify the request header and body. We also need to change the URL to include the ID.

const baseUrl = 'http://localhost:8080/api/categories';

function updateCategory(id, category)
{
    const url = `${baseUrl}/${id}`;
    return fetch(url, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(category)
    }).then(response => {
        if (!response.ok) {
            throw new Error(response.statusText);
        }
    });
}

DELETE

Note that the DELETE method does not have a body.

const baseUrl = 'http://localhost:8080/api/categories';

function deleteCategory(id)
{
    const url = `${baseUrl}/${id}`;
    return fetch(url, {
        method: 'DELETE'
    }).then(response => {
        if (!response.ok) {
            throw new Error(response.statusText);
        }
    });
}

Do it: get one category by its id

The categories page needs one category at a time: the one a shopper picked. The lesson's getAllCategories asks for the whole list. Write the function that asks for one category, by its id, the same way.

The practice box has no real API, so it answers fetch itself, the way your categories API would:

The request The API answers
GET http://localhost:8080/api/categories/2 200, with { "categoryId": 2, "categoryName": "Condiments", "description": "Sauces and spreads" }
GET http://localhost:8080/api/categories/8 200, with { "categoryId": 8, "categoryName": "Seafood", "description": "Seaweed and fish" }
GET http://localhost:8080/api/categories/300 404: there's no such category

The function gets one value:

  • id: the category's id, a number, such as 8.

For example, getCategory(8) sends GET http://localhost:8080/api/categories/8. The API answers 200, and the promise the function returns gives back the category:

{ categoryId: 8, categoryName: 'Seafood', description: 'Seaweed and fish' }

Your job: write the function getCategory(id) with fetch and .then, as this lesson does.

  • Send a GET to baseUrl, a slash, then the id: http://localhost:8080/api/categories/8.
  • Return the promise, so the caller can wait for the category.
  • When the response is OK (any 2xx), the promise gives back the category from the response's JSON.
  • When it isn't OK, throw an Error whose message is The API answered <the status>, such as The API answered 404.

Practiced live on the lesson page: write the JavaScript right there and check it.

Cheat sheets