Skip to main content
Albero Academy

REST APIs & Environment

Design a REST API with the right methods and status codes, handle errors, and manage secrets with environment variables.

Chapter 4Node.js15 min readBeginner friendly
  • #Node.js
  • #REST
  • #API

A REST API exposes resources (students, orders) over HTTP using a consistent convention: the HTTP method says what to do, the URL says to what. Get this convention right and any client — a React app, a mobile app, another service — can use your API predictably.

REST principles

MethodMeaningExample
GETReadGET /students
POSTCreatePOST /students
PUT / PATCHUpdatePATCH /students/42
DELETERemoveDELETE /students/42

Status codes

  • 2xx success — 200 OK, 201 Created, 204 No Content
  • 4xx client error — 400 Bad Request, 401 Unauthorized, 404 Not Found
  • 5xx server error — 500 Internal Server Error

A CRUD resource

students API
let students = [{ id: 1, name: "Aanya" }];
app.get("/students", (req, res) => res.json(students));
app.get("/students/:id", (req, res) => {
const s = students.find(s => s.id === Number(req.params.id));
if (!s) return res.status(404).json({ error: "Not found" });
res.json(s);
});
app.post("/students", (req, res) => {
const student = { id: Date.now(), ...req.body };
students.push(student);
res.status(201).json(student);
});

Error handling

Express catches errors passed to next(err). Add an error-handling middleware last (it takes four arguments):

central error handler
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({ error: err.message });
});

Environment variables

Never hard-code secrets (API keys, database URLs, ports) in source. Put them in a .env file (git-ignored) and read them from process.env:

.env
PORT=3000
DATABASE_URL=postgres://localhost/albero
JWT_SECRET=change-me
reading config
const port = process.env.PORT || 3000;
app.listen(port);

Practice

Build a full CRUD API for a programmes resource: list, get-one (404 if missing), create (201), update and delete. Add a central error handler, and move the port into a .env file.

Key takeaways

  1. 01REST maps HTTP methods to actions: GET read, POST create, PUT/PATCH update, DELETE remove.
  2. 02Return the right status code: 2xx success, 4xx client error (404, 400, 401), 5xx server error.
  3. 03A resource is a set of routes on one URL prefix (/students, /students/:id).
  4. 04Centralise errors in a 4-argument Express error middleware registered last.
  5. 05Keep secrets in a git-ignored .env, read via process.env, and commit only a .env.example.