DEV Community

Jimmy Parrish
Jimmy Parrish

Posted on

Making a fetch (GET) request in JavaScript

Learning how to do a fetch request, just like anything in coding, can be confusing at first. I am currently in the first phase of my coding boot camp at Flatiron where I learned, among plenty of other things, how to do a FETCH request.

The fetch() method is a way of retrieving data from an API or database and is available on the global scope. There are actually four different fetch requests, "GET", "POST", "PATCH/PUT", and "DELETE". I'm only going to talk about about "GET". It's like telling the API "I need to get some information from you." Once the data is obtained, it can be added to the DOM.

The fetch() method requires only one parameter which is the URL of the resource that you want to fetch. To set up a fetch request, pass a URL string in as an argument.

Image description

You will need to convert the data to JSON by adding .then() methods. JSON is just an efficient format for sending information over the wire. By converting the data to JSON, this allows the user to easily work with it.

With this standard fetch format, what we expect to happen with the fetched data is expressed after the second .then. In my project, I set up code to display the fetched data on the web page by creating and appending elements (see below). The entire fetch request was built within this function.

Image description

This particular function fetches random dog images from an API and adds them to the DOM once a user "clicks" on a button. I created an event listener in the global scope and used a callback to invoke the function once the button is clicked.

Image description

Fetch can be confusing and frustrating at first, but once you get the hang of it, fetching and manipulating the data is a ton of fun. This is important as you will need to get good at fetching data from a backend if you want to be a front-end developer.

Resource:
“Fetch API - Web Apis: MDN.” Web APIs | MDN,
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Top comments (0)