Back to Tutorials

Featured Building REST APIs with Node.js and Express

Introduction to REST APIs

REST (Representational State Transfer) APIs are the backbone of modern web applications. They allow different applications to communicate with each other over HTTP.

What You'll Learn

  • Understanding REST principles
  • Setting up a Node.js Express server
  • Creating API endpoints
  • Handling requests and responses
  • Error handling and validation

Setting Up Your Project

First, create a new directory and initialize your Node.js project:

mkdir my-api
cd my-api
npm init -y
npm install express cors dotenv
npm install --save-dev nodemon

Creating Your First API

Create a file called server.js:

const express = require('express');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());

// Sample data
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('/api/users', (req, res) => {
  res.json(users);
});

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

// POST create new user
app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  if (!name || !email) {
    return res.status(400).json({ error: 'Name and email are required' });
  }
  const newUser = {
    id: users.length + 1,
    name,
    email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT update user
app.put('/api/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex === -1) {
    return res.status(404).json({ error: 'User not found' });
  }
  users[userIndex] = { ...users[userIndex], ...req.body };
  res.json(users[userIndex]);
});

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

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Testing Your API

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

# Get all users
curl http://localhost:3000/api/users

# Get specific user
curl http://localhost:3000/api/users/1

# Create new user
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob","email":"bob@example.com"}'

Best Practices

  • Always validate input data
  • Use proper HTTP status codes
  • Implement error handling
  • Add authentication for protected routes
  • Document your API endpoints

Next Steps

Now that you have a basic API, consider adding:

  • Database integration (MongoDB, PostgreSQL)
  • Authentication (JWT tokens)
  • Rate limiting
  • API documentation (Swagger/OpenAPI)
  • Testing (Jest, Mocha)