Developers often have to retrieve data from their own API or third-party API. This article talks about using your browser’s Fetch API to GET some data from an endpoint.
What is the Fetch API?
The Fetch API is an interface that allows us to make HTTP Requests to a server from a web browser like Chrome or Firefox. A GET request hits an endpoint on a server then returns a response with data from that endpoint so you can read it.
Types of requests
The GET HTTP Request is only one type of request you can make to a server. Other types of requests are POST, PUT, and DELETE. These requests make a CRUD application. It is where we can Create (POST), Read (GET), Update (PUT), and Destroy (DELETE) data in our database.
In addition, we can hit endpoints on third party APIs. Depending on the API, you’ll only be allowed to perform certain requests, mainly to keep their data immutable, so you won’t be able to do those requests that manipulate data, you’ll only be able to read it.
How does Fetch API work?
The Fetch API uses a Promise-based system of communication. As a reminder, Promises are asynchronous functions that encapsulate logic into its block of code and returns a response that determines if the promise was resolved or rejected.
As users of the Fetch API, we don’t need to actually write the promise logic. We just have to use it to send a request and the Fetch API returns a promise under the hood. Here’s the basic syntax so we can get the response:
promise.then(response).then(json).catch(error);
The promise is the actual asynchronous request. The fetch()
method is available in the global scope and is passed the endpoint we want to make the HTTP request to.
let promise = fetch("https://swapi.dev/api/films/1");
After the request, we can either use promise syntax with then and catch or use async/await function to get the server’s response.
Promise syntax
promise.then(response => { if (response.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + response.status); return; } response.json().then(data => { console.log(data); }).catch(error => { console.log(error.message); }) })
Here we take the promise then wait for a response. When we get a response, if the status code is anything other than 200, we log an error code to our console and terminate the function.
Otherwise, to make the response readable so our frontend website can use it, we change it to JavaScript Object Notation (JSON) object with the json()
method. We want this to evaluate first before moving on, so we chain on a promise to the previous promise.
Once that is evaluated we can then log what was passed in to see it on our console. If you are following along, you should get something like this:
{ title: 'A New Hope', episode_id: 4, opening_crawl: 'It is a period of civil war.\r\n' + 'Rebel spaceships, striking\r\n' + 'from a hidden base, have won\r\n' + 'their first victory against\r\n' + 'the evil Galactic Empire.\r\n' + '\r\n' + 'During the battle, Rebel\r\n' + 'spies managed to steal secret\r\n' + "plans to the Empire's\r\n" + 'ultimate weapon, the DEATH\r\n' + 'STAR, an armored space\r\n' + 'station with enough power\r\n' + 'to destroy an entire planet.\r\n' + '\r\n' + "Pursued by the Empire's\r\n" + 'sinister agents, Princess\r\n' + 'Leia races home aboard her\r\n' + 'starship, custodian of the\r\n' + 'stolen plans that can save her\r\n' + 'people and restore\r\n' + 'freedom to the galaxy....', director: 'George Lucas', producer: 'Gary Kurtz, Rick McCallum', release_date: '1977-05-25', characters: [ 'http://swapi.dev/api/people/1/', 'http://swapi.dev/api/people/2/', 'http://swapi.dev/api/people/3/', 'http://swapi.dev/api/people/4/', 'http://swapi.dev/api/people/5/', 'http://swapi.dev/api/people/6/', 'http://swapi.dev/api/people/7/', 'http://swapi.dev/api/people/8/', 'http://swapi.dev/api/people/9/', 'http://swapi.dev/api/people/10/', 'http://swapi.dev/api/people/12/', 'http://swapi.dev/api/people/13/', 'http://swapi.dev/api/people/14/', 'http://swapi.dev/api/people/15/', 'http://swapi.dev/api/people/16/', 'http://swapi.dev/api/people/18/', 'http://swapi.dev/api/people/19/', 'http://swapi.dev/api/people/81/' ], planets: [ 'http://swapi.dev/api/planets/1/', 'http://swapi.dev/api/planets/2/', 'http://swapi.dev/api/planets/3/' ], starships: [ 'http://swapi.dev/api/starships/2/', 'http://swapi.dev/api/starships/3/', 'http://swapi.dev/api/starships/5/', 'http://swapi.dev/api/starships/9/', 'http://swapi.dev/api/starships/10/', 'http://swapi.dev/api/starships/11/', 'http://swapi.dev/api/starships/12/', 'http://swapi.dev/api/starships/13/' ], vehicles: [ 'http://swapi.dev/api/vehicles/4/', 'http://swapi.dev/api/vehicles/6/', 'http://swapi.dev/api/vehicles/7/', 'http://swapi.dev/api/vehicles/8/' ], species: [ 'http://swapi.dev/api/species/1/', 'http://swapi.dev/api/species/2/', 'http://swapi.dev/api/species/3/', 'http://swapi.dev/api/species/4/', 'http://swapi.dev/api/species/5/' ], created: '2014-12-10T14:23:31.880000Z', edited: '2014-12-20T19:49:45.256000Z', url: 'http://swapi.dev/api/films/1/' }
If we get this information on the frontend, we can use it to populate cards or a table or however we would like to display it.
Async/Await
We can also use the async/await function to log the same result.
let getRequest = async () => { try { let fetched = await fetch("http://swapi.dev/api/films/1"); if(fetched) { let read = await fetched.json() console.log(read); return read; } } catch (error) { throw new Error(error.message); } } getRequest()
The async
keyword tells us that some portion of that function will be asynchronous. When we come to the await keyword, execution of the script pauses until that line of code is evaluated.
We have two await
statements in this function, comparable to the two then()
statements we had in the promise logic. One statement waits for the fetching to happen at the URL we passed in, and the other waits until the fetched information has been parsed into JSON. We use try/catch
to catch any errors we may get if something unusual comes back from the responses.
Final notes
For the Fetch API to work in the node environment (i.e. if you are using an IDE like Visual Studio Code), you will need to yarn add
or npm install node-fetch
, as fetch only works in the browser environment.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.