How to Create an API Using Node.js, Express.js, and Axios
Tags: javascript, express, api, webdev
Published: 2024-05-19 15:26:50

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

```bash
npm install express axios
```
Additionally, install nodemon as a dev dependency to automatically restart your server when file changes are detected:

```bash
npm install --save-dev nodemon
```
Now, update your package.json to use nodemon for starting the server:

```json
{
  "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"
  }
}
```
**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.
```javascript
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}`);
})
```
2. Run the Server
Start the server using `nodemon`
```bash
npm run server
```

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 `routes`folder 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 

```javascript 

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;
```
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 

```javascript
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;
```
now visit to  `http://localhost:3000/ipl` and you will be able to see the data in json format of the matchDetails.