This article will walk you though setting up a basic response using the fetch API.
What is Fetch API?
According to MDN Web Docs, Fetch API simply provides an interface for fetching resources. It provides a more powerful feature set over the traditional XMLHttpRequest, and it is easier to use. The fetch() method
- accepts one mandatory argument (this should be the path to your API or JSON resource)
- returns a promise (the promise will resolve to the JSON response)
Because of its simplicity, fetch has quickly become the common goto method for consuming responses from API endpoints, or in the case of the example covered here, a simple JSON response from a static file.
Writing the JSON File
- You Don’t know JS – Book Series (Kyle Simpson): https://github.com/getify/You-Dont-Know-JS
- Shaping Up with Angular.JS (Code School): https://www.codeschool.com/courses/shaping-up-with-angular-js
- HTML/JS: Making webpages interactive with jQuery (Khan Academy): https://www.khanacademy.org/computing/computer-programming/html-js-jquery
- JQuery AJAX (W3 Schools): http://www.w3schools.com/jquery/jquery_ajax_intro.asp
- JQuery API Documentation (jQuery): https://api.jquery.com/
Each of the entries include name, provider (or author), and URL of the resource. Copy and paste the JSON code below into a text file and call it resources.json. Keep in mind in real life we would most likely be hitting an API endpoint with our fetch call, however for the sake of keeping this simple we are using a static file.
Once you’re done, be sure to check your work using the free JSON Lint service.
Let’s break the code down.
- document.querySelector is used to manage a click event from a button with an id of #retrieve-resources that will be used to grab the JSON
- a variable called displayResources is set to the #display-resources id in the HTML file (see below for HTML code)
- a temporary message, “Loading data from JSON source…” is placed in displayResources.textcontent
- fetch() is used with the mandatory parameter of the MyJson file and returns a response
- the result is then parsed into a variable called output using a for loop to iterate the JSON records
- output is finally appended to displayResources.innerHtml
Writing the HTML
The code above uses Bootstrap and includes the retrieve-resources and display-resources ids needed for the click event and placeholder for the data retrieved from JSON. Once a user clicks the retrieve-resources link, the JS code above will begin.
That’s it. This was a pretty basic tutorial, but it should be enough to get you up and running with basic requests using fetch(). For more information, be sure to check out the Fetch API documentation.
Image Credits: Photo by Wyatt Ryan on Unsplash.