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. Over the years, Axios has become the most common and popular HTTP client, and it has a massive 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.
If you want to jump right into the code, check out the GitHub repo here.
Axios is a Promise-based HTTP client for the browser and Node. 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.
The 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 XMLHttpRequest
objects. On the client side, Axios also supports protection against XSRF.
axios.get()
method?An HTTP GET
request is used to request a specified resource from a server. 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:
mkdir axios-get-examples cd axios-get-examples npm init -y npm install axios
The command npm init -y
creates a package.json
similar to the one below in your project’s folder:
{ "name": "axios-get-examples", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
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:
{ "name": "axios-get-examples", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "axios": "^0.25.0" } }
You can also install axios
using yarn
or bower
, like so:
// Yarn yarn add axios // Bower bower install 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:
touch index.js
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:
npm install -D nodemon
Modify "scripts"
in your package.json
, like this:
"scripts": { "start": "node index.js", "dev": "nodemon index.js" },
Your package.json
should look like this:
{ "name": "axios-get-examples", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js", "dev": "nodemon index.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "axios": "^0.25.0" }, "devDependencies": { "nodemon": "^2.0.15" } }
Run the following command to start your Node application:
npm run dev
You’ll see the following message in your terminal once it has started:
> [email protected] dev > nodemon index.js [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node index.js` [nodemon] clean exit - waiting for changes before restart
Update the index.js
file to include the following code:
// index.js console.log('Hello World!');
You will notice that nodemon
detects the file change, restarts the application, and shows the following message in the terminal:
Hello World! [nodemon] clean exit - waiting for changes before restart
Finally, you can remove the console.log()
code from the index.js
file.
GET
requests using AxiosIn 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:
const axios = require('axios');
Now, you can use axios.<method>
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:
// Axios GET Default axios .get("https://finalspaceapi.com/api/v0/character/?limit=2") .then(function (response) { console.log(response); });
You will see a lengthy response in the terminal similar to this (the following response is truncated):
{ "status": 200, "statusText": "OK", "headers": { "server": "nginx/1.18.0 (Ubuntu)", "date": "Sat, 22 Jan 2022 09:38:29 GMT", "content-type": "application/json; charset=utf-8", "content-length": "2754" }, "config": { "transitional": { "silentJSONParsing": true, "forcedJSONParsing": true, "clarifyTimeoutError": false }, "headers": { "Accept": "application/json, text/plain, */*", "User-Agent": "axios/0.25.0" }, "method": "get", "url": "https://finalspaceapi.com/api/v0/character/?limit=2", "data": undefined }, "data": [ { "id": 1, "name": "Gary Goodspeed", "status": "Alive", "species": "Human", "gender": "Male", "hair": "Blonde", "alias": [ "The Gary (by Lord Commander and Invictus)", "Thunder Bandit(code name)" ], "origin": "Earth", "abilities": [ "Piloting", "Marksmanship", "Hand-to-hand combat", "Weapons: Blasters" ], "img_url": "https://finalspaceapi.com/api/character/avatar/gary_goodspeed.png" }, { "id": 2, "name": "Mooncake", "status": "Unknown", "species": "Mooncake's Species", "gender": "None (referred to as male)", "hair": "None", "alias": ["Specimen E - 351", "Little Buddy"], "origin": "Outer space", "abilities": ["Hovering", "Firing Laser Beams", "Planetary Destruction"], "img_url": "https://finalspaceapi.com/api/character/avatar/mooncake.jpg" } ] }
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:
axios.request(config) axios.get(url[, config])
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 absoluteheaders
– 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 stringsauth
– An object with a username
and password
to authenticate an HTTP Basic auth requestThe above Axios request can be rewritten as the following:
// Using the Request Config axios({ method: "get", url: "https://finalspaceapi.com/api/v0/character/?limit=2", }).then(function (response) { console.log(response.data); });
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).
For example, you can rewrite the above code like so:
// Using the Request Config axios .get("https://finalspaceapi.com/api/v0/character/?limit=2", { responseType: "json", }) .then(function (response) { console.log(response.data); });
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.
The following code creates a file named nature.jpg
in your project folder:
// Axios with responseType - stream // GET request for remote image in node.js const fs = require('fs'); axios({ method: 'get', url: 'https://images.unsplash.com/photo-1642291555390-6a149527b1fa', responseType: 'stream' }) .then(function (response) { // console.log(response.data.pipe); response.data.pipe(fs.createWriteStream('nature.jpg')) });
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:
// Using Asyc/Await async function getCharacters() { const response = await axios.get( "https://finalspaceapi.com/api/v0/character/?limit=2" ); console.log(response.data); } getCharacters();
Finally, you can get the data from the response body using destructuring assignments:
async function getCharacters() { const { data } = await axios.get( "https://finalspaceapi.com/api/v0/character/?limit=2" ); console.log(data); } getCharacters();
GET
requests with query parametersIn this section, we will learn how to make Axios GET
requests with query parameters.
First, add the following code to the index.js
file:
// Axios GET Query Parameters const url = require("url"); const queryParams = { limit: 1, sort: "desc", }; const params = new url.URLSearchParams(queryParams); console.log(params); axios .get(`https://finalspaceapi.com/api/v0/character/?${params}`) .then(function (response) { console.log(response.data); });
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.
Here is what the params
will look like:
URLSearchParams { 'limit' => '1', 'sort' => 'desc' }
And here is what the returned data looks like:
[ { id: 47, name: 'Zargon Tukalishi', status: 'Deceased', species: 'Unknown', gender: 'Male', hair: 'None', alias: [], origin: 'Yarno', abilities: [], img_url: 'https://finalspaceapi.com/api/character/avatar/zargon_tukalishi.jpg' } ]
GET
requests with an API keyOne 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. dotenv is a popular npm library used to load environment variables from the .env
file.
Run the following command to install the dotenv package:
npm install dotenv
Next, create a new file named .env
by running the following command:
touch .env
Paste the NASA API key into the .env
file as shown below:
NASA_API_KEY = IqIxEkPjdl1Dnl9mjTKU6zTZD0
Now, add the following code to the index.js
file to fetch data from the NASA API:
// Using with API Key require("dotenv").config(); axios .get( `https://api.nasa.gov/planetary/apod?api_key=${process.env.NASA_API_KEY}` ) .then((response) => { console.log(response.data); });
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.
You will see a response similar to this from the NASA API:
{ copyright: 'Elena Pinna', date: '2022-01-22', explanation: "On Monday, January's Full Moon rose as the Sun set. Spotted near the eastern horizon, its warm hues are seen in this photo taken near Cagliari, capital city of the Italian island of Sardinia. Of course the familiar patterns of light and dark across the Moon's nearside are created by bright rugged highlands and dark smooth lunar maria. Traditionally the patterns are seen as pareidolia, giving the visual illusion of a human face like the Man in the Moon, or familiar animal like the Moon rabbit. But for a moment the swarming murmuration, also known as a flock of starlings, frozen in the snapshot's field of view lends another pareidolic element to the scene. Some see the graceful figure of a dancer enchanted by moonlight.", hdurl: 'https://apod.nasa.gov/apod/image/2201/IMG_4039copia2_2048.jpg', media_type: 'image', service_version: 'v1', title: 'The Full Moon and the Dancer', url: 'https://apod.nasa.gov/apod/image/2201/IMG_4039copia2_1024.jpg' }
You can also use the params
option of the request config to make the same request:
// With API Key and params option require("dotenv").config(); axios({ method: "get", url: `https://api.nasa.gov/planetary/apod`, params: { api_key: process.env.NASA_API_KEY, }, }).then((response) => { console.log(response.data); });
You can also authenticate requests with other HTTP authentication methods like Bearer authentication by passing the Bearer Token in the Authorization
header. For example:
// Using Authorization Header axios({ method: "get", url: "<ENDPOINT>", headers: { Authorization: `Bearer ${process.env.TOKEN}`, }, }).then((response) => { console.log(response.data); });
You may need to make concurrent requests to multiple endpoints. 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:
// Axios.all() const endpoints = [ "https://rickandmortyapi.com/api/character", "https://www.breakingbadapi.com/api/characters", "https://www.breakingbadapi.com/api/episodes", "https://www.breakingbadapi.com/api/quotes", ]; axios.all(endpoints.map((endpoint) => axios.get(endpoint))).then((allResponses) => { allResponses.forEach((response) => { console.log(response.data); }); });
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:
{info: Object, results: Array(20)} (62) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …] (102) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …] [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …]
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:
axios .get("https://rickandmortyapi.com/api/character/-1") .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); });
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.
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.
You can also handle errors based on their types. Add the following code to the index.js
file:
// Error Handling - Error Specific axios .get("https://rickandmortyapi.com/api/character/-1") .then((response) => { console.log(response.data); }) .catch((error) => { if (error.response) { console.error(error.response.data); console.error(error.response.status); console.error(error.response.headers); } else if (error.request) { console.error(error.request); } else { console.error("Error", error.message); } });
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.
Because the error in the above code occurred on the server side, the error
object will have a response
property, and the following message will be seen in the terminal:
{ error: 'Character not found' } 404 { 'access-control-allow-origin': '*', 'content-length': '31', 'content-type': 'application/json; charset=utf-8', date: 'Sat, 22 Jan 2022 11:27:05 GMT', etag: 'W/"1f-t9l5xVmJZaPHJIukjZQ7Mw4gpG8"', server: 'Netlify', age: '0', 'x-nf-request-id': '01FT0RMCAKMA5BWJ8SMHAJ3RVC', 'x-powered-by': 'Express' }
You can also throw an error by using the validateStatus
request config option. For example:
// Error Handling with validateStatus option axios .get("https://rickandmortyapi.com/api/character/-1", { validateStatus: function (status) { return status < 500; // Reject only if the status code is less than 500 }, }) .then((response) => { console.log(response.data); });
This option will throw an error when the response’s status
satisfies the condition in it. You will see a message similar to this in the terminal:
{ error: 'Character not found' }
HEAD
requests with AxiosA HEAD
request is a GET
request without a message body. You can create a HEAD
request with the axios.head
method. The data
property in the response
object will be empty with such requests.
For example:
// Axios Head Request axios.head("https://rickandmortyapi.com/api/character/1").then((response) => { console.log( `Status: ${response.status} - Server: ${response.headers.server} - Data: ${response.data}` ); });
Here is the message you will see in the terminal:
Status: 200 - Server: Netlify - Data:
In this article, we discussed what Axios is and how can you use it to make GET
requests. We also learned how to make concurrent requests, handle errors, and make HEAD requests.
There’s no doubt that frontends are getting more complex. As you add new JavaScript libraries and other dependencies to your app, you’ll need more visibility to ensure your users don’t run into unknown issues.
LogRocket is a frontend application monitoring solution that lets you replay JavaScript errors as if they happened in your own browser so you can react to bugs more effectively.
LogRocket works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.
Build confidently — start monitoring for free.
We show how to use Goxgen to scaffold a full-stack React app. See how to integrate React with Go and modify Goxygen to suit your project requirements.
Express.js is a Node.js framework for creating maintainable and fast backend web applications in JavaScript. In the fast-paced world of […]
Web components are underrated for the performance and ergonomic benefits they provide in vanilla JS. Learn how to nest them in this post.
Angular’s new defer
feature, introduced in Angular 17, can help us optimize the delivery of our apps to end users.