What is a REST API?
A REST API lets the front end read and change data over HTTP using URLs and methods:
| Method | Action | Example |
|---|---|---|
| GET | Read | GET /api/todos |
| POST | Create | POST /api/todos |
| PUT/PATCH | Update | PATCH /api/todos/1 |
| DELETE | Delete | DELETE /api/todos/1 |
Data is usually sent as JSON.
Set up
Install Node.js, then in a new folder:
npm init -y
npm install expressA simple API
Create server.js:
const express = require("express");
const app = express();
app.use(express.json());
let todos = [{ id: 1, title: "Learn Express", done: false }];
let nextId = 2;
app.get("/api/todos", (req, res) => res.json(todos));
app.post("/api/todos", (req, res) => {
const title = (req.body.title || "").trim();
if (!title) return res.status(400).json({ error: "title is required" });
const todo = { id: nextId++, title, done: false };
todos.push(todo);
res.status(201).json(todo);
});
app.delete("/api/todos/:id", (req, res) => {
todos = todos.filter(t => t.id !== Number(req.params.id));
res.status(204).end();
});
app.listen(3000, () => console.log("API running on http://localhost:3000"));Run with node server.js and open http://localhost:3000/api/todos.
Status codes to know
200OK,201Created,204No Content400Bad Request,401Unauthorized,403Forbidden,404Not Found500Server Error
Good practice
- Validate every input on the server.
- Return clear error messages.
- Use environment variables for secrets:
process.env.DB_PASSWORD. - Enable CORS only for origins you trust.
Practice
Add a PATCH route to mark a to-do as done and test all routes with a tool like Postman or curl.