fetch API. The Fetch API basically allows us to make HTTP requests to web servers. We could use Fetch on its own to make a request to our API and then tackle on the response using a
.then() function, or we could use a cleaner method of wrapping our Fetch in an
async function. Nevertheless, this article is not focused on teaching you how to write
async functions, rather how to use it to make our requests easier with Fetch.
Having talked at length about making requests to an API using Fetch, you may wonder what an API exactly is: In short an API (Application Programming Interface) is any standard interface or endpoint that facilitates connection to a web server. In this article we would be making a simple request to Unsplash API. Unsplash is a web platform that acts as a repository of high quality free images, hence, their API enables us to make requests to their central server for an image, which would in turn make a response to us.
Making a Request:
To get started, quickly scaffold a simple index.html project on your PC. It should look something similar to this:
So at the script section of our project we are going to create two things: a fetch request without the async function as a wrapper and also a fetch request with the wrapper. This way we can get a knowledge of both worlds:
Now looking closely, the searchTerm and the accessKeys are two variables that would help our API below them function optimally. Access Keys are private hence endeavor to keep them hidden!
In fetch without async wrapper above, we use the fetch to make a GET request to a server(Unsplash) via an API, this request is then tackled on using the
.then() method grabs the parsed data and outputs it on our browsers console.
async function too also helps in making asynchronous requests, how so: a response is expected and upon getting the response the data is stored in a constant called – res. Next we await the response to be parsed into a JSON format, after resolving it is passed to a constant – data.