π’
EPISODE 05
Resources Β· status codes Β· CRUD Β· CORS
Building a REST API
Design and implement a REST API: pick correct status codes, model resources around URLs, support CRUD, and enable CORS for browser clients.
RESTAPIHTTPstatus codesCORS
Duration
β± About 2.5 hours
Level
π Intermediate
Prerequisite
π― node-04
OUTCOME
A working /tasks REST API with full CRUD and proper status codes
What you'll learn
- 1Design resource-based URLs
- 2Return the right status code for each scenario
- 3Implement create / read / update / delete
- 4Enable CORS for cross-origin browser requests
1. REST Conventions
| Method | URL | Action | Success Status |
|---|---|---|---|
| GET | /tasks | List all tasks | 200 |
| GET | /tasks/:id | Get one task | 200 (or 404) |
| POST | /tasks | Create a task | 201 |
| PUT | /tasks/:id | Replace a task | 200 |
| PATCH | /tasks/:id | Partial update | 200 |
| DELETE | /tasks/:id | Delete a task | 204 (no body) |
2. Sample CRUD
javascript
import express from "express";
import cors from "cors";
const app = express();
app.use(cors());
app.use(express.json());
let tasks = [];
let nextId = 1;
app.get("/tasks", (req, res) => res.json(tasks));
app.get("/tasks/:id", (req, res) => {
const t = tasks.find(t => t.id == req.params.id);
if (!t) return res.status(404).json({ error: "Not found" });
res.json(t);
});
app.post("/tasks", (req, res) => {
const task = { id: nextId++, title: req.body.title, done: false };
tasks.push(task);
res.status(201).json(task);
});
app.delete("/tasks/:id", (req, res) => {
tasks = tasks.filter(t => t.id != req.params.id);
res.status(204).end();
});
app.listen(3000);3. Status Codes Cheat Sheet
- 2xx β success (200 OK, 201 Created, 204 No Content)
- 3xx β redirection (301 Moved, 304 Not Modified)
- 4xx β client error (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict)
- 5xx β server error (500 Internal Server Error, 503 Service Unavailable)
4. CORS
Browsers block cross-origin requests by default. Enable CORS so your frontend can call your API.
javascript
import cors from "cors";
// Allow specific origins
app.use(cors({
origin: ["http://localhost:5173", "https://myapp.com"],
credentials: true,
}));Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β