DEV Community

Cover image for How to Create an API Using Node.js, Express.js, and Axios
Utkarsh Yadav
Utkarsh Yadav

Posted on

How to Create an API Using Node.js, Express.js, and Axios

Creating an API with Node.js and Express.js is a powerful way to handle HTTP requests and responses, enabling you to build robust back-end services. Axios, on the other hand, is a promise-based HTTP client for the browser and Node.js that makes it easier to interact with external APIs. This guide will take you through the steps of creating an API using these technologies.

Prerequisites

  • Basic knowledge of javascript and Node.js
  • Node.js installed on your machine
  • A code editor of your choice .(I will be using VS CODE)

Setting up the project

  1. Initialise a new Node.js project
    You can create a new empty folder (with name example-api) on your desktop and then drag and drop it to vs code editor to open the folder.

  2. Installing the necessary Packages
    For installing the packages I will be using node package manager (npm), you can use yarn as well.
    Now to install open your terminal and run the following

npm install express axios
Enter fullscreen mode Exit fullscreen mode

Additionally, install nodemon as a dev dependency to automatically restart your server when file changes are detected:

npm install --save-dev nodemon
Enter fullscreen mode Exit fullscreen mode

Now, update your package.json to use nodemon for starting the server:

{
  "type": "module",
  "dependencies": {
    "axios": "^1.6.8",
    "express": "^4.19.2",
    "nodemon": "^3.1.0"
  },
  "scripts": {
    "server": "nodemon server.js",
    "test": "mocha",
    "fetch":"nodemon fetch.js",
    "dev":"nodemon index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating the Express Server

  1. Create server.js File

In the root of your project directory, create a file named server.js and then we'll setup a basic express server.

import express from "express"

const PORT = 3000;
const app = express();

app.get("/", (req, res) => {
    res.send("Hello from homepage");
})

app.listen(PORT, () => {
    console.log(`[SERVER] ExpressJS is listening to port http://localhost:${PORT}`);
})
Enter fullscreen mode Exit fullscreen mode
  1. Run the Server Start the server using nodemon
npm run server
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser, and you should see "Hello from homepage".

Adding routes to our API
Organizing our Express.js application by separating routes into different files and using Express Router is a best practice for maintaining clean, scalable, and manageable code. To do this we will create a new folder named routes in our root directory and inside our routesfolder create a new file named routes.js

  1. Creating a cricket match score route Now, to create a route that will send the data of a demo match for the scope of this article, navigate to routes.js file inside routes folder and write the following code

import express from "express";
const apiRoutes = express.Router();

const matchDetails = [
  {
    matchID: 60,
    Teams: "Rajasthan Royals vs Kolkata Knight Riders",
    Venue: {
      Stadium: "Eden Gardens",
      City: "Kolkata",
    },
    Weather: "Haze, Dew after sunset",
    Time: "7:30 pm IST",
    Date: "19 May 2024",
    Toss: {
      wonBy: "Team Name",
      Decision: "TBD",
    },
    pitchReport: "Flat track with movement expected for pacers",
    liveScore: {
      totalScore: "60",
      wickets: "1",
      FOW: "12",
      overs: "7",
      Batter1: {
        Name: "Jos Buttler",
        Score: "32",
        ballsFaced: "12",
        sixes: "3",
        fours: "2",
      },
      Batter2: {
        Name: "Sanju Samson",
        Score: "28",
        ballsFaced: "20",
        sixes: "2",
        fours: "1",
      },
      Bowler: {
        Name: "Glenn Maxwell",
        Overs: "2",
        wickets: "1",
        Maiden: "1",
      },
    },
    teamRosters: {
      RajasthanRoyals: [
        "Jos Buttler",
        "Sanju Samson",
        "Ben Stokes",
        "Jofra Archer",
      ],
      KolkataKnightRiders: [
        "Eoin Morgan",
        "Shubman Gill",
        "Andre Russell",
        "Pat Cummins",
      ],
    },
  },
  {
    matchID: 61,
    Teams: "Mumbai Indians vs Chennai Super Kings",
    Venue: {
      Stadium: "Wankhede Stadium",
      City: "Mumbai",
    },
    Weather: "Clear skies",
    Time: "7:30 pm IST",
    Date: "20 May 2024",
    Toss: {
      wonBy: "Team Name",
      Decision: "TBD",
    },
    pitchReport: "Good batting surface with some assistance for spinners",
    liveScore: {
      totalScore: "85",
      wickets: "2",
      FOW: "45",
      overs: "10",
      Batter1: {
        Name: "Rohit Sharma",
        Score: "45",
        ballsFaced: "30",
        sixes: "4",
        fours: "3",
      },
      Batter2: {
        Name: "Suryakumar Yadav",
        Score: "35",
        ballsFaced: "25",
        sixes: "2",
        fours: "2",
      },
      Bowler: {
        Name: "Deepak Chahar",
        Overs: "3",
        wickets: "1",
        Maiden: "0",
      },
    },
    teamRosters: {
      MumbaiIndians: [
        "Rohit Sharma",
        "Suryakumar Yadav",
        "Kieron Pollard",
        "Jasprit Bumrah",
      ],
      ChennaiSuperKings: [
        "MS Dhoni",
        "Ravindra Jadeja",
        "Deepak Chahar",
        "Faf du Plessis",
      ],
    },
  },

];

apiRoutes.get("/ipl", (req, res) => {
  res.status(200).json(matchDetails);
});

export default apiRoutes;
Enter fullscreen mode Exit fullscreen mode

Our /ipl route has been create and now we need to import this route to our main server.js file and update the existing code to

import express from "express"
import apiRoutes from "./routes/routes.js"

const PORT = 3000;
const app = express();

app.get("/", (req, res) => {
    res.send("Hello from homepage");
})
app.get("/ipl", apiRoutes)

app.listen(PORT, () => {
    console.log(`[SERVER] ExpressJS is listening to port http://localhost:${PORT}`);
})
export default app;
Enter fullscreen mode Exit fullscreen mode

now visit to http://localhost:3000/ipl and you will be able to see the data in json format of the matchDetails.

Top comments (0)