REST API Design Made Simple with Express.js
What Is a REST API?
REST stands for:
Representational State Transfer
A REST API allows:
Client ↔ Server communication
Usually using HTTP requests.
Real-World Example
Frontend application:
Requests user data
Sends form data
Updates profile
Deletes records
Backend API handles these operations.
API Communication Flow
What Are Resources?
In REST, everything is treated as a resource.
Examples:
Example Resource
We will use:
/users
HTTP Methods
REST APIs use HTTP methods to perform actions.
CRUD vs HTTP Methods
GET Request
Used to fetch data.
Example
app.get("/users", (req, res) => {
res.send("Get all users");
});
GET Single User
app.get("/users/:id", (req, res) => {
res.send(`Get user ${req.params.id}`);
});
POST Request
Used to create new data.
Example
app.post("/users", (req, res) => {
res.send("Create user");
});
PUT Request
Used to update existing data.
Example
app.put("/users/:id", (req, res) => {
res.send(`Update user ${req.params.id}`);
});
DELETE Request
Used to remove data.
Example
app.delete("/users/:id", (req, res) => {
res.send(`Delete user ${req.params.id}`);
});
REST Route Structure
Why REST Route Naming Matters
Good REST APIs use clean resource-based naming.
Good Examples
/users /products /orders
Avoid
/getUsers /createUser /deleteUser
HTTP methods already describe the action.
Complete Express Example
const express = require("express");
const app = express();
app.use(express.json());
app.get("/users", (req, res) => {
res.json([
{ id: 1, name: "Ali" },
{ id: 2, name: "Sara" }
]);
});
app.post("/users", (req, res) => {
res.status(201).json({
message: "User created"
});
});
app.put("/users/:id", (req, res) => {
res.json({
message: `User ${req.params.id} updated`
});
});
app.delete("/users/:id", (req, res) => {
res.json({
message: `User ${req.params.id} deleted`
});
});
app.listen(3000);
What Is express.json()?
app.use(express.json());
Allows Express to read JSON request bodies.
Status Codes Basics
Status codes tell client what happened.
Common Status Codes
Example
res.status(201).json({
message: "User created"
});
REST Request-Response Lifecycle
REST API Design Principles
Example API Endpoints
Common Beginner Mistakes
Using Wrong HTTP Method
Incorrect:
GET /createUser
Correct:
POST /users
Verb-Based URLs
Incorrect:
/deleteProduct
Correct:
/products/:id
with DELETE method.
Why REST Became Popular
REST APIs are:
Simple
Standardized
Scalable
Easy for frontend/backend communication
Real-World Usage
REST APIs power:
Mobile apps
React frontends
SaaS platforms
Third-party integrations
Key Takeaways
Final Notes
REST API design is one of the most important backend development skills because almost every modern application depends on APIs.
Understanding REST fundamentals makes it easier to build:
Frontend integrations
Mobile backends
SaaS applications
Scalable services
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!