REST API Basics
RESTful API principles and HTTP methods.
HTTP Methods
GET - Retrieve data
GET /api/users
GET /api/users/123
POST - Create resource
POST /api/users
Body: { "name": "John" }
PUT - Update/Replace
PUT /api/users/123
PATCH - Partial update
PATCH /api/users/123
DELETE - Remove resource
DELETE /api/users/123
Status Codes
2xx Success
200 OK - Request succeeded
201 Created - Resource created
204 No Content - Success, no body
4xx Client Errors
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
5xx Server Errors
500 Internal Server Error
503 Service Unavailable
REST Principles
Stateless
Each request contains all needed info
Resource-based URLs
/api/users not /api/getUsers
/api/users/123/posts
Use HTTP methods correctly
GET for reading only
POST/PUT/DELETE for changes
JSON responses
Content-Type: application/json
Node.js Example
Express REST API
const express = require("express");
const app = express();
app.use(express.json());
// GET all users
app.get("/api/users", (req, res) => {
res.json(users);
});
// GET single user
app.get("/api/users/:id", (req, res) => {
const user = users.find(u => u.id === req.params.id);
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
});
// POST create user
app.post("/api/users", (req, res) => {
const newUser = req.body;
users.push(newUser);
res.status(201).json(newUser);
});