Axios Get

Posted on  by admin

As a developer, you will be required to work with APIs, whether internal or third party.

They are needed to bring different applications and services together to build a well-defined application. Communicating with APIs effectively is an essential factor in your application’s performance, scalability, and reliability.

Making GET Requests Using axios

Over the years, Axios has become the most common and popular HTTP client, and with over 90k stars on GitHub, it has one of the largest developer communities behind it. In this article, we will learn how to make GET requests in Axios.

I will demonstrate how you can use Axios GET to make requests to public APIs like The Rick and Morty API and Final Space API, and how you can make concurrent GET requests and handle errors.

How to Make a Request Using Axios

If you want to jump right into the code, check out the GitHub repo here.

Working knowledge of HTML, CSS, and JavaScript.

Node.js and npm installed on your local dev machine.

Any code editor of your choice. Axios is a Promise-based HTTP client for the browser and Node.

How to Make a POST Request Using axios

Let’s break down this definition to understand what Axios does.

First, HTTP stands for Hypertext Transfer Protocol.

It is a client-server protocol for fetching resources such as HTML documents.

How to install Axios in a Node.js project

“Client” is the user-agent that acts on behalf of the user, and initiates the requests for resources.

  • Web browsers such as Google Chrome are a popular example of a client.
  • A Promise-based client returns promises.
  • Axios is isomorphic, which means it can run in the browser and Node.js with the same code.
  • When used on the server side, it uses Node’s native http module, whereas, on the client side, it uses XMLHttpRequests.
  • On the client side, Axios also supports protection against XSRF.
  • An HTTP GET request is used to request a specified resource from a server.

What is the Axios GET method?

These requests do not contain any payload with them, i.e., the request doesn’t have any content.

Axios GET is the method to make HTTP GET requests using the Axios library.

In this section, we will create the sample app that uses Axios to fetch data using the GET request.

To begin, run the following command in the terminal:.

The command npm init -y creates a package.json similar to the one below in your project’s folder:.

Conclusion

The last command, npm install axios, installs the axios package as a dependency in your project.

There will be a new package-lock.json file and a node_modules folder in the project folder.

The package.json file will also update and will look similar to this:. You can also install axios using yarn or bower, like so:.

Simple GET request using axios

Next, create a file named index.js where you will write the code to fetch resources using the GET requests. Run the following command in the project’s root to create the index.js file:.

Run the following command in your project’s root directory to install nodemon as a dev dependency.

Nodemon is an excellent local development tool that automatically restarts the Node application whenever it detects a file change in the directory:.

How to make Axios GET requests with query parameters

Modify "scripts" in your package.json, like this:. Your package.json should look like this:. Run the following command to start your Node application:.

You’ll see the following message in your terminal once it has started:.

Update the index.js file to include the following code:. You will notice that nodemon detects the file change, restarts the application, and shows the following message in the terminal:.

How to make concurrent requests with Axios

Finally, you can remove the console.log() code from the index.js file. In this section, we will see how to import and use Axios to make GET requests to the Final Space API in order to fetch data.

  • Update the index.js file to import the axios package using the require function.
  • Node follows the CommonJS module system, and you can use modules present in separate files using the inbuilt require function:.
  • Now, you can use axios. to initiate any request, such as a GET request.
  • Add the following code to the index.file.
  • The following code fetched two characters from the Final Space API Characters endpoint:.

You will see a lengthy response in the terminal similar to this (the following response is truncated):.

GET request using axios with error handling

The above implementation of axios.get() is the default and most popular way to make a GET request in the codebase.

Axios also provides shorthand methods for performing different requests, like so:.

Here, you pass a request object with the necessary configuration of the request as the argument to the axios.get() method.

While there are several options that you can pass to this request object, here are the most common and popular ones:.

baseUrl – When specified, this baseUrl is prepended to url unless the url is absolute.

Error handling in Axios

headers – An object with custom headers to be sent with the requestor, like headers: {'X-Requested-With': 'XMLHttpRequest'},.

params – An object whose key/value pairs are appended to the url as query strings. auth – An object with a username and password to authenticate an HTTP Basic auth request.

How to make Axios GET requests with an API key

The above Axios request can be rewritten as the following:. This object must include the url property to fetch the data.

Requests default to the GET request when the method property is not specified.

You can also pass a responseType option, which indicates the type of data that will be returned by the server to the request config object (set to json by default).

The options Parameter

For example, you can rewrite the above code like so:.

The responseType option can be set to arraybuffer, document, blob, text, or stream. It is essential to set the responseType option when the returned response or data is not in JSON format.

For example, the following code fetches a nature image from Unsplash as a Node stream. You can then use the createWriteStream() of the inbuilt fs module and write the fetched stream in a file.

LogRocket: Full visibility into your web apps

The following code creates a file named nature.jpg in your project folder:.

You can also use the popular async/await instead of promises.

For example, you can rewrite the above code by placing it inside an async function:. Finally, you can get the data from the response body using destructuring assignments:.

In this section, we will learn how to make Axios GET requests with query parameters.

First, add the following code to the index.js file:. In the code above, we use the URLSearchParams method from the url module to convert an object with query parameters as key/value pairs in the required URL query format.

Prerequisites

Here is what the params will look like:. And here is what the returned data looks like:.

One often needs to authenticate requests by passing an API key along with the request.

In this section, we will learn how to use an API key with Axios to make requests.

We will use the NASA API as an example. First, navigate to https://api.nasa.gov/ in the browser and fill the required fields to generate an API key.

Click on the Signup button.

On the next page, your API key will be shown to you. The API keys should be kept hidden from the public and stored as environment variables inside a .env file.

How to make GET requests using Axios

dotenv is a popular npm library used to load environment variables from the .env file.

Run the following command to install the dotenv package:.

Next, create a new file named .env by running the following command:. Paste the NASA API key into the .env file as shown below:.

Now, add the following code to the index.js file to fetch data from the NASA API:.

In the above code, we import the dotenv package and use the API key in the URL as a query parameter. You will need to restart your application, so hit CTRL+C in the terminal and run the command npm run dev to start the Node application.

Sending Headers Using axios

You will see a response similar to this from the NASA API:. You can also use the params option of the request config to make the same request:.

You can also authenticate requests with other HTTP authentication methods like Bearer authentication by passing the Bearer Token in the Authorization header.

You may need to make concurrent requests to multiple endpoints.

Conclusion

In this section, we will learn how you can use the axios.all() method to make multiple requests.

To begin, add the following code to the index.js file:. Here, we pass an array of axios.get() requests in the axios.all() method, then map over the endpoints array to create an array of axios.get() requests, which is then resolved by the axios.all() method.

The response order is the same as the order of the requests in the axios.all() method:.

GET request using axios with set HTTP headers

In this section, we will discuss how to handle errors with Axios.

The most common way is to chain a .catch() method with the axios.get() to catch any errors that may occur.

Add the following code to the index.js file:.

In the code above, we are trying to fetch a character from The Rick and Morty API whose id is -1, and because there is no such character with a negative id, this request will result in an error.

How to Install Axios

The above catch block consoles any error that may occur.

This error object is quite large, and you may not always display everything, so you can be selective about what to log to the error message.

Installing axios from npm

You can also handle errors based on their types.

Add the following code to the index.js file:.

If the error occurred on the server side, then the error object will contain a response property that can be used to access the error’s status, headers, and other details.

If the request was made and no response was received, then the error object will contain the request property XMLHttpRequest in the browser, and an instance of http.ClientRequest in Node.

If an error occurred while making the request, then error.message will indicate such errors.