REST API
REST API is a common way for apps to communicate over HTTP.
In a REST API, the server exposes resources like users, products, or orders.
Most REST APIs send and receive JSON.
Basics
Section titled “Basics”What REST Means
Section titled “What REST Means”REST stands for Representational State Transfer.
You do not need to remember the full name.
The important idea is this:
- the URL points to a resource
- the HTTP method tells what action you want
Example:
GET /usersmeans get all usersGET /users/1means get one userPOST /usersmeans create a new user
Resources And Endpoints
Section titled “Resources And Endpoints”A resource is the thing your API works with.
Examples:
userspostsproductsorders
An endpoint is a specific method and path together.
Examples:
GET /usersPOST /usersDELETE /users/1
HTTP Methods
Section titled “HTTP Methods”These are the main methods you need to know:
| Method | Purpose |
|---|---|
| GET | read data |
| POST | create new data |
| PUT | replace all data |
| PATCH | update part of data |
| DELETE | remove data |
Simple example:
| Action | Route |
|---|---|
| Get all users | GET /users |
| Get one user | GET /users/1 |
| Create a user | POST /users |
| Update a user | PATCH /users/1 |
| Delete a user | DELETE /users/1 |
Route Params And Query Params
Section titled “Route Params And Query Params”Route Params
Section titled “Route Params”Use a route param when you want one specific item.
Example:
GET /users/42
Here, 42 is the user id.
Query Params
Section titled “Query Params”Use query params for filtering, searching, sorting, or pagination.
Examples:
GET /users?role=adminGET /users?page=2GET /products?sort=price
Simple rule:
- route param = one item
- query param = change the list
Request And Response
Section titled “Request And Response”When a client sends a request, it usually contains:
- a method
- a URL
- sometimes headers
- sometimes a body
Example request body:
{ "name": "Alice", "email": "alice@example.com"}Example JSON response:
{ "id": 1, "name": "Alice", "email": "alice@example.com"}Status Codes
Section titled “Status Codes”Status codes tell the client what happened.
Common ones:
200 OKfor success201 Createdfor a new item400 Bad Requestfor invalid input401 Unauthorizedwhen login is required404 Not Foundwhen the resource does not exist500 Internal Server Errorwhen the server fails
Small Example
Section titled “Small Example”app.get('/users', (req, res) => { res.json([ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, ]);});
app.post('/users', (req, res) => { res.status(201).json({ id: 3, name: 'Charlie' });});In this example:
GET /usersreturns dataPOST /userscreates datares.json()sends JSON back
Good REST Habits
Section titled “Good REST Habits”- keep routes simple and predictable
- use nouns like
/usersand/products - return JSON consistently
- use the correct status code
- keep request and response shapes clear