Concept
Rest API Principles
A REST API exposes resources (such as users, orders, articles) using standard HTTP verbs. In Express, you map resources to endpoints:
GET /users: Retrieve a list of users.GET /users/:id: Retrieve a specific user profile.POST /users: Create a new user record.PUT /users/:id: Overwrite/update a user.DELETE /users/:id: Delete a user.
Request Body Parsing
HTTP request bodies arrive as raw streams. To read JSON payloads inside req.body, Express requires a body-parser middleware to compile bytes into objects:
app.use(express.json()); // Global body-parser middleware
app.post('/orders', (req, res) => {
const newOrder = req.body; // Parses incoming JSON automatically
res.status(201).json(newOrder); // Returns 201 Created status
});Semantic Status Codes
A robust REST API returns appropriate HTTP status codes:
- 200 OK: Request completed successfully.
- 201 Created: Resource created successfully.
- 400 Bad Request: Validation or parameter syntax error.
- 401 Unauthorized: Missing or invalid credentials.
- 403 Forbidden: Valid credentials, but lacks access permissions.
- 404 Not Found: Resource does not exist.
- 500 Internal Server Error: Unhandled backend server crashes.
Common Mistakes
1. Returning generic 200 OK for validation failures or errors
Returning 200 OK with an error message payload like { error: "Invalid Email" } forces clients to parse response bodies to detect failures. Always use semantic codes (e.g. 400 Bad Request) so HTTP clients can handle errors automatically.
2. Forgetting to configure the JSON parser middleware
If you try to read req.body without registering app.use(express.json()), req.body will return undefined or an empty object, causing database validations to fail.
Best Practices
- Match HTTP Verbs to Intent: Do not use
GETfor actions that write or modify data (e.g./api/delete-user). Keep GET safe and idempotent. - Return Structured Error Envelopes: Maintain a consistent error response layout across all endpoints:
{ "success": false, "error": { "code": "VALIDATION_FAILED", "message": "Email is required" } } - Limit Payload Sizes: Enforce limit bounds on body parsing middleware to prevent Denial of Service (DoS) attacks via massive JSON uploads:
