Building RESTful APIs with Express.js

Lavesh Katariya

Lavesh Katariya

· 2 min read
Building RESTful APIs with Express.js

What Is a RESTful API?

A RESTful API adheres to REST (Representational State Transfer) principles, allowing communication between clients and servers using standard HTTP methods:

  • GET: Retrieve data.
  • POST: Create new data.
  • PUT: Update existing data.
  • DELETE: Remove data.

Setting Up Express.js

1. Initialize a Node.js Project

Start by creating a new project:

mkdir express-api && cd express-api
npm init -y

2. Install Express.js

Install Express.js using npm:

npm install express

Creating a Basic RESTful API

1. Setup the Server

Create a file named server.js and add the following code:

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

app.use(express.json()); // Middleware to parse JSON requests

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

2. Define Routes

Add routes for basic CRUD operations:

const data = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' }
];

// GET all items
app.get('/items', (req, res) => {
  res.json(data);
});

// GET item by ID
app.get('/items/:id', (req, res) => {
  const item = data.find(i => i.id === parseInt(req.params.id));
  if (item) res.json(item);
  else res.status(404).send('Item not found');
});

// POST a new item
app.post('/items', (req, res) => {
  const newItem = { id: data.length + 1, name: req.body.name };
  data.push(newItem);
  res.status(201).json(newItem);
});

// PUT to update an item
app.put('/items/:id', (req, res) => {
  const item = data.find(i => i.id === parseInt(req.params.id));
  if (item) {
    item.name = req.body.name;
    res.json(item);
  } else res.status(404).send('Item not found');
});

// DELETE an item
app.delete('/items/:id', (req, res) => {
  const index = data.findIndex(i => i.id === parseInt(req.params.id));
  if (index !== -1) {
    const deletedItem = data.splice(index, 1);
    res.json(deletedItem);
  } else res.status(404).send('Item not found');
});

Testing the API

Using Postman or Curl

You can test the API using tools like Postman or curl:

  • GET all items:
curl http://localhost:3000/items
  • POST a new item:
curl -X POST -H "Content-Type: application/json" -d '{"name": "NewItem"}' http://localhost:3000/items
  • Other methods: Test similarly with appropriate HTTP verbs and payloads.

Best Practices for Building APIs

  1. Validation: Use middleware like express-validator for input validation.
  2. Error Handling: Implement centralized error handling to provide consistent responses.
  3. Authentication and Authorization: Secure your API with tools like passport or jsonwebtoken.
  4. Documentation: Use tools like Swagger to document your API endpoints.
  5. Performance: Optimize with caching and efficient database queries.

Building RESTful APIs with Express.js is straightforward and powerful. By following these steps and adhering to best practices, you can create scalable and maintainable APIs for your applications.

Lavesh Katariya

About Lavesh Katariya

Innovative Full-Stack Developer | Technical Team Lead | Cloud Solutions Architect

With over a decade of experience in building and leading cutting-edge web application projects, I specialize in developing scalable, high-performance platforms that drive business growth. My expertise spans both front-end and back-end development, making me a versatile and hands-on leader capable of delivering end-to-end solutions.

Copyright © 2025 Lavesh Katariya. All rights reserved.