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
| Method | Meaning | Example |
|---|---|---|
GET | Read | GET /students |
POST | Create | POST /students |
PUT / PATCH | Update | PATCH /students/42 |
DELETE | Remove | DELETE /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
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):
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:
PORT=3000DATABASE_URL=postgres://localhost/alberoJWT_SECRET=change-me
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
- 01REST maps HTTP methods to actions: GET read, POST create, PUT/PATCH update, DELETE remove.
- 02Return the right status code: 2xx success, 4xx client error (404, 400, 401), 5xx server error.
- 03A resource is a set of routes on one URL prefix (/students, /students/:id).
- 04Centralise errors in a 4-argument Express error middleware registered last.
- 05Keep secrets in a git-ignored .env, read via process.env, and commit only a .env.example.
