API & Authentication

REST API Setup & Deployment Guide

Design and build a clean REST API – resources, HTTP methods, status codes, validation, versioning and OpenAPI docs – then deploy it securely.

Updated Official documentation ↗

1. Introduction & use cases

A REST API exposes your data as resources (users, orders, products) at URLs, and clients act on them with standard HTTP methods: GET to read, POST to create, PUT/PATCH to update and DELETE to remove. Responses are usually JSON and use status codes to say what happened.

REST is stateless – every request carries everything needed (including authentication), which makes APIs easy to cache and scale. Any language can implement it; this guide uses Node.js + Express, but the design rules apply everywhere.

Where it is used

  • Back-ends for web, mobile and desktop apps
  • Public APIs for partners and integrations
  • Microservices talking to each other
  • Webhooks that notify other systems

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
API clientcurl, Postman or Bruno
BasicsHTTP, JSON and JavaScript

3. Local setup

  1. 1Learn the vocabulary

    Map actions to methods and answer with the right status code.

    OUTPUT
    Method  URL                  Action             Success code
    GET     /api/v1/books        list books         200 OK
    GET     /api/v1/books/42     get one book       200 OK / 404
    POST    /api/v1/books        create a book      201 Created
    PATCH   /api/v1/books/42     update fields      200 OK
    DELETE  /api/v1/books/42     delete             204 No Content
    
    Errors: 400 bad input · 401 not logged in · 403 not allowed
            404 not found · 409 conflict · 422 validation · 429 rate limit · 500 server
  2. 2Set up the project

    Express for routing, zod for validation, swagger-ui-express for docs.

    BASH
    mkdir books-api && cd books-api
    npm init -y && npm pkg set type=module
    npm install express zod swagger-ui-express helmet cors express-rate-limit

4. Create & run a project

  1. 1Build a versioned resource

    Plural nouns in URLs, validation on input, pagination on lists, consistent error JSON.

    server.js
    import express from 'express';
    import helmet from 'helmet';
    import { z } from 'zod';
    
    const app = express();
    app.use(helmet(), express.json());
    const v1 = express.Router();
    
    const books = new Map();
    let nextId = 1;
    const BookInput = z.object({ title: z.string().min(1), author: z.string().min(1), year: z.number().int().optional() });
    
    v1.get('/books', (req, res) => {
      const page = Math.max(1, Number(req.query.page) || 1);
      const limit = Math.min(100, Number(req.query.limit) || 20);
      const all = [...books.values()];
      res.json({ data: all.slice((page - 1) * limit, page * limit), page, limit, total: all.length });
    });
    
    v1.get('/books/:id', (req, res) => {
      const b = books.get(Number(req.params.id));
      b ? res.json(b) : res.status(404).json({ error: { code: 'not_found', message: 'Book not found' } });
    });
    
    v1.post('/books', (req, res) => {
      const parsed = BookInput.safeParse(req.body);
      if (!parsed.success) return res.status(422).json({ error: { code: 'validation', details: parsed.error.issues } });
      const book = { id: nextId++, ...parsed.data };
      books.set(book.id, book);
      res.status(201).location(`/api/v1/books/${book.id}`).json(book);
    });
    
    v1.delete('/books/:id', (req, res) => {
      books.delete(Number(req.params.id)) ? res.status(204).end() : res.status(404).json({ error: { code: 'not_found' } });
    });
    
    app.use('/api/v1', v1);
    app.listen(3000, () => console.log('REST API on http://localhost:3000/api/v1'));
  2. 2Try every endpoint

    Check codes with -i.

    BASH
    node server.js
    curl -i -X POST localhost:3000/api/v1/books -H "Content-Type: application/json" -d '{"title":"Clean Code","author":"Robert C. Martin"}'
    curl -i "localhost:3000/api/v1/books?page=1&limit=10"
    curl -i -X DELETE localhost:3000/api/v1/books/1
  3. 3Document it with OpenAPI

    Write (or generate) an OpenAPI spec and serve Swagger UI so clients can explore the API.

    JS
    import swaggerUi from 'swagger-ui-express';
    import { readFileSync } from 'node:fs';
    const spec = JSON.parse(readFileSync('./openapi.json', 'utf8'));
    app.use('/docs', swaggerUi.serve, swaggerUi.setup(spec));

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

.env
PORT=3000
CORS_ORIGIN=https://app.example.com
DATABASE_URL=postgres://api:pass@localhost:5432/books

Key dependencies

Package / toolUsed for
express (or FastAPI, Django REST, Go net/http)HTTP routing
zod / joi / pydanticInput validation
helmet, corsSecurity headers and cross-origin rules
express-rate-limitThrottle abusive clients
swagger-ui-express / OpenAPIInteractive documentation

Folder structure

project structure
books-api/
├── src/
│   ├── routes/v1/books.js
│   ├── schemas/         # zod schemas
│   ├── services/
│   └── server.js
├── openapi.json        # API contract
└── tests/

Essential commands

CommandWhat it does
curl -i URLSee status code and headers
curl -X POST -H "Content-Type: application/json" -d JSON URLSend JSON
npx @redocly/cli lint openapi.jsonValidate the OpenAPI file
npm testRun API tests (supertest)

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS or containers
HTTPSMandatory – tokens travel in headers
Reverse proxyNginx with request size limits
ProtectionRate limiting, authentication, CORS allow-list
MonitoringAccess logs, error tracking, uptime checks

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Node.js on the server

    Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  3. 3Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/books-api
    cd /var/www/books-api
    npm ci --omit=dev
    nano .env   # production values
  4. 4Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo npm install -g pm2
    pm2 start server.js --name books-api -i max
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs books-api        # live logs
    pm2 restart books-api     # after each deploy
  5. 5Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:3000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  6. 6Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  7. 7Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  8. 8Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  9. 9Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  10. 10Add rate limiting and body limits

    Protect the API from abuse at the app and proxy levels.

    JS
    import rateLimit from 'express-rate-limit';
    app.set('trust proxy', 1);
    app.use('/api/', rateLimit({ windowMs: 60_000, limit: 120 }));
    app.use(express.json({ limit: '100kb' }));

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ curl -i -X POST localhost:3000/api/v1/books -d '{...}'HTTP/1.1 201 CreatedLocation: /api/v1/books/1Content-Type: application/json; charset=utf-8{"id":1,"title":"Clean Code","author":"Robert C. Martin"}$ curl -i -X DELETE localhost:3000/api/v1/books/1HTTP/1.1 204 No Content
Figure 1: terminal output of the sample REST API project (section 4).
1Design resources +OpenAPI2Validate + test3PM2 on server4Nginx + ratelimits5HTTPS clients
Figure 2: production deployment flow (section 6).
books-api/├── src/│ ├── routes/v1/books.js│ ├── schemas/ # zod schemas│ ├── services/│ └── server.js├── openapi.json # API contract└── tests/
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Everything returns 200, even errors

Use proper codes: 400/422 for bad input, 401/403 for auth, 404 for missing, 500 for server errors. Clients and monitoring rely on them.

415 Unsupported Media Type or empty body

Clients must send Content-Type: application/json; the server must parse JSON (express.json()).

CORS errors from browsers

Allow your front-end origin in CORS settings and answer OPTIONS preflight requests.

Breaking changes broke mobile apps

Version the API (/api/v1, /api/v2) and keep old versions running until clients update.

Lists are slow / time out

Paginate (page/limit or cursors), index database columns used for filters and sorting.

Best practices

  • Nouns in URLs, verbs in methods: POST /orders, not /createOrder.
  • Return the same error format everywhere.
  • Version from day one and document with OpenAPI.
  • Use HTTPS only, authenticate with tokens (JWT / OAuth 2.0).
  • Make PUT and DELETE idempotent; support Idempotency-Key for payments.