DEV Community

Cover image for How to call an API with fetch()
Graham Fleming
Graham Fleming

Posted on

How to call an API with fetch()

The Fetch API provides an interface for fetching resources using the Request and Response objects, allowing them to be used anywhere that might require you to generate a response programmatically. For making a request and fetching a resource, use the fetch() method.

First, we would need to define that we are using the fetch() method and pass in the URL as a parameter.

fetch("YOUR_URL")
Enter fullscreen mode Exit fullscreen mode

After the URL is passed in, the .then() method will give you the ability to work with the data object that is returned. Use the data response to work with the data that is returned from the call.

    .then(response => {
        // handle the response
        console.log(data);
    })
Enter fullscreen mode Exit fullscreen mode

In the case of errors, using the .catch() method we are able to see the output in our console, and handle any errors that are incoming during the fetch() call.

    .catch(error => {
        // handle the error
        console.log(error );
    });
Enter fullscreen mode Exit fullscreen mode

With the basics of calling an API and dealing with the data response you can use this information to expand on the different types of data that you can work with, adding more functionality and automation to your applications.

fetch("YOUR_URL")
    .then(response => {
        // handle the response
        console.log(data);
    })
    .catch(error => {
        // handle the error
        console.log(error );
    });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)