Call a REST API from JavaScript

How to call a REST API from JavaScript in 5 minutes โšก

1. Create a REST API

So to get started first we need an API to call. If you already have an API to use you can skip forward to the next step. Using the form below you can quickly set up a mock JSON API that we will use in this tutorial. Simply paste some JSON into the text field and press Create API to get started. In this tutorial we will use the following response body that you can use if you are out of ideas:

{ "fruits": [ "dragonfruit", "pineapple", "banana", "watermelon" ] }

Free API Editor

If you want to create a simple API for testing purposes, simply enter a response body below and press Create API to get your custom API URL.

mocki logo

Use Mocki to create a fully fledged mock API. Sign up for a 7-day free trial and get:

  • Multiple API endpoints
  • Monitoring dashboard
  • Simulated errors and delays
  • Generated test data
Sign Up (Free Trial)

When you have pressed the button you should get a URL to your API. Make sure to save it so that we can use it later on.

Note: If you want to use more advanced features such as setting response headers, adding multiple endpoints and much more simply sign up here to create your mock API. If you want to create a real API with dynamic responses we recommend using a SaaS Boilerplate.

2. Getting started ๐Ÿš€

To get started we need to create a file that we can write some code in. Create a new file in your favorite text editor, add the code below and save it as index.html.

<pre id="data"></pre>

<script>
// Our JavaScript goes here
</script>

3. Use fetch to call the API ๐Ÿ•

In JavaScript the easiest way to call an API through HTTP is to use the fetch library. This is included in all major browsers. Let’s edit our index.html to use it!

The following code will execute a GET call to our API and show the result inside the <pre> tag. Open your index.html file in Chrome to check out the result.

<pre id="data"></pre>

<script>

fetch('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8')
    .then(response => response.json())
    .then(json => data.innerHTML = JSON.stringify(json));

</script>

As simple as that! In the next step we will try a POST request.

4. Make a POST request โœ‰๏ธ

A GET request is usually made when fetching data from the API. If we want to create something through an API a POST request is used. We can easily modify our usage of the fetch library to make our request into a POST.

<pre id="data"></pre>

<script>

fetch('https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8', { method: 'POST' } )
    .then(response => response.json())
    .then(json => data.innerHTML = JSON.stringify(json));

</script>