Backend Development 5 min read

Building a REST API with Node.js and Express

Learn how to create a robust REST API from scratch using Node.js, Express, and best practices for modern web development.

Y

Your Name

Author

Share:
Building a REST API with Node.js and Express

Building a REST API with Node.js and Express

REST APIs are the backbone of modern web applications. In this comprehensive guide, we’ll build a complete REST API from scratch using Node.js and Express.

What You’ll Learn

  • Setting up a Node.js project
  • Creating RESTful endpoints
  • Handling HTTP methods (GET, POST, PUT, DELETE)
  • Error handling and validation
  • Best practices for API design

Prerequisites

Before we start, make sure you have:

  • Node.js installed (version 16 or higher)
  • Basic knowledge of JavaScript
  • Understanding of HTTP concepts

Getting Started

Let’s begin by setting up our project structure:

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

Creating the Server

First, let’s create our main server file:

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());

// Routes
app.get('/', (req, res) => {
  res.json({ message: 'API is running!' });
});

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

Defining Routes

Now let’s create some RESTful routes:

// GET all items
app.get('/api/items', (req, res) => {
  // Your logic here
  res.json({ items: [] });
});

// GET single item
app.get('/api/items/:id', (req, res) => {
  const { id } = req.params;
  // Your logic here
  res.json({ item: { id } });
});

// POST create item
app.post('/api/items', (req, res) => {
  const newItem = req.body;
  // Your logic here
  res.status(201).json({ item: newItem });
});

// PUT update item
app.put('/api/items/:id', (req, res) => {
  const { id } = req.params;
  const updates = req.body;
  // Your logic here
  res.json({ item: { id, ...updates } });
});

// DELETE item
app.delete('/api/items/:id', (req, res) => {
  const { id } = req.params;
  // Your logic here
  res.status(204).send();
});

Error Handling

Proper error handling is crucial for a robust API:

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ 
    error: 'Something went wrong!',
    message: err.message 
  });
});

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({ 
    error: 'Route not found' 
  });
});

Validation

Input validation is essential for security:

const validateItem = (req, res, next) => {
  const { name, description } = req.body;
  
  if (!name || !description) {
    return res.status(400).json({
      error: 'Name and description are required'
    });
  }
  
  next();
};

// Use validation middleware
app.post('/api/items', validateItem, (req, res) => {
  // Your logic here
});

Best Practices

1. Use Proper HTTP Status Codes

  • 200: Success
  • 201: Created
  • 400: Bad Request
  • 404: Not Found
  • 500: Internal Server Error

2. Consistent Response Format

// Success response
{
  "success": true,
  "data": { /* your data */ },
  "message": "Operation successful"
}

// Error response
{
  "success": false,
  "error": "Error description",
  "code": "ERROR_CODE"
}

3. Use Environment Variables

// .env file
PORT=3000
DATABASE_URL=mongodb://localhost:27017/myapi
JWT_SECRET=your-secret-key

Security Considerations

  1. Rate Limiting: Prevent abuse
  2. Authentication: Protect sensitive endpoints
  3. Input Sanitization: Prevent injection attacks
  4. HTTPS: Always use in production

Testing Your API

Use tools like Postman or curl to test:

# Test GET endpoint
curl http://localhost:3000/api/items

# Test POST endpoint
curl -X POST http://localhost:3000/api/items \
  -H "Content-Type: application/json" \
  -d '{"name":"Test Item","description":"Test Description"}'

Conclusion

Building a REST API with Node.js and Express is straightforward when you follow best practices. Remember to:

  • Plan your API structure
  • Implement proper error handling
  • Validate all inputs
  • Use appropriate HTTP status codes
  • Document your endpoints

This foundation will serve you well as you build more complex APIs. In the next article, we’ll explore adding database integration and authentication.

Next Steps

  • Add database connectivity (MongoDB, PostgreSQL)
  • Implement authentication and authorization
  • Add API documentation with Swagger
  • Deploy to production

What aspect of API development would you like to explore next?

Tags

#Node.js #Express #API #Backend #JavaScript

Related Articles

React Hooks: A Complete Guide for Modern Development
Web Development

React Hooks: A Complete Guide for Modern Development

Master React Hooks with this comprehensive guide covering useState, useEffect, custom hooks, and advanced patterns for building powerful React applications.

#React #JavaScript #Hooks +1 more