The API Series - Part 2: The REST API, fetch(), and AXIOS
Tags: tutorial, codenewbie
Published: 2021-04-29 13:41:05

## Introduction

In this tutorial, you'll learn of different tooling options that allow you to make requests from APIs, you'll learn how to retrieve data from a REST API, how to submit data to a REST API, and you'll learn how to use a developer key in the case that the API requires it.


## Prerequisites

Some familiarity with JavaScript.


## Getting Started With the REST API

RESTful APIs communicate using HTTP/HTTPS. So part of your request will include what looks to be a website URL. These URLs are found in the API documentation, and they are the access points for the data or functionality you need. As an example, the following URL is part of a [Dev.to API](https://docs.forem.com/api/) request to get the blog articles for a user named "vwc-user1": `https://dev.to/api/articles?username=vwc-user1`

The API may also display the format of all the data associated within this URL. It looks like this:

![DEV API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xbuohgqt7jfo8n87f8sl.JPG)

This list and data is stored as JSON. JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. But without formatting and parsing, it's not very useful to us. If you submit the URL to the browser using your username instead of "vwc-user1," you'll only see a jumble of data. 

To get our data in a way that's useful to use, we'll need to add in some tooling designed just for this purpose.

## Fetch()

Per the MDN Documentation:

"The [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) method that provides an easy, logical way to fetch resources asynchronously across the network."

The Fetch API is something that is already available to you. That's because the Fetch API is part of the browser software and certain Fetch objects are part of the Javascript language. It will just work.

Before going further, you'll need to know the HTTP verbs. Below is a list of these verbs and what function they do when they are declared as your request method:

- POST: Creates and inserts new data to API
- GET: Receive something from the API
- DELETE: Delete data
- PUT*: Updates/replaces existing data
- PATCH*: Updates/modifies existing data

*To understand the differences between PUT and PATCH, visit [PATCH - HTTP | Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)

In the sections below, we'll use the fetch() method to make a GET and POST request.

## GET

Let's say that we found our API endpoint already. This is the part that looks like a website URL:

```html
http://some-site.com//some.json
```

Here is an example of a Fetch request to that same endpoint:

```javascript
fetch('http://some-site.com//some.json', {
	method: 'get'
})
  .then(function(response) {
    return response.text();
  })
  .then(function(text) {
    console.log('Request successful', text);
  })
  .catch(function(error) {
    log('Request failed', error)
  });
```

First we invoke the [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) method, passing it the URL shared above. Within the Fetch() method is also included the method type of "get" as an option within the Fetch() request. This is wrapped in curly brackets. The GET method retrieves data from the API. Other methods, which you'll see shortly, can send data to a database associated with the API.
Second, we see a .then() chained to the fetch() method. [then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) is part of JavaScript's Promises object. So once our Fetch() method delivers the desired resource, the promise is officially met and the Then() method executes a function. In this case, the function takes the response from API request, which Fetch() handles by returning as an object called "[response](https://developer.mozilla.org/en-US/docs/Web/API/Response)," and turns this raw data into text using the [Text()](https://developer.mozilla.org/en-US/docs/Web/API/Body/text) method.

>Oftentimes the [json()](https://developer.mozilla.org/en->US/docs/Web/API/Body/json) method is used in place of the Text() >method, and that's to convert the raw data within the response >object into a json object.

Once the request is turned to text, the next promise in our chain is met and the second Then() method executes a function. In this case, the Text() method returns a "text" object (an object created by this particular method) and logs the string "Request successful" and the text object to the console.

The [Catch()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) method is designed specifically for error handling and will execute a function that logs an error message when the previous promises are not met.


## POST

There are times when we want to send data to a database using an API. For example, the Twitter API allows developers to post tweets through API requests. When you send new data, this is considered the POST method. When you update existing data, this is what's known as a PUT method.

In the example below, we are going to POST the user object to the API endpoint of:

```html
https://example-api.com/post-user
```

```javascript
// this is our user object that we're passing to the API via POST request
let user = {
  email: "example@email.com",
  firstName: "John", 
  lastName: "Doe"
}

// this is our POST request

fetch('https://example-api.com/post-user', {
  method: "POST",
  headers: {
    'X-API-KEY': 'my-apikey-string',
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  body: JSON.stringify(user),
})
.then(response => response.json()) 
.then(json => console.log(json));
.catch(err => console.log(err));
```

In the above example, we set the fetch method as POST to let the API know that we are passing it new data. The headers section allows us to include more instructions and information with our request. You'll notice an API X-API-Key included in the header. This allows the API to authenticate our request. In this case, we would have registered with www.example-api.com to receive an API key. When they see a request from our unique API key, they'll know it's coming from the registered user with that key.

Within the header section, you'll also notice "Accept" and "Content-Type." In this example, we're letting the API know to accept and expect to receive data in the "application/json" format. The application documentation should let you know how the API expects to receive data.

The body section includes the data we are passing to the API. In this example, we're sending the user object defined in the first part of the above code block. But for the API to understand the data passed to it, we must first turn our user object into a string using the [JSON.stringify() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). We must convert the object to a JSON string because Fetch() does not recognize JavaScript objects as a valid body response. This is a quirk of the Fetch API that developers must know when using Fetch()

After the body is defined, we then go into the chain of promises. Starting with:

```javascript
.then(response => response.json())
```

The above code waits for a response. And when it receives a response as JSON, it uses the [json() method](https://developer.mozilla.org/en-US/docs/Web/API/Body/json) to parse the response back to the JavaScript object format.

The second link in our promise chain looks like this:

```javascript
.then(json => console.log(json));
```

The above code takes the JavaScript object return in the previous promise link and logs this value to the console. This should send you the data you sent, and it may include an id and time stamp that was generated by the API as the data was posted to the database.
The final link in the promise chain alerts us of any errors in the process by logging errors to the console:

```javascript
.catch(err => console.log(err));
```

This break down of the Fetch API has covered some of the basics. As you grow as a developer, you'll find use cases for more of its functionality. As always, the Mozilla Development Network is the best starting place to read the documentation.


## AXIOS

Axios is a popular library used to make HTTP requests to RESTful APIs. The library replaces the functionality of the Fetch API, and adds some improvements. For instance, the Axios library will handle some of the data type conversions for you, so you're not always using JSON.stringify or relying on the text() method.

Consider the similarities and differences of the Axios HTTP requests below:

```javascript
// Send a POST request

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Blue',
    lastName: 'Falcon'
  }
})
  .then(response => {
    console.log(response);
  })
  .catch(err => {
    console.log(err);
})
```

```javascript
// Send a GET request

axios.get('/user', {
    params: {
      USER_ID: XYZ543
    }
  })
  .then(response => {
    console.log(response);
  })
  .catch(err => {
    console.log(err);
})
```

In the above code, you'll see that Axios differs from Fetch in that we don't have to change the format of the response. This reduces some complexity for us as developers, and makes the code easier to read.

Axios can be installed via your [package manager](https://en.wikipedia.org/wiki/Package_manager) of choice or accessed through a CDN, which is when you gain access to Axios by linking your HTML document with a script tag provided by Axios.

To learn more about Axios, visit their GitHub page at: [https://github.com/axios/axios](https://github.com/axios/axios)