Create a REST API with Node.js and Express

Create a REST API with Node.js and Express

Create a REST API with Node.js and Express
6 min read

Introduction

REST (Representational State Transfer) APIs are used to connect frontend and backend applications. With Node.js and Express, you can create REST APIs quickly and efficiently. In this tutorial, we will create a simple API to manage user data (Create, Read, Update, Delete).


Steps

1. Project Preparation

a. Make sure you have Node.js installed on your computer. Check with::

node -v
npm -v

b. Create a new project folder and go into it:

mkdir rest-api-node
cd rest-api-node

c. Initialize the project:

npm init -y

d. Instal Express:

npm install express

2. Project Structure

Create a folder structure like this:

rest-api-node/
|
|--- index.js         # Main file
|--- package.json     # Config File

3. Create API

Open index.js file and add the following code:

a. Setup Server

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

// Middleware for parsing JSON
app.use(express.json());

// Root Endpoint
app.get('/', (req, res) => {
    res.send('Welcome to the User API!');
});

// Run the server
app.listen(port, () => {
    console.log(`Server berjalan di http://localhost:${port}`);
});

Run your server with the command:

node index.js

Visit http://localhost:3000/ to see the output "Welcome to the User API!".

b. Add Data Dummy

Add dummy data above the endpoint code:

let users = [
    { id: 1, name: "John Doe", email: "[email protected]" },
    { id: 2, name: "Jane Doe", email: "[email protected]" }
];

c. Endpoint CRUD

Add the following endpoints:

- Get All Users

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

- Get User By ID

app.get('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');
    res.json(user);
});

- Adding New Users

app.post('/users', (req, res) => {
    const newUser = {
        id: users.length + 1,
        name: req.body.name,
        email: req.body.email
    };
    users.push(newUser);
    res.status(201).json(newUser);
});

- Updating Users

app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).send('User not found');

    user.name = req.body.name;
    user.email = req.body.email;
    res.json(user);
});

- Deleting Users

app.delete('/users/:id', (req, res) => {
    const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
    if (userIndex === -1) return res.status(404).send('User not found');

    const deletedUser = users.splice(userIndex, 1);
    res.json(deletedUser);
});

API Testing

Use Postman or cURL to test the endpoints:

1. GET /users

Get a list of users.

2. GET /users/:id

Get user details by ID.

3. POST /users

Add a new user with a JSON payload like:

{ "name": "Alice", "email": "[email protected]" }

4. PUT /users/:id

Update a user by ID with a JSON payload.

5. DELETE /users/:id

Delete a user by ID.

Conclusion

You have successfully created a simple REST API with Node.js and Express. For further development, you can add a database (such as MongoDB or MySQL) and authentication features.

Recommended for you