The fetch() Method
This method is used to collect data from any API that responds to the request of a client in the form of JSON or XML. The syntax of the fetch method is pretty simple it takes only one mandatory argument and one optional parameter as
- URL: The URL of the API to reach and ask for a response in the form of JSON or XML
- Options: Optional parameters that help us change the request from “get” to “post” and other variants
- Note: The fetch method returns a promise
To test out the fetch() method to fetch data from an API you need a dummy API or a mock API. For this purpose, we are using the dummy API provided by Req|Res with the URL “https://reqres.in/api/products/3”.
Next up, we need a dummy HTML page with some basic elements inside it. For this example, we used the following lines in the HTML:
This should give us the following webpage:
Then we define an async function to get the data from the API using the URL we just stored with the following lines:
What we are doing in this code is that we are waiting for a promise from the fetch(URL) and storing that promise inside the response variable.
Once we get the promise, we need to convert it into the JSON format using the response.json(). Since response.json() is also a promise that returns data, we use the keyword await.
Lastly, we are printing out the data fetched from the API using the console log function.
Now, all we need to do is to call this async function and pass in the URL of the API with the following line:
The complete code snippet is:
If you run this web page and head over to the console in the browser’s developer tools, you will see the following output: