Fetch API Tutorial for Beginners: How to Use Fetch API

Fetch API Tutorial for Beginners: How to Use Fetch API

Use the button in the demo to display the content.

Notice the resource that I’m loading in the CodePen demo:

fetch('https://codepen.io/impressivewebs/pen/KKVopdL.html')

That’s a separate CodePen file that I created. CodePen allows you to append .html, .css, or .js to any CodePen URL to request that pen’s HTML, CSS, or JavaScript content, which is useful when using Ajax or Fetch API requests so you’re not hampered by cross-origin limitations. So that’s pretty useful! Try changing the URL to request the CSS or JavaScript (i.e. using KKVopdL.css or KKVopdL.js at the end of the URL) to see the results.

Now that you’ve seen a basic Fetch API example, I’ll introduce you to the different parts of that request.

The resource location parameter

As already discussed, the only argument that’s required when using the fetch() method is the resource. This will usually be a direct URL to the resource being requested, but it can also be a Request object. All the examples I’m going to use in this tutorial will incorporate a direct URL reference, which is the most common way you’ll see fetch() used.

Let’s look at some examples using a direct URL to various free APIs as the requested resources (i.e. the resources I want to ‘fetch’).

Here’s a request for some basketball data:

fetch('https://www.balldontlie.io/api/v1/teams/28')

Here’s a request for JavaScript jobs in the New York area:

fetch('https://jobs.github.com/positions.json?description=javascript&location=new+york')

And here’s a request for a random beer:

fetch('https://api.punkapi.com/v2/beers/random')

Any of those URLs can be viewed directly in your browser and they all involve resources from various free APIs. You can try out other free APIs by visiting this GitHub repo. Just make sure you choose one that doesn’t require authentication (i.e. it has “No” under the “Auth” column).

The returned Promises in a Fetch API request

Every fetch() method begins the process of requesting a resource and returns a Promise. A detailed discussion of JavaScript Promises is out of the scope of this tutorial, but I’ll cover enough for you to be able to work with fetch().

According to MDN, a Promise is an object that:

[…] represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

If I were to convert a Promise into a couple of English sentences, it might look like this:

Do something. When that “something” is finished, do something

[…]

 



This article was written by Louis Lazaris and originally published on CodeinWP.

Disclosure: Some of the links in this post are "affiliate links." This means if you click on the link and purchase the product, We may receive an affiliate commission.

Leave a Comment

You have to agree to the comment policy.

Scroll to Top