Axios With NodeJs

Axios is a popular JavaScript library used for making HTTP requests from the browser and Nodejs enviroments. It provides a simple way to interact with external APIs and fetch data from remote servers.

In this article, we are going to explore how to use Axios in a Nodejs and Express environment to create a simple API that performs basic CRUD (Create, Read, Update, Delete) operations on a fictional todos resource.

Prerequisites

Before diving into the implementation, ensure you have the following prerequisites:

  1. Node.js and npm (Node Package Manager) installed on your machine.
  2. A text editor or IDE of your choice for writing code.
  3. Basic knowledge of JavaScript and RESTful APIs.

Setting Up the Project

To get started, create a new directory for your project and navigate into it using your terminal or command prompt:

mkdir axios-simple-api
cd axios-simple-api

Now, initialize a new Node.js project by running:

npm init -y

This will create a package.json file with default settings.

Next, let’s install the necessary dependencies. We need Axios to make HTTP requests, and Express to set up our API server:

npm install axios express

Creating the Simple API

Let’s create an index.js file in the project directory. This will be the entry point of our application.

axios-simple-api/
├── index.js
├── package.json
└── node_modules/

Open the index.js file in your text editor and start by importing the required modules:

const express = require('express');
const axios = require('axios');
const app = express();

const PORT = 3000; // You can change this to any port number of your choice

Now, let’s define some basic routes for our API. The implementation of these routes uses Axios to make HTTP requests to a fictional JSONPlaceholder API. You can replace this URL with any other API endpoint you want to interact with.

Get Request

This request is used to fetch all the todos from API. When a client makes a GET request to /todos endpoint, the server will also make axios get request to the API for getting todos. To get all todos from API, the axios get() method is used. It takes the URL as its first argument ('https://jsonplaceholder.typicode.com/todos').

// GET /todos
app.get('/todos', async (req, res) => {
  try {
    // Fetch the list of todos from a remote API (simulated using JSONPlaceholder)
    const response = await axios.get('https://jsonplaceholder.typicode.com/todos');
    const todos = response.data;
    res.json(todos);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

The response from the API is stored in the response variable. This response object contains various properties, such as data, status, headers, etc. After server receives the data from the JSONPlaceholder API, extracts the todos, and sends them back as a JSON response to the client.

Post Request

This request is used to create a new todo on the server. When a client makes a POST request to /todos, the server will also make axios post request to API create a new todo.

The Axios post() method is used to perform the POST request. It takes the URL as its first argument ('https://jsonplaceholder.typicode.com/todos') and the data to be sent in the request body as its second argument.

// POST /todos
app.post('/todos', async (req, res) => {
  try {
    // Create a new todo on the remote API (simulated using JSONPlaceholder)
    const response = await axios.post('https://jsonplaceholder.typicode.com/todos', req.body);
    const newTodo = response.data;
    res.json(newTodo);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

The response from the server is stored in the response variable. The newly created todo is extracted from the response.data property and server responds to the client’s request with the newly created todo in JSON format using res.json(newTodo).

Put Request

This request is used to update an existing todo on the server. The client needs to provide the ID of the todo to be updated, along with the updated data for the todo in the request body.

In this example, Axios makes a PUT request to API at the /todos/:id endpoint, with the updated todo data in the request body. The Axios put() method is used to perform the PUT request. It takes the URL with the placeholder for the todo ID.

// PUT /todos/:id
app.put('/todos/:id', async (req, res) => {
  try {
    // Update the todo with the given ID on the remote API (simulated using JSONPlaceholder)
    const response = await axios.put(`https://jsonplaceholder.typicode.com/todos/${req.params.id}`, req.body);
    const updatedTodo = response.data;
    res.json(updatedTodo);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

When API send send response, the updated todo is extracted from the response.data property and server responds to the client’s request with the updated todo in JSON format using res.json(updatedTodo).

Delete Request

This request is used to delete an existing todo from the server. The client needs to provide the ID of the todo to be deleted in the URL. After client send request to delete a todo, Axios delete request is triggered to remove a todo from API.

The Axios delete() method is used to perform the DELETE request. It takes the URL with the placeholder for the todo ID ('https://jsonplaceholder.typicode.com/todos/${req.params.id}') as its argument.

// DELETE /todos/:id
app.delete('/todos/:id', async (req, res) => {
  try {
    // Delete the todo with the given ID on the remote API (simulated using JSONPlaceholder)
    await axios.delete(`https://jsonplaceholder.typicode.com/todos/${req.params.id}`);
    res.json({ message: 'Todo deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});
  • The API does not return any specific data in response to the DELETE request, so we do not need to extract any data from the response.
  • The server responds to the client’s request with a JSON object containing a message indicating the successful deletion using res.json({ message: 'Todo deleted successfully' }).

Testing the API

Finally, let’s start the server

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Now that we have our simple API set up, it’s time to test it. Save the index.js file and run the following command in your terminal:

node index.js

The server should start, and you’ll see the message “Server is running on http://localhost:3000 in the console. To test the API endpoints, you can use tools like curl or Postman.

Conclusion

In this article, we explored how to use Axios in a Node environment to create a simple API for a fictional “todos” resource. Axios makes it easy to make HTTP requests and interact with remote APIs, allowing us to perform CRUD operations with ease.

Remember to replace the fictional JSONPlaceholder API URL with a real API endpoint if you want to connect to a live server. You can extend this example to include authentication, validation, and database interactions to build more sophisticated APIs.

Thank you for reading.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top