How to Build a Simple API with Express.js

Published on 19th March, 2025

If you are new to backend development and want to create a simple API, Express.js is a great place to start. It’s a lightweight and easy-to-use framework for Node.js that helps you build web applications and APIs quickly.

In this guide, we’ll create a basic API that can add, view, update, and delete users. Let’s get started!

Step 1: Set Up Your Project

First, make sure you have Node.js installed on your computer. You can check by running:

node -v

If Node.js is installed, you will see a version number. If not, download and install it from https://nodejs.org.

Now, create a new folder for your project and open it in your terminal. Run:

mkdir express-api
cd express-api

Initialize a new Node.js project with:

npm init -y

This will create a package.json file, which keeps track of your project dependencies.

Step 2: Install Express.js

Now, install Express.js by running:

npm install express

Once installed, you are ready to write your first API!

Step 3: Create a Basic Express Server

Inside your project folder, create a new file called server.js and open it in a code editor. Then, add this code:

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

app.use(express.json()); // Allows our API to handle JSON data

app.get("/", (req, res) => {
    res.send("Welcome to our API!");
});

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

Now, run the server:

node server.js

Open your browser and go to http://localhost:3000/. You should see "Welcome to our API!" displayed on the page.

Step 4: Create API Routes

We will now add some routes to manage users in our API. Replace your server.js file with this code:

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

app.use(express.json());

// Fake database (array)
let users = [
    { id: 1, name: "John Doe", email: "john@example.com" },
    { id: 2, name: "Jane Smith", email: "jane@example.com" }
];

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

// Get a single 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);
});

// Add a new user
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);
});

// Update a user
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);
});

// Delete a user
app.delete("/users/:id", (req, res) => {
    users = users.filter(u => u.id !== parseInt(req.params.id));
    res.send("User deleted");
});

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

Step 5: Test Your API

Now restart your server:

node server.js

You can test the API using Postman or cURL, but the easiest way is to use a browser or a tool like Hoppscotch.

Try these API endpoints:

  • GET all users → http://localhost:3000/users
  • GET a single user → http://localhost:3000/users/1
  • POST a new user → Use Postman to send a POST request to http://localhost:3000/users with JSON data:
{
  "name": "Alice",
  "email": "alice@example.com"
}
  • PUT (update) a user → http://localhost:3000/users/1 with JSON data:
{
  "name": "John Updated",
  "email": "john.updated@example.com"
}
  • DELETE a user → http://localhost:3000/users/1

Conclusion

That’s it! You’ve just built a simple API using Express.js. Here’s a quick recap of what we did:

  • ✅ Set up a Node.js project
  • ✅ Installed and configured Express.js
  • ✅ Created API routes to handle CRUD operations
  • ✅ Tested the API

This is just the beginning! You can now explore database integration (MongoDB, MySQL, PostgreSQL), authentication (JWT), or deployment (Docker, AWS, Vercel) to take your API to the next level.

Comments

Please login to publish your comment!

By logging in, you agree to our Terms of Service and Privacy Policy.


No comments here!