Node.js12 min read

Building RESTful APIs with Node.js and Express

Learn how to build production-ready RESTful APIs using Node.js and Express framework.

Michael Chen
November 28, 2025
18.2k724

Building RESTful APIs is one of the most common use cases for Node.js. Express.js provides a robust set of features for web and mobile applications, making API development straightforward and efficient.

Setting Up Express

First, let's set up a basic Express server with proper middleware configuration.

REST API Best Practices

When building RESTful APIs, following best practices ensures your API is maintainable, scalable, and easy to use:

- Use proper HTTP methods (GET, POST, PUT, DELETE, PATCH) - Implement proper status codes - Version your API - Use proper error handling - Implement request validation - Add rate limiting and security measures

Middleware in Express

Middleware functions are functions that have access to the request object, response object, and the next middleware function in the application's request-response cycle.

#Node.js#Express#REST API#Backend

Common Questions & Answers

Q1

What are the main HTTP methods used in RESTful APIs?

A

The main HTTP methods are: GET (retrieve resources), POST (create new resources), PUT (update entire resources), PATCH (partial updates), and DELETE (remove resources). Each method should be idempotent except POST.

Q2

How do you handle errors in Express?

A

Express uses error-handling middleware with four arguments (err, req, res, next). You can create a centralized error handler that catches all errors and formats them consistently.

javascript
// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  
  res.status(err.statusCode || 500).json({
    error: {
      message: err.message,
      status: err.statusCode || 500
    }
  });
});

// Usage in route
app.get('/api/users/:id', async (req, res, next) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      const error = new Error('User not found');
      error.statusCode = 404;
      throw error;
    }
    res.json(user);
  } catch (error) {
    next(error);
  }
});
Q3

What is middleware and how does it work?

A

Middleware are functions that execute during the request-response cycle. They have access to req, res, and next. Middleware can execute code, modify req/res objects, end the request-response cycle, or call the next middleware. They execute in the order they are defined.

javascript
// Custom logging middleware
const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Pass control to next middleware
};

app.use(logger);

// Authentication middleware
const authenticate = (req, res, next) => {
  const token = req.headers.authorization;
  
  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }
  
  // Verify token logic here
  next();
};

app.get('/api/protected', authenticate, (req, res) => {
  res.json({ message: 'Protected route' });
});