Got JSON, Now What?
13 Oct 2022 - B-rad
There comes a time in every developers life where you have to GET some data from an API endpoint, display it ever so lovingly on the world wide web and not freak out about it. We will use the Star Wars API and display that to the browser. I promise this article will be a blast. The act of sending and receiving data over the web is known as an AJAX call. This allows browsers to send and retrieve information, that developers can manipulate to do many different things. There are five main HTTP methods to do this, GET, POST, PUT, PATCH, and DELETE. If you need a refresher the MDN docs breaks down HTTP methods. This article will only focus on GET. According to the MDN docs the GET method requests a representation of the specified resource. Requests using GET should only retrieve data. This is a READ ONLY method and we have no risks of corrupting or mutating data. So let’s dive into using the Javascript Fetch() API to fetch some star wars data. We want to get all of the Star Wars Movies according to the Star Wars API Docs we can call this:
Fetch will return a Promise. In order to do anything with what we fetched it needs to be written in a .then call which returns a promise:
I wanted to console.log the response to show that fetch is responding back with an object..
Well this is interesting.. How do we now get the data. We know from the Star Wars API docs that JSON is the standard data format provided by SWAPI by default. The Fetch .json method will convert to JSON!!
Oh Joy! We got our list of films. Take a peek in the console.
Oh No! Did we do something wrong?!? Wait a second I see some movies in a field called results! Lets try this again..
Amazing and congrats! We are getting our films!! Now what?? We could do a forEach() on that Array and display it or go next level. The Star Wars API gives us the ability to use search with our params. Next article we will wire up a form, use the user input as a search param, use that forEach() on results and attempt to display an GET request from the Star Wars API! Until the next time we kick it together…