1. HTTP request method
HTTP (Hypertext Transfer Protocol) is an application layer protocol used for communication between client and server.
| HTTP method | Corresponds to CRUD | function | Idempotence |
|---|---|---|---|
| GET | READ | Get resources | Yes |
| POST | CREATE | Create resources or submit data for processing | No (default) |
| PUT | UPDATE | Create or completely replace the target resource | Yes |
| PATCH | UPDATE | Partially modified resources | No guarantee |
| DELETE | DELETE | Delete resources | Yes |
| HEAD | READ | Only get the response headers, do not return the response body | Yes |
| OPTIONS | — | Query the communication options supported by the server | Yes |
Idempotence (Idempotency)
The same request is executed once and multiple times, and the expected effect on the server is the same, which is called idempotent.
For example:
GET /users/1: Repeated reading should not change the server resource status.PUT /users/1: The same content is submitted repeatedly, and the final status of the resource is the same.DELETE /users/1: Duplicate deletion, the resources will eventually be in a non-existent state.POST /orders: Repeated submissions may create multiple orders, so the default is not idempotent.
Note: Idempotent does not mean that every response is exactly the same. For example, if you delete a resource repeatedly, 204 may be returned for the first time and 404 for the second time.
HTTP also distinguishes safe methods (Safe Methods). GET, HEAD, and OPTIONS are all safe methods, which means that the client does not request changes to the server resource state.
2. HTTP stateless
HTTP is a stateless protocol (Stateless Protocol).
The meaning is: when the server processes a certain HTTP request, it does not rely on the HTTP protocol to automatically remember the context of the previous request.
For example:
Client → GET /products
Server → Products
Client → GET /profile
Server → Profile
Each request requires information that the server needs to process the request.
But statelessness does not mean that the server cannot save user information.
In practical application:
- Cookie: The browser saves Cookie and sends it in subsequent requests.
- Session: The server can save the session state, and the client identifies the session through Session ID.
- JWT: The client can carry Token, and the server identifies the user after verification.
HTTP itself is stateless, but Web applications can implement stateful user sessions through Cookie, Session, Token and other mechanisms.
In addition, HTTP Keep-Alive can reuse the TCP connection, but connection reuse and application layer session state are two different concepts.
3. URL structure
Common URL structure:
scheme://host:port/path?query#fragment
For example:
https://api.example.com:443/api/v1/users?page=2#details
| composition | Description |
|---|---|
| scheme | Protocol, such as HTTP, HTTPS |
| host | Domain name or IP address |
| port | Server port |
| path | Resource path |
| query | query parameters |
| fragment | page fragment identifier |
Supplement:
- HTTP The default port is 80.
- HTTPS The default port is 443.
- Query parameters are commonly used for searching, filtering, paging, and sorting.
- Fragment is typically handled on the client side by the browser and is not sent to the server as part of the normal HTTP request target.
URI is a resource identifier, and URL is a type of URI, used to locate resources.
4. RESTful API design specifications
REST (Representational State Transfer) is an architectural style.
RESTful API is usually resource-centric and represents operations through the HTTP method.
URL Design
It is recommended to use nouns and plural forms:
/api/v1/users
/api/v1/users/{user_id}
/api/v1/users/{user_id}/orders
/api/v1/users/{user_id}/orders/{order_id}
It is generally not recommended to reuse verbs in URL:
GET /getUsers
POST /createUser
DELETE /deleteUser/1
More recommended:
GET /users
POST /users
GET /users/1
PUT /users/1
PATCH /users/1
DELETE /users/1
However, for business operations that cannot be naturally mapped to CRUD, action endpoints can also be used, for example:
POST /orders/123/cancel
POST /payments/123/refund
Such designs are common engineering practice and are not prohibited or required by REST.
URL Design Principles
- Use nouns to describe resources, usually in the plural.
- Use the HTTP method to differentiate between operations.
- Use the Query parameter to implement searching, filtering, sorting, and paging.
- Keep the URL hierarchy simple and avoid deep nesting.
- API versions can be placed in URL, such as
/api/v1/, but this is not the only way to manage versions.
5. Query Parameters
The Query parameter is typically used in GET requests:
GET /api/v1/pois?city=1&limit=20&offset=40
| parameters | Purpose |
|---|---|
city=1 | filter |
limit=20 | 20 items returned each time |
offset=40 | Skip first 40 items |
ordering=-score | Descending order by score |
search=Tokyo | Search keywords |
For complex searches, you can also use POST to carry the JSON request body, but the query semantics of this interface should be clearly defined.
6. HTTP Request / Response
Request structure
POST /api/v1/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer <token>
{
"name": "Alice",
"age": 25
}
Mainly includes:
- Request Method: Request method.
- URL: Requesting resources.
- Headers: Request metadata.
- Body: Request content if present.
Response structure
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/users/123
{
"id": 123,
"name": "Alice",
"age": 25
}
Mainly includes:
- Status Code: response status code.
- Headers: Response metadata.
- Body: Response content (if present).
7. Common HTTP Header
| Header | function |
|---|---|
| Content-Type | The data type of the request body or response body |
| Accept | The type of data the client wishes to receive |
| Authorization | Bring authentication credentials |
| Cookie | The browser sends Cookie to the server |
| Set-Cookie | The server requires browser setting Cookie |
| Cache-Control | Control caching policies |
| Accept-Encoding | Compression algorithms supported by the client |
| Content-Encoding | Compression algorithm used for response content |
| Origin | Source information of the request source, commonly used in CORS |
| Access-Control-Allow-Origin | Specify origins that allow cross-origin access |
| ETag | Resource version identifier, used for cache verification |
Content-Type and Accept
Content-Type: application/json
Accept: application/json
Difference:
Content-Type: What is the format of the current transmission content.Accept: What format the client wants the server to return.
Accept-Encoding and Content-Encoding
Accept-Encoding: br, gzip
Content-Encoding: br
Browsers support Brotli and gzip, servers choose Brotli compressed responses.
8. HTTP status code
HTTP status codes are divided into five categories:
| range | Category | meaning |
|---|---|---|
| 1xx | Informational | informative response |
| 2xx | Success | Request successful |
| 3xx | Redirection | Redirect or cache verification |
| 4xx | Client Error | Client request error |
| 5xx | Server Error | Server error |
2xx Success
| status code | Name | meaning |
|---|---|---|
| 200 | OK | The request is successful and data is usually returned |
| 201 | Created | Resource created successfully |
| 202 | Accepted | The request has been accepted, but processing has not yet completed |
| 204 | No Content | Request successful, no response body |
Common usage:
- GET Success: 200
- POST created successfully: 201
- PUT/PATCH modified successfully: 200 or 204
- DELETE Success: 204
- Async task accepted: 202
202 There is no guarantee that the asynchronous task will eventually be executed successfully.
3xx redirect
| status code | Name | meaning |
|---|---|---|
| 301 | Moved Permanently | permanent redirect |
| 302 | Found | temporary redirect |
| 304 | Not Modified | The resource has not been modified and the cache can be reused. |
| 307 | Temporary Redirect | Temporary redirection, retaining request method |
| 308 | Permanent Redirect | Permanent redirect, retaining request method |
Note: 304 is usually used for conditional requests, which is different from ordinary page jumps.
4xx client error
| status code | Name | meaning |
|---|---|---|
| 400 | Bad Request | The request format is wrong or the parameters are illegal |
| 401 | Unauthorized | Missing valid authentication credentials |
| 403 | Forbidden | The server refused to execute the request |
| 404 | Not Found | The resource does not exist or is not public |
| 405 | Method Not Allowed | The HTTP method is not supported |
| 406 | Not Acceptable | Unable to provide response that meets the requirements of Accept |
| 409 | Conflict | Conflicts with current resource status |
| 410 | Gone | The resource is permanently unavailable |
| 413 | Content Too Large | The requested content exceeds the server limit |
| 415 | Unsupported Media Type | The data format of the request body is not supported |
| 422 | Unprocessable Content | The request format is recognized, but the content cannot be processed |
| 429 | Too Many Requests | Requests are too frequent, triggering rate limiting |
The difference between 401 and 403
- 401: The client lacks valid authentication credentials and usually requires login or re-authentication.
- 403: The server understands the request but refuses to execute it, and may return 403 even if the client is authenticated.
The difference between 400 and 422
- 400: Usually indicates an error in the request format or parameters, and can also cover request validation failure.
- 422: The request syntax is correct and the content type is identifiable, but the server cannot process the instructions or semantics.
Different frameworks may choose different status codes for validation errors.
For example, a Serializer validation failure for Django REST Framework usually returns 400, while a request data validation error for FastAPI usually returns 422.
5xx server error
| status code | Name | meaning |
|---|---|---|
| 500 | Internal Server Error | Server internal error |
| 502 | Bad Gateway | Gateway received invalid upstream response |
| 503 | Service Unavailable | Service is temporarily unavailable |
| 504 | Gateway Timeout | Gateway timed out waiting for upstream response |
For Nginx + Django architecture:
- 500: Django may be caused by internal exception.
- 502: Nginx could not obtain a valid Django upstream response.
- 503: The server is temporarily unable to provide services.
- 504: Nginx timed out waiting for Django upstream response.
9. HTTP cache
HTTP caching avoids repeated downloading of unchanged resources.
Common response headers:
Cache-Control: public, max-age=31536000, immutable
Usually used for JS, CSS static resources with content hash.
Common Cache-Control instructions:
| instructions | meaning |
|---|---|
| public | Allow shared cache storage |
| private | Responses can only be stored by private caches |
| no-cache | Must verify before reusing cache |
| no-store | Do not allow caching of stored responses |
| max-age=3600 | Cache freshness period is 3600 seconds |
| immutable | Resources will not change during the fresh period |
ETag cache verification
The browser's first request:
GET /api/v1/data
The server returns:
HTTP/1.1 200 OK
ETag: "abc123"
Request again:
GET /api/v1/data
If-None-Match: "abc123"
If the resource has not changed, the server can return:
HTTP/1.1 304 Not Modified
The browser continues to use the content from the cache.
10. CORS and CSRF
CORS(Cross-Origin Resource Sharing)
Browsers restrict cross-origin reads of responses through the same-origin policy. CORS allows the server to declare which cross-origin requests can be accessed by the browser.
For example:
Access-Control-Allow-Origin: https://example.com
Cross-origin requests will first send OPTIONS preflight requests (Preflight Request) in some cases.
CORS is mainly a browser security mechanism, not the identity authentication mechanism of the backend API.
CSRF(Cross-Site Request Forgery)
CSRF is an attack that uses browsers to automatically carry authentication credentials such as Cookie to induce users to perform unexpected operations on logged-in websites.
Common defense methods:
- CSRF Token。
- SameSite attribute of Cookie.
- Check Origin/Referer.
- Do not use GET to implement the operation of modifying the server status.
CORS and CSRF are different security mechanisms and cannot replace each other.
11. HTTP/1.1、HTTP/2、HTTP/3
| Features | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| underlying transport | TCP | TCP | QUIC (based on UDP) |
| Multiplexing | No HTTP/2-style multiplexing | support | support |
| Header compression | No dedicated Header compression mechanism | HPACK | QPACK |
| Transport layer head-of-line blocking | exist | exist | Avoid TCP-style cross-flow head-of-line blocking |
Core differences:
- HTTP/1.1: Widely compatible, often using multiple TCP connections to improve concurrency.
- HTTP/2: Multiplex multiple requests on one connection to improve transmission efficiency.
- HTTP/3: Based on QUIC, it improves multi-stream transmission performance in the case of packet loss.
HTTP/2 and HTTP/3 do not change the basic semantics of methods such as GET and POST.
Summary
Core knowledge of HTTP and RESTful API:
| module | focus |
|---|---|
| HTTP Method | GET、POST、PUT、PATCH、DELETE |
| HTTP Features | Stateless, safe, idempotent |
| URL | Scheme、Host、Port、Path、Query |
| RESTful | Resource orientation, HTTP method, status code |
| Request/Response | Header、Body、Status Code |
| HTTP status code | 2xx、3xx、4xx、5xx |
| cache | Cache-Control、ETag、304 |
| safe | HTTPS、Authentication、CORS、CSRF |
| HTTP version | HTTP/1.1、HTTP/2、HTTP/3 |
For back-end API development, what needs to be mastered most is the semantics of the HTTP method, the correct use of status codes, idempotence, authentication and authorization, caching policies and cross-domain security.
reference document: