Docs / Programming & Development / How to Build a REST API with Express and MongoDB

How to Build a REST API with Express and MongoDB

By Admin · Mar 1, 2026 · Updated Apr 23, 2026 · 26 views · 2 min read

Overview

Express is a minimal Node.js web framework, and MongoDB is a document-oriented NoSQL database. Together they provide a flexible stack for building REST APIs on your Breeze.

Prerequisites

  • A Breeze running Ubuntu 22.04 or later
  • Node.js 18+ installed
  • MongoDB installed and running
  • Nginx installed

Step 1: Initialize the Project

mkdir /var/www/rest-api && cd /var/www/rest-api
npm init -y
npm install express mongoose dotenv helmet cors

Step 2: Create the API Server

Create server.js:

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

const app = express();
app.use(helmet());
app.use(cors());
app.use(express.json());

mongoose.connect(process.env.MONGO_URI);

const ItemSchema = new mongoose.Schema({
  name: String,
  description: String,
  createdAt: { type: Date, default: Date.now }
});
const Item = mongoose.model('Item', ItemSchema);

app.get('/api/items', async (req, res) => {
  const items = await Item.find();
  res.json(items);
});

app.post('/api/items', async (req, res) => {
  const item = await Item.create(req.body);
  res.status(201).json(item);
});

app.listen(3000, () => console.log('API running on port 3000'));

Step 3: Environment and Production

Create a .env file:

MONGO_URI=mongodb://localhost:27017/myapi
pm2 start server.js --name "rest-api"
pm2 save && pm2 startup

Step 4: Nginx Reverse Proxy

server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
sudo ln -s /etc/nginx/sites-available/restapi /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d api.yourdomain.com

Best Practices

  • Use helmet for security headers and cors for cross-origin control
  • Add input validation with express-validator
  • Implement rate limiting with express-rate-limit

Was this article helpful?