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 need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| API client | curl, Postman or Bruno |
| Basics | HTTP, JSON and JavaScript |
3. Local setup
1Learn the vocabulary
Map actions to methods and answer with the right status code.
OUTPUTMethod 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 server2Set up the project
Express for routing, zod for validation, swagger-ui-express for docs.
BASHmkdir 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
1Build a versioned resource
Plural nouns in URLs, validation on input, pagination on lists, consistent error JSON.
server.jsimport 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'));2Try every endpoint
Check codes with
-i.BASHnode 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/13Document it with OpenAPI
Write (or generate) an OpenAPI spec and serve Swagger UI so clients can explore the API.
JSimport 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
PORT=3000
CORS_ORIGIN=https://app.example.com
DATABASE_URL=postgres://api:pass@localhost:5432/booksKey dependencies
| Package / tool | Used for |
|---|---|
express (or FastAPI, Django REST, Go net/http) | HTTP routing |
zod / joi / pydantic | Input validation |
helmet, cors | Security headers and cross-origin rules |
express-rate-limit | Throttle abusive clients |
swagger-ui-express / OpenAPI | Interactive documentation |
Folder structure
books-api/
├── src/
│ ├── routes/v1/books.js
│ ├── schemas/ # zod schemas
│ ├── services/
│ └── server.js
├── openapi.json # API contract
└── tests/Essential commands
| Command | What it does |
|---|---|
curl -i URL | See status code and headers |
curl -X POST -H "Content-Type: application/json" -d JSON URL | Send JSON |
npx @redocly/cli lint openapi.json | Validate the OpenAPI file |
npm test | Run API tests (supertest) |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS or containers |
| HTTPS | Mandatory – tokens travel in headers |
| Reverse proxy | Nginx with request size limits |
| Protection | Rate limiting, authentication, CORS allow-list |
| Monitoring | Access logs, error tracking, uptime checks |
Deployment steps
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.
BASHssh 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_IP2Install 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.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v3Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/books-api cd /var/www/books-api npm ci --omit=dev nano .env # production values4Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo 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 deploy5Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:3000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { 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"; } }6Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx7Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status8Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com9Add 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.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run10Add rate limiting and body limits
Protect the API from abuse at the app and proxy levels.
JSimport 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.
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.