← ProgrammingBack to top

HTTP and RESTful API

1. HTTP request method

HTTP (Hypertext Transfer Protocol) is an application layer protocol used for communication between client and server.

HTTP methodCorresponds to CRUDfunctionIdempotence
GETREADGet resourcesYes
POSTCREATECreate resources or submit data for processingNo (default)
PUTUPDATECreate or completely replace the target resourceYes
PATCHUPDATEPartially modified resourcesNo guarantee
DELETEDELETEDelete resourcesYes
HEADREADOnly get the response headers, do not return the response bodyYes
OPTIONS—Query the communication options supported by the serverYes

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
compositionDescription
schemeProtocol, such as HTTP, HTTPS
hostDomain name or IP address
portServer port
pathResource path
queryquery parameters
fragmentpage 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

  1. Use nouns to describe resources, usually in the plural.
  2. Use the HTTP method to differentiate between operations.
  3. Use the Query parameter to implement searching, filtering, sorting, and paging.
  4. Keep the URL hierarchy simple and avoid deep nesting.
  5. 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
parametersPurpose
city=1filter
limit=2020 items returned each time
offset=40Skip first 40 items
ordering=-scoreDescending order by score
search=TokyoSearch 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

Headerfunction
Content-TypeThe data type of the request body or response body
AcceptThe type of data the client wishes to receive
AuthorizationBring authentication credentials
CookieThe browser sends Cookie to the server
Set-CookieThe server requires browser setting Cookie
Cache-ControlControl caching policies
Accept-EncodingCompression algorithms supported by the client
Content-EncodingCompression algorithm used for response content
OriginSource information of the request source, commonly used in CORS
Access-Control-Allow-OriginSpecify origins that allow cross-origin access
ETagResource 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:

rangeCategorymeaning
1xxInformationalinformative response
2xxSuccessRequest successful
3xxRedirectionRedirect or cache verification
4xxClient ErrorClient request error
5xxServer ErrorServer error

2xx Success

status codeNamemeaning
200OKThe request is successful and data is usually returned
201CreatedResource created successfully
202AcceptedThe request has been accepted, but processing has not yet completed
204No ContentRequest 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 codeNamemeaning
301Moved Permanentlypermanent redirect
302Foundtemporary redirect
304Not ModifiedThe resource has not been modified and the cache can be reused.
307Temporary RedirectTemporary redirection, retaining request method
308Permanent RedirectPermanent redirect, retaining request method

Note: 304 is usually used for conditional requests, which is different from ordinary page jumps.

4xx client error

status codeNamemeaning
400Bad RequestThe request format is wrong or the parameters are illegal
401UnauthorizedMissing valid authentication credentials
403ForbiddenThe server refused to execute the request
404Not FoundThe resource does not exist or is not public
405Method Not AllowedThe HTTP method is not supported
406Not AcceptableUnable to provide response that meets the requirements of Accept
409ConflictConflicts with current resource status
410GoneThe resource is permanently unavailable
413Content Too LargeThe requested content exceeds the server limit
415Unsupported Media TypeThe data format of the request body is not supported
422Unprocessable ContentThe request format is recognized, but the content cannot be processed
429Too Many RequestsRequests 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 codeNamemeaning
500Internal Server ErrorServer internal error
502Bad GatewayGateway received invalid upstream response
503Service UnavailableService is temporarily unavailable
504Gateway TimeoutGateway 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:

instructionsmeaning
publicAllow shared cache storage
privateResponses can only be stored by private caches
no-cacheMust verify before reusing cache
no-storeDo not allow caching of stored responses
max-age=3600Cache freshness period is 3600 seconds
immutableResources 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

FeaturesHTTP/1.1HTTP/2HTTP/3
underlying transportTCPTCPQUIC (based on UDP)
MultiplexingNo HTTP/2-style multiplexingsupportsupport
Header compressionNo dedicated Header compression mechanismHPACKQPACK
Transport layer head-of-line blockingexistexistAvoid 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:

modulefocus
HTTP MethodGET、POST、PUT、PATCH、DELETE
HTTP FeaturesStateless, safe, idempotent
URLScheme、Host、Port、Path、Query
RESTfulResource orientation, HTTP method, status code
Request/ResponseHeader、Body、Status Code
HTTP status code2xx、3xx、4xx、5xx
cacheCache-Control、ETag、304
safeHTTPS、Authentication、CORS、CSRF
HTTP versionHTTP/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: