This article systematically organizes the status codes in the HTTP protocol, categorizing and analyzing their meanings and applicable scenarios, which can help developers quickly locate request issues and optimize interaction logic. It also designs a standard based on the combination of HTTP methods and status codes.
Detailed Explanation of HTTP Status Codes: Uses and Meanings
HTTP status codes are indicators of the server’s response to client requests, used to quickly determine the success, failure, or need for further action of a request.
- 2xx: Success, focusing on
<span>200</span>,<span>201</span>, and<span>204</span>. - 3xx: Redirection, distinguishing between
<span>301</span>(permanent) and<span>302</span>(temporary). - 4xx: Client errors,
<span>400</span>(syntax),<span>401</span>(unauthorized),<span>403</span>(forbidden). - 5xx: Server errors,
<span>500</span>(general),<span>502</span>(bad gateway),<span>503</span>(service unavailable).
Below are detailed explanations of the 2xx, 3xx, 4xx, and 5xx status codes, including applicable scenarios and typical use cases.
1. (2xx) Success
Indicates that the request has been successfully received, understood, and processed by the server.
200 OK
- Use: Standard success response, indicating that the request has been successfully completed.
- Typical Scenarios:
<span>GET</span>request successfully retrieves resources (e.g., querying user information).<span>PUT</span>or<span>PATCH</span>request successfully updates resources.- Example:
HTTP/1.1 200 OK Content-Type: application/json {"id": 1, "name": "John Doe"}
201 Created
- Use: Resource created successfully, typically used for
<span>POST</span>requests. - Requirements: The response should include the URI of the new resource (
<span>Location</span>header). - Typical Scenarios:
- User registration successful, returning new user ID.
- Returning order details after creating an order.
- Example:
HTTP/1.1 201 Created Location: /api/users/123 Content-Type: application/json {"id": 123, "status": "active"}
204 No Content
- Use: Request succeeded, but no content to return.
- Typical Scenarios:
<span>DELETE</span>request successfully deletes a resource.<span>PUT</span>/<span>PATCH</span>updates successfully but does not require returning data.- Example:
HTTP/1.1 204 No Content
206 Partial Content
- Use: The server returns partial content, suitable for chunked downloads or resuming downloads.
- Typical Scenarios:
- Segmented loading of video streams.
- Supporting
<span>Range</span>requests during large file downloads. - Example:
HTTP/1.1 206 Partial Content Content-Range: bytes 0-999/5000 Content-Length: 1000 [Binary Data...]
2. (3xx) Redirection
Indicates that the client needs to take further action to complete the request (e.g., redirecting to a new URL).
301 Moved Permanently
- Use: The resource has been permanently moved to a new URL, and the client should update bookmarks.
- SEO Impact: Search engines will update their indexes.
- Example:
HTTP/1.1 301 Moved Permanently Location: https://new.example.com/resource
302 Found (Temporary Redirect)
- Use: The resource has been temporarily moved to a new URL, and subsequent requests should still use the original address.
- Typical Scenarios:
- Short link redirection.
- Temporarily redirecting to the homepage after login.
- Example:
HTTP/1.1 302 Found Location: /temp-redirect
304 Not Modified
- Use: The resource has not been modified, and the client can continue using the cache.
- Trigger Conditions: The request header includes
<span>If-Modified-Since</span>or<span>If-None-Match</span>. - Example:
HTTP/1.1 304 Not Modified
308 Permanent Redirect
- Use: Similar to
<span>301</span>, but forces the original HTTP method to be maintained (e.g.,<span>POST</span>will not change to<span>GET</span>). - Typical Scenarios:
- Ensuring the request method remains unchanged during API migration.
- Example:
HTTP/1.1 308 Permanent Redirect Location: https://new-api.example.com
3. (4xx) Client Errors
Indicates that the client request is incorrect and needs to be corrected before retrying.
400 Bad Request
- Use: Request syntax error, the server cannot parse.
- Typical Scenarios:
- Invalid JSON format.
- Missing required parameters.
- Example:
HTTP/1.1 400 Bad Request {"error": "Invalid JSON format"}
401 Unauthorized
- Use: No valid credentials provided (login required).
- Requirements: The response header should include
<span>WWW-Authenticate</span>. - Example:
HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="API"
403 Forbidden
- Use: Identity verified, but no access rights (distinguished from
<span>401</span>). - Typical Scenarios:
- Ordinary users attempting to access admin interfaces.
- IP being blacklisted.
- Example:
HTTP/1.1 403 Forbidden {"error": "Insufficient permissions"}
404 Not Found
- Use: The requested resource does not exist.
- Typical Scenarios:
- Invalid URL accessed.
- No results from database queries.
- Example:
HTTP/1.1 404 Not Found {"error": "User not found"}
429 Too Many Requests
- Use: Client request frequency is too high (triggering rate limiting).
- Typical Scenarios:
- API calls exceeding quota.
- Preventing brute force attacks.
- Example:
HTTP/1.1 429 Too Many Requests Retry-After: 60 # Retry after 60 seconds
4. (5xx) Server Errors
Indicates that an error occurred while the server was processing the request, requiring backend fixes.
500 Internal Server Error
- Use: General server error, no specific information.
- Typical Scenarios:
- Code exceptions (e.g., uncaught
<span>NullPointerException</span>). - Example:
HTTP/1.1 500 Internal Server Error {"error": "Server encountered an error"}
502 Bad Gateway
- Use: The gateway/proxy server received an invalid response from the upstream server.
- Typical Scenarios:
- Backend service connected by Nginx crashes.
- Example:
HTTP/1.1 502 Bad Gateway
503 Service Unavailable
- Use: The server is temporarily unavailable (overloaded or under maintenance).
- Recommendations: Use with
<span>Retry-After</span>header. - Example:
HTTP/1.1 503 Service Unavailable Retry-After: 3600 # Retry after 1 hour
504 Gateway Timeout
-
Use: The gateway timed out waiting for a response from the upstream server.
-
Typical Scenarios:
- Database query timeout.
- Slow response from third-party APIs.
-
Example:
HTTP/1.1 504 Gateway Timeout
Key Points and Scenario Recommendations
- Cache Optimization: Proper use of
<span>304</span>can significantly reduce redundant transmissions. - Access Control:
<span>401</span>should be used with<span>WWW-Authenticate</span>header, while<span>403</span>directly denies access. - Redirection Choices:
- Use
<span>301</span>or<span>308</span>for permanent migrations (SEO friendly); - Use
<span>302</span>or<span>307</span>for temporary adjustments (preserving original method).
<span>502/504</span>are often related to proxies or upstream services;<span>503</span>requires checking server load or maintenance status.
HTTP status codes are the “language” of front-end and back-end interactions. Accurately understanding their meanings can quickly locate issues. For example:
- If encountering
<span>429</span>, optimize request frequency or negotiate throttling strategies; <span>204</span>is suitable for operations that do not require returning data (e.g., logging). It is recommended to choose the most appropriate status code based on specific business scenarios to enhance the standardization of API design.
Standard Combinations of HTTP Methods and Status Codes
1. GET (Retrieve Resource)
- 200 OK: Successfully returns the resource (e.g., retrieving user information).
- 404 Not Found: Resource does not exist.
- 304 Not Modified: Cache is valid (used with
<span>If-Modified-Since</span>or<span>ETag</span>).
2. POST (Create Resource)
-
201 Created: Resource created successfully, the response body must include the URI of the new resource (
<span>Location</span>header).HTTP/1.1 201 Created Location: /api/users/123 -
202 Accepted: The request has been accepted but not completed (suitable for asynchronous tasks).
-
400 Bad Request: Invalid request data (e.g., missing fields or format errors).
3. PUT (Full Update Resource)
- 200 OK or 204 No Content: Update successful (the latter is used when there is no response body).
- 404 Not Found: Resource does not exist (if the resource must exist).
- 409 Conflict: Resource state conflict (e.g., version mismatch).
4. PATCH (Partial Update Resource)
- 200 OK: Returns the updated complete resource.
- 204 No Content: Only updates without returning.
- 422 Unprocessable Entity: Semantic error (e.g., field validation failure).
5. DELETE (Delete Resource)
- 204 No Content: Deletion successful (no response body).
- 404 Not Found: Resource does not exist (if idempotency is required).
6. HEAD (Get Metadata)
- 200 OK: Same as GET, but without response body.