Skip to content

25 Rest Api Project

DodaTech 3 min read

title: Building a Complete REST API with Node.js — Project weight: 35 date: 2026-06-28 lastmod: 2026-06-28 description: Build a complete production-ready REST API with Node.js combining Express, JWT auth, MongoDB, Redis caching, file upload, Docker, testing, and Swagger docs. tags: [api-development, nodejs]


This capstone project combines all Node.js REST API skills to build a production-ready e-commerce API with Express, JWT authentication, MongoDB, Redis caching, file upload, Docker deployment, comprehensive testing, and Swagger documentation.

```mermaid
flowchart TD
  A[E-Commerce API] --> B[Auth Module]
  A --> C[Product Module]
  A --> D[Order Module]
  A --> E[User Module]
  B --> F[JWT Login/Register]
  C --> G[CRUD + Search]
  D --> H[CRUD + Status]
  E --> I[Profile + Avatar]
  A --> J[Infrastructure]
  J --> K[Redis Cache]
  J --> L[Docker]
  J --> M[Swagger Docs]
  style A fill:#e1f5fe
  style B fill:#c8e6c9
  style C fill:#c8e6c9
  style J fill:#fff9c4

Build an e-commerce API with product management, user accounts, order processing, and shopping cart. Implement all learned concepts: RESTful resource naming, CRUD endpoints, JWT authentication, role-based authorization, filtering/sorting/pagination, file upload for product images, Redis caching, rate limiting, comprehensive testing, Swagger documentation, and Docker deployment.

Project Structure:

ecommerce-api/
├── src/
│   ├── config/         # Environment, database, redis config
│   ├── controllers/    # Route handlers
│   ├── middleware/      # Auth, validation, error handling
│   ├── models/         # Mongoose schemas
│   ├── routes/         # Express routers
│   ├── services/       # Business logic
│   ├── utils/          # Helpers, logger
│   └── app.js          # Express setup
├── tests/              # Jest + Supertest tests
├── uploads/            # Product images
├── Dockerfile
├── docker-compose.yml
├── .env.example
└── package.json

Step 1: Project Setup

// package.json scripts
{
  "scripts": {
    "start": "node src/app.js",
    "dev": "nodemon src/app.js",
    "test": "jest --coverage",
    "test:watch": "jest --watch"
  }
}

// src/app.js - Main application
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const rateLimit = require('express-rate-limit');
const { errorHandler } = require('./middleware/errorHandler');
const routes = require('./routes');

const app = express();

// Security
app.use(helmet());
app.use(cors({ origin: process.env.CORS_ORIGIN }));

// Rate limiting
app.use('/api/', rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
}));

// Parsing
app.use(express.json({ limit: '10kb' }));
app.use('/uploads', express.static('uploads'));

// Logging
app.use(morgan('combined'));

// Routes
app.use('/api', routes);

// Error handling
app.use(errorHandler);

module.exports = app;

Step 2: Auth Module

// src/routes/auth.js
router.post('/auth/register', validate(registerSchema), authController.register);
router.post('/auth/login', authLimiter, validate(loginSchema), authController.login);
router.post('/auth/refresh', authController.refreshToken);
router.post('/auth/logout', authenticate, authController.logout);
router.get('/auth/me', authenticate, authController.getProfile);

Step 3: Product Module with Caching

// src/controllers/productController.js
exports.listProducts = async (req, res, next) => {
  try {
    const cacheKey = `products:${JSON.stringify(req.query)}`;
    const cached = await redisClient.get(cacheKey);
    if (cached) return res.json(JSON.parse(cached));

    const { page, limit, sort, ...filters } = req.query;
    const products = await Product.find(filters)
      .sort(sort || '-createdAt')
      .skip((page - 1) * limit)
      .limit(limit);

    const total = await Product.countDocuments(filters);
    const response = { status: 'success', data: products, meta: { total, page, limit } };

    await redisClient.setEx(cacheKey, 300, JSON.stringify(response));
    res.json(response);
  } catch (error) {
    next(error);
  }
};

Step 4: Testing

// tests/integration/auth.test.js
describe('Auth Endpoints', () => {
  test('POST /api/auth/register - creates user', async () => {
    const res = await request(app)
      .post('/api/auth/register')
      .send({ name: 'Test', email: 'test@test.com', password: 'Password123' });
    expect(res.status).toBe(201);
    expect(res.body.data).toHaveProperty('accessToken');
  });

  test('POST /api/auth/login - returns tokens', async () => {
    await request(app)
      .post('/api/auth/register')
      .send({ name: 'Test', email: 'test@test.com', password: 'Password123' });

    const res = await request(app)
      .post('/api/auth/login')
      .send({ email: 'test@test.com', password: 'Password123' });
    expect(res.status).toBe(200);
    expect(res.body).toHaveProperty('accessToken');
  });
});

Expected output:

PASS  tests/integration/auth.test.js
  Auth Endpoints
    ✓ POST /api/auth/register - creates user (55 ms)
    ✓ POST /api/auth/login - returns tokens (23 ms)
  ...
Test Suites: 5 passed, 5 total
Tests:       24 passed, 24 total

Mini Project Implementation

Build a complete e-commerce API with the following features:

  1. User Management: Register, login, profile, avatar upload, role-based access (admin/customer)
  2. Product Management: CRUD, category filtering, price range, text search, product images, pagination
  3. Order Management: Create order, list orders (user sees own, admin sees all), order status workflow
  4. Shopping Cart: Add/remove items, update quantities, calculate totals
  5. Infrastructure: Redis caching, rate limiting, Swagger docs, Docker deployment, automated tests

What's Next

Now learn about building REST APIs with FastAPI in Building REST APIs with FastAPI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro