How to create an API using Node.js and Express.js

How to create an API using Node.js and Express.js

Step-by-step guide for creating API in Node.js using Express.js

Creating an API in Node.js using Express.js involves several steps. This guide aims to simplify the process, focusing on practical implementation rather than lengthy theoretical explanations. By keeping the article concise, readers can quickly grasp the essentials of API creation in Node.js using Express.js.

Step 1: Set Up the Project

First, ensure you have Node.js and NPM installed. Then, create a new project directory and initialize it with npm:

mkdir user-info-api
cd user-info-api
npm init -y

Step 2: Install Dependencies

You need to install Express.js:

npm install express

Step 3: Create the Server

Create an index.js file and set up a basic Express server:

const express = require('express');
const app = express();
const port = 3000;

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

Step 4: Define the Data

Create a JSON file, users.json that contains the id, first_name, last_name, email, phone, gender. Here's an example structure:

[{
  "id": 1,
  "first_name": "Angelle",
  "last_name": "Prozescky",
  "email": "aprozescky0@tmall.com",
  "phone": "+55 784 320 6277",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Neda",
  "last_name": "Yirrell",
  "email": "nyirrell1@macromedia.com",
  "phone": "+46 516 685 9057",
  "gender": "Female"
}, {
  "id": 3,
  "first_name": "Chester",
  "last_name": "Kettow",
  "email": "ckettow2@wordpress.org",
  "phone": "+30 206 359 9319",
  "gender": "Male"
}, {
  "id": 4,
  "first_name": "Francklin",
  "last_name": "Wealthall",
  "email": "fwealthall3@digg.com",
  "phone": "+86 931 256 9850",
  "gender": "Male"
}, {
  "id": 5,
  "first_name": "Harri",
  "last_name": "Cheverell",
  "email": "hcheverell4@examiner.com",
  "phone": "+48 701 447 7286",
  "gender": "Female"
}]

Step 5: Create the API Endpoint:

Modify index.js to add an endpoint that serves the users-data based on the provided id:

const usersInfo = require('./users.json');

app.get('/users/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const userData = usersInfo.find(info => info.id === id);

    if(userData) {
        res.json(userData);
    } else {
        res.status(404).json({ error: "User not found" });
    }
});

To add multiple endpoints to your API, you can define additional routes in your Express application. Here's how you can add another route to return all users data.

app.get('/users', (req, res) => {
  res.json(usersInfo);
});

Step 6: Run the Server

Start the server using:

node index.js

Step 7: Test the API

You can test the API using a tool like Postman or curl:

curl http://localhost:3000/users/1

This should return:

{
  "id": 1,
  "first_name": "Angelle",
  "last_name": "Prozescky",
  "email": "aprozescky0@tmall.com",
  "phone": "+55 784 320 6277",
  "gender": "Female"
}

To get all users data:

curl http://localhost:3000/users

This should return:

[{
  "id": 1,
  "first_name": "Angelle",
  "last_name": "Prozescky",
  "email": "aprozescky0@tmall.com",
  "phone": "+55 784 320 6277",
  "gender": "Female"
}, {
  "id": 2,
  "first_name": "Neda",
  "last_name": "Yirrell",
  "email": "nyirrell1@macromedia.com",
  "phone": "+46 516 685 9057",
  "gender": "Female"
}, {
  "id": 3,
  "first_name": "Chester",
  "last_name": "Kettow",
  "email": "ckettow2@wordpress.org",
  "phone": "+30 206 359 9319",
  "gender": "Male"
}, {
  "id": 4,
  "first_name": "Francklin",
  "last_name": "Wealthall",
  "email": "fwealthall3@digg.com",
  "phone": "+86 931 256 9850",
  "gender": "Male"
}, {
  "id": 5,
  "first_name": "Harri",
  "last_name": "Cheverell",
  "email": "hcheverell4@examiner.com",
  "phone": "+48 701 447 7286",
  "gender": "Female"
}]

Complete index.js Example

Here's the compilation of the above chunks of code in the index.js file for clarity.

const express = require('express');
const app = express();
const port = 3000;
const usersInfo = require('./users.json'); // Load the JSON file

app.get('/users/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const userData = usersInfo.find(info => info.id === id);

    if(userData) {
        res.json(userData)
    } else {
        res.status(404).json({ error: "User not found" });
    }
});

app.get('/users', (req, res) => {
  res.json(usersInfo);
});

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

By following these steps, you'll have a working API that serves user data based on the provided ID parameter, as well as the ability to retrieve all user data through another route.

Thanks for reading this article. Make sure to like and share it with your friends so we can grow together. Please share your API link in the comments below.