Table of Contents
Basic Understanding of HTTP Status Codes
1. What are HTTP status codes?
HTTP status codes are three-digit numbers returned by web servers in response to a client’s request made to a server. They indicate whether a specific HTTP request has been successfully completed, encountered an error, or requires further action. Status codes are part of the HTTP standard (Hypertext Transfer Protocol) and are grouped into five classes based on the first digit.
2. What are the five classes of HTTP status codes?
The five classes are:
- 1xx (Informational): The request was received, and the process is continuing
- 2xx (Success): The request was successfully received, understood, and accepted
- 3xx (Redirection): Further action needs to be taken to complete the request
- 4xx (Client Error): The request contains bad syntax or cannot be fulfilled by the server
- 5xx (Server Error): The server failed to fulfill a valid request
3. Who defines HTTP status codes?
HTTP status codes are defined by the Internet Engineering Task Force (IETF) in the HTTP specifications, primarily in RFC 7231 (which replaced RFC 2616). The IANA (Internet Assigned Numbers Authority) maintains the official registry of HTTP status codes.
4. Are HTTP status codes required in all HTTP responses?
Yes, every HTTP response must include a status code. If a server fails to include a status code, clients typically interpret this as a 200 OK status by default, though this behavior isn’t standardized and may vary by client implementation.
5. Can custom HTTP status codes be created?
While technically possible for a server to return any three-digit number, it’s not recommended to create custom status codes outside the standard ones. Non-standard codes may cause unpredictable behavior in clients. Instead, use standard codes with customized response bodies to convey specific information.
1xx: Informational Status Codes
6. What does a 100 Continue status mean?
The 100 Continue status indicates that the initial part of the request has been received and has not yet been rejected by the server. The client should continue with the request or ignore the response if the request is already finished. This is commonly used when clients want to know if a server will accept a large request before sending it entirely.
7. When is 101 Switching Protocols used?
The 101 Switching Protocols response is sent when the server agrees to switch protocols as requested by the client. This is commonly seen when upgrading from HTTP/1.1 to WebSocket connections, where the client sends an “Upgrade” header, and the server responds with 101 to confirm the protocol change.
8. What does a 102 Processing status indicate?
The 102 Processing status indicates that the server has received and is processing the request, but no response is available yet. This prevents the client from timing out and assuming the request was lost, particularly useful for operations that take significant time to process.
9. What is the purpose of 103 Early Hints?
The 103 Early Hints status code allows the server to send response headers before the final HTTP message. This lets browsers preload resources like CSS and JavaScript files while the server prepares the full response, improving page load performance.
10. Are 1xx status codes commonly seen in everyday browsing?
No, 1xx status codes are rarely visible to end users during normal browsing. These codes typically happen behind the scenes as part of the HTTP protocol negotiation between clients and servers. Most browsers and API clients handle these codes automatically without user interaction.
2xx: Success Status Codes
11. What does a 200 OK status code signify?
The 200 OK status code indicates that the request has succeeded. For GET requests, the response includes the requested resource. For POST requests, it might include a description of the action’s result. This is the standard “success” response for HTTP requests.
12. When should a 201 Created status code be used?
The 201 Created status code should be used when a request has been fulfilled and has resulted in one or more new resources being created. It’s typically returned in response to POST, PUT, or PATCH requests. The response should include a Location header pointing to the newly created resource.
13. What does a 202 Accepted response mean?
A 202 Accepted response indicates that the request has been accepted for processing, but the processing has not been completed. This status is especially useful for asynchronous operations when the server doesn’t want to wait for the completion of the requested process before sending a response.
14. When is a 204 No Content status appropriate?
A 204 No Content status is appropriate when the server has successfully processed the request but is not returning any content. It’s often used for DELETE operations or for PUT/PATCH requests where the client doesn’t need the updated representation of the resource.
15. What does a 206 Partial Content response indicate?
A 206 Partial Content response indicates that the server is delivering only part of the resource due to a range header sent by the client. This is commonly used for resuming interrupted downloads or for streaming media content, allowing clients to request specific portions of a file.
3xx: Redirection Status Codes
16. What is the purpose of 300 Multiple Choices?
The 300 Multiple Choices status indicates that the requested resource has multiple representations, each with its own specific location. The user (or user agent) can select a preferred representation and redirect to its location, though this code is rarely seen in practice compared to other 3xx codes.
17. What’s the difference between 301 and 302 redirects?
A 301 Moved Permanently redirect indicates that the requested resource has been permanently moved to a new URL, and future references should use the new URL. Search engines update their links to the new location.
A 302 Found (formerly Temporary Redirect) indicates a temporary redirect where the requested resource resides temporarily under a different URL. Future requests should still use the original URL.
18. When should a 303 See Other status be used?
A 303 See Other status should be used primarily after a POST request to redirect the user to a resource that can be accessed using a GET method, such as a confirmation page. It indicates that the response to the request can be found under a different URI and should be retrieved using a GET method.
19. What does a 304 Not Modified response mean?
A 304 Not Modified response indicates that the resource has not been modified since the version specified by the request headers (If-Modified-Since or If-None-Match). The client can continue to use their cached version of the resource, saving bandwidth since no response body is transmitted.
20. How does a 307 Temporary Redirect differ from 302?
While both indicate a temporary redirect, 307 Temporary Redirect specifically preserves the request method during redirection. With 302, some clients historically changed POST requests to GET when redirecting, but 307 guarantees that a POST request will remain a POST after redirection, maintaining RESTful behavior.
4xx: Client Error Status Codes
21. What does a 400 Bad Request status mean?
A 400 Bad Request status indicates that the server cannot or will not process the request due to a client error, such as malformed request syntax, invalid request message framing, or deceptive request routing. The client should modify the request before resubmitting.
22. When is a 401 Unauthorized status returned?
A 401 Unauthorized status is returned when authentication is required but has either failed or not been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. Despite its name, this status is about authentication, not authorization.
23. What’s the difference between 401 Unauthorized and 403 Forbidden?
401 Unauthorized indicates that authentication is required and has failed or hasn’t been provided—essentially “you need to log in.”
403 Forbidden indicates that the server understood the request but refuses to authorize it—meaning “I know who you are, but you don’t have permission for this resource.” Unlike 401, re-authenticating won’t help with a 403 error.
24. What does a 404 Not Found status indicate?
A 404 Not Found status indicates that the server can’t find the requested resource. It could mean the URL is mistyped, the resource has been deleted or moved, or the server is configured not to disclose whether the resource exists for security reasons. This is one of the most commonly encountered HTTP errors.
25. What is a 405 Method Not Allowed response?
A 405 Method Not Allowed response indicates that the request method (GET, POST, PUT, DELETE, etc.) is known by the server but is not supported for the requested resource. For example, a resource might allow GET and POST but not DELETE. The response must include an Allow header listing valid methods.
26. When might a 406 Not Acceptable status be returned?
A 406 Not Acceptable status is returned when the server cannot produce a response matching the list of acceptable values defined in the request’s Accept headers (like content types, character sets, encodings, or languages). This means the server can’t generate content that the client is willing to accept.
27. What does a 408 Request Timeout mean?
A 408 Request Timeout response indicates that the server timed out waiting for the request from the client. The client began the request but didn’t complete it within the server’s timeout period. The client may repeat the request without modifications at any later time.
28. What causes a 409 Conflict status code?
A 409 Conflict status code indicates that the request couldn’t be completed due to a conflict with the current state of the target resource. This is often encountered in situations where multiple users are trying to modify the same resource simultaneously, or when attempting to create a resource that already exists.
29. When is a 410 Gone status appropriate?
A 410 Gone status is appropriate when the requested resource is permanently unavailable and no forwarding address is known. This is similar to 404 but indicates the resource once existed but has been deliberately removed with no forwarding address. It’s useful for API versioning or resource retirement.
30. What does a 413 Payload Too Large response mean?
A 413 Payload Too Large response indicates that the request entity is larger than limits defined by server; the server might close the connection or return a Retry-After header field. This commonly occurs when uploading files that exceed maximum size limits set by the server.
31. What is a 415 Unsupported Media Type response?
A 415 Unsupported Media Type response indicates that the server refuses to accept the request because the payload format (specified in the Content-Type header) is in an unsupported format. For example, sending a JSON payload when the server only accepts XML.
32. What does a 429 Too Many Requests indicate?
A 429 Too Many Requests response indicates that the user has sent too many requests in a given amount of time (“rate limiting”). The server typically includes a Retry-After header indicating how long to wait before making another request. This is important for API design to prevent abuse.
5xx: Server Error Status Codes
33. What does a 500 Internal Server Error mean?
A 500 Internal Server Error indicates a generic server-side error message when the server encounters an unexpected condition that prevented it from fulfilling the request. This could be due to server misconfiguration, application errors, database issues, or other server-side problems not specific enough to use other 5xx codes.
34. When might a 501 Not Implemented status be returned?
A 501 Not Implemented status is returned when the server does not support the functionality required to fulfill the request. This might be because the server doesn’t recognize the request method or lacks the ability to fulfill it. It indicates a permanent limitation, not a temporary error.
35. What does a 502 Bad Gateway response signify?
A 502 Bad Gateway response signifies that the server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request. This often occurs in load-balanced environments when a backend server is malfunctioning.
36. What’s the meaning of a 503 Service Unavailable response?
A 503 Service Unavailable response means the server is temporarily unable to handle the request due to maintenance or overloading. This is typically a temporary condition that will be alleviated after some delay. The server may include a Retry-After header indicating how long the client should wait before retrying.
37. When might a server return a 504 Gateway Timeout?
A 504 Gateway Timeout is returned when a server acting as a gateway or proxy did not receive a timely response from an upstream server it needed to access to complete the request. This typically happens when the upstream server is slow or unresponsive, but the gateway server has a timeout configured.
Common Status Codes in Web Development
38. Which HTTP status codes are most commonly encountered during web browsing?
The most commonly encountered status codes during normal web browsing are:
- 200 OK (successful responses)
- 301/302 (redirects)
- 304 Not Modified (cached content)
- 404 Not Found (missing resources)
- 500 Internal Server Error (server problems)
These represent the majority of everyday HTTP transactions, though browsers typically only show errors to users (mainly 404 and 500).
39. Which status codes are most important for SEO?
The most important HTTP status codes for SEO are:
- 200 OK (indicates content that should be indexed)
- 301 Moved Permanently (preserves link equity when URLs change)
- 404 Not Found (helps search engines understand which pages don’t exist)
- 410 Gone (signals permanently removed content)
- 500/503 (alerts to site problems that could affect indexing)
Search engines like Google use these status codes to determine how to crawl and index websites.
40. How do browsers typically handle different status codes?
Browsers handle status codes differently:
- 200-level codes: Display the content normally
- 300-level redirects: Automatically follow them, usually without user awareness
- 304 Not Modified: Use cached content without showing any error
- 400/500 level errors: Display error pages, either the server’s custom error page or the browser’s built-in error page
- 401/403: May prompt for authentication or display permission errors
Most status codes are invisible to users unless they’re error codes.
41. Which status codes should REST APIs return?
RESTful APIs should use a range of status codes to properly indicate different outcomes:
- 200 OK for successful operations
- 201 Created when a resource is successfully created
- 204 No Content for successful operations with no response body
- 400 Bad Request for malformed requests
- 401/403 for authentication/authorization failures
- 404 for resources not found
- 405 Method Not Allowed for unsupported HTTP methods
- 409 Conflict for resource conflicts
- 422 Unprocessable Entity for validation errors
- 429 Too Many Requests for rate limiting
- 500 for server errors
Proper status code usage makes APIs more intuitive and easier to integrate with.
42. How should e-commerce websites handle HTTP status codes?
E-commerce websites should handle status codes carefully:
- Use 200 OK for product pages and successful transactions
- Implement 301 redirects for moved or renamed products
- Return 404 for discontinued products (or 410 if permanently removed)
- Use 503 with Retry-After during maintenance windows
- Implement custom, helpful error pages for 404/500 errors with search functionality and recommended products
- Return appropriate 4xx codes for checkout errors with clear explanations
Good status code implementation improves both user experience and SEO for e-commerce sites.
HTTP Status Codes and SEO
43. How do search engines interpret 301 vs. 302 redirects?
Search engines treat 301 and 302 redirects differently:
With 301 Moved Permanently redirects, search engines:
- Transfer most of the link equity (ranking power) from the old URL to the new one
- Eventually drop the old URL from their index and replace it with the new URL
- Consider this a permanent change
With 302 Found (temporary) redirects:
- Keep the old URL in the index as the canonical version
- Do not transfer as much link equity to the new URL
- Continue to periodically check if the redirect is still in place
Using the correct redirect type is crucial for maintaining SEO during site restructuring.
44. How do 404 errors impact SEO?
404 errors impact SEO in several ways:
- A few 404 errors for non-existent pages are normal and won’t hurt SEO
- Excessive 404s may signal poor site quality to search engines
- 404s for previously indexed pages can lead to loss of traffic and ranking
- If important pages return 404s, the link equity flowing to them is wasted
- Links pointing to 404 pages are essentially dead ends for search engine crawlers
Best practice is to implement 301 redirects for valuable pages that no longer exist and maintain a helpful custom 404 page for genuine errors.
45. Is it better to use 404 or 410 for removed content from an SEO perspective?
From an SEO perspective:
A 410 Gone status provides a stronger signal to search engines that content has been deliberately removed and will not return. This can lead to faster de-indexing of the URL compared to a 404.
A 404 Not Found is more ambiguous and may cause search engines to check back later to see if the content returns.
For permanently removed content where you want fast removal from search indexes, 410 is generally preferred. However, in practice, many sites use 404 for all missing content regardless of reason, and search engines have adapted to this convention.
46. How should soft 404 errors be handled for SEO?
Soft 404 errors (pages that return 200 OK status but actually display “not found” content) should be avoided for SEO because:
- They confuse search engines by indicating content exists when it doesn’t
- They waste crawl budget on non-existent pages
- They can lead to poor-quality pages being indexed
To fix soft 404s:
- Return proper 404 HTTP status codes for truly missing content
- Implement 301 redirects for moved content
- Ensure your custom 404 page returns the actual 404 status code
- Use Google Search Console to identify and fix soft 404 issues
Proper error handling provides clear signals to search engines about your site’s content.
47. How do search engines handle 5xx server errors?
Search engines handle 5xx server errors in the following ways:
- Temporary treatment: For occasional 5xx errors, search engines will typically retry the URL later without immediately affecting rankings
- Persistent issues: If 5xx errors continue over time, search engines may:
- Reduce crawling frequency of the affected site
- Gradually drop pages from the index
- Negatively impact rankings due to poor user experience
- Flag the site in tools like Google Search Console
During planned maintenance, using 503 Service Unavailable with a Retry-After header is recommended to inform search engines when to return, minimizing SEO impact.
HTTP Status Codes in Security
48. How are HTTP status codes relevant to web security?
HTTP status codes play several important roles in web security:
- Authentication failures (401) signal improper credential usage
- Authorization issues (403) indicate potential access attempts to restricted resources
- Certain error responses might leak sensitive system information if not properly configured
- Consistent error handling prevents information disclosure
- Rate limiting (429) helps prevent brute force attacks
- Unexpected status codes may indicate potential attacks or probing
- Status code timing differences can potentially reveal information in side-channel attacks
Properly implementing status codes is an important aspect of defense in depth for web applications.
49. What security implications does a 401 Unauthorized response have?
A 401 Unauthorized response has several security implications:
- It indicates authentication is required but hasn’t been provided or has failed
- It should include a WWW-Authenticate header specifying the authentication scheme
- Multiple 401 responses from the same IP may indicate brute force attempts
- The response should not reveal whether a username exists (to prevent user enumeration)
- Timing differences in 401 responses should be minimized to prevent username discovery
- After multiple failed attempts, additional security measures like temporary IP blocking or CAPTCHA challenges may be appropriate
Proper implementation of 401 responses is critical for secure authentication systems.
50. How should 403 Forbidden responses be handled securely?
Secure handling of 403 Forbidden responses includes:
- Providing minimal information about why access was denied
- Not revealing the existence of sensitive resources
- Logging access attempts for security monitoring
- Ensuring consistent response times to prevent information leakage
- Considering whether 404 Not Found might be more appropriate in some cases to hide resource existence
- Including enough information for legitimate users to understand the issue without revealing system details
The goal is to deny access while minimizing information disclosure to potential attackers.
51. What role do status codes play in preventing information disclosure?
Status codes help prevent information disclosure by:
- Using generic error messages that don’t reveal system internals
- Implementing consistent error handling across an application
- Avoiding status codes that reveal the existence of sensitive resources
- Sometimes using 404 instead of 403 to hide resource existence
- Ensuring status pages don’t include stack traces, system paths, or database information
- Maintaining consistent response times to prevent timing attacks
- Providing custom error pages that don’t reveal server software or versions
Proper status code implementation is part of the principle of least privilege applied to information sharing.
52. How can HTTP status codes help identify potential attacks?
HTTP status codes can help identify potential attacks through:
- Unusual patterns of 401/403 responses (potential brute force or authorization bypass attempts)
- Sequences of 404 responses for non-existent paths (directory enumeration attempts)
- High volumes of 400 Bad Request responses (potential fuzzing or injection attempts)
- Patterns of 405 Method Not Allowed (API scanning)
- Sequences of 5xx errors with unusual parameters (potential injection or DoS attempts)
- Suspicious patterns of 302 redirects (open redirect probing)
Security monitoring systems often analyze patterns of status codes as part of threat detection.
HTTP Status Codes in Modern Web Architecture
53. How are HTTP status codes used in RESTful API design?
In RESTful API design, HTTP status codes serve as a standardized way to communicate outcomes:
- 200 OK for successful requests that return content
- 201 Created when resources are successfully created
- 204 No Content for successful operations without response bodies
- 400 Bad Request for malformed or invalid requests
- 401/403 to distinguish between authentication and authorization failures
- 404 for resources that don’t exist
- 405 Method Not Allowed for unsupported HTTP methods on resources
- 409 Conflict for resource state conflicts
- 422 Unprocessable Entity for semantic validation errors
- 429 Too Many Requests for rate limiting
Proper status code usage makes APIs self-documenting and enables client code to handle different scenarios appropriately.
54. How do microservices architectures use HTTP status codes?
In microservices architectures, HTTP status codes are crucial for:
- Inter-service communication outcomes
- Circuit breaking decisions (e.g., stopping requests after multiple 5xx errors)
- Service health reporting
- API gateway routing and response handling
- Aggregating responses from multiple downstream services
- Handling partial failures when composing responses from multiple services
- Service discovery and health checking
- Distributed tracing and error correlation
With many services communicating via HTTP, consistent status code usage becomes essential for system reliability and observability.
55. How do single-page applications (SPAs) handle HTTP status codes?
Single-page applications handle HTTP status codes differently than traditional websites:
- AJAX/fetch requests interpret status codes programmatically rather than triggering browser navigation
- SPAs must implement custom error handling for 4xx/5xx responses in API calls
- Client-side routing doesn’t generate real HTTP status codes for navigational changes
- Server-side rendering or pre-rendering may be needed to return proper status codes for SEO
- SPAs often implement custom error states rather than relying on browser error pages
- Status code 204 (No Content) is often used for successful operations that don’t return data
This requires developers to carefully handle status codes in application code rather than relying on browser behavior.
56. How do content delivery networks (CDNs) leverage HTTP status codes?
CDNs use HTTP status codes in several ways:
- 200/304 decisions for serving cached content vs. validating with origin
- Custom error pages for various status codes
- Edge computing logic based on status code responses
- Cache control decisions based on origin server status codes
- 5xx failover to alternate origins or cached versions
- Distinguishing between CDN errors (edge server issues) and origin errors
- Geolocation or IP-based blocking (typically 403)
- DDoS protection responses (429 or custom status codes)
CDNs often allow custom behaviors to be configured based on specific status code responses from origin servers.
57. What role do HTTP status codes play in GraphQL implementations?
GraphQL has a unique relationship with HTTP status codes:
- Unlike REST, GraphQL typically returns 200 OK even for operations with errors
- Errors are conveyed in the response body’s “errors” field rather than via status codes
- 400 Bad Request may be used for malformed GraphQL syntax
- 401/403 may still be used for authentication/authorization before GraphQL processing
- 429 Too Many Requests for rate limiting
- 5xx errors for server failures that prevent GraphQL execution
- Some implementations use 4xx codes for validations, but this isn’t standard
This approach centralizes error handling in the response data structure rather than relying on HTTP status codes, which can be both an advantage and a limitation.
Handling HTTP Status Codes in Different Languages
58. How do you handle HTTP status codes in JavaScript/Node.js?
In JavaScript/Node.js, HTTP status codes are handled in several ways:
Browser-side:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
// Response.ok is true if status is 200-299
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Node.js server (Express):
app.get('/resource', (req, res) => {
if (!resourceExists) {
return res.status(404).json({ error: 'Resource not found' });
}
if (!userAuthorized) {
return res.status(403).json({ error: 'Forbidden' });
}
// Success case
res.status(200).json(resource);
});
Node.js also provides the http.STATUS_CODES object, which maps status codes to their official descriptions.
59. How do you handle HTTP status codes in Python?
In Python, HTTP status codes are typically handled using libraries like requests or frameworks like Django or Flask:
Client-side with requests:
import requests
response = requests.get('https://api.example.com/data')
try:
# Raises an HTTPError for 4xx/5xx responses
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
print(f"Status Code: {response.status_code}")
Server-side with Flask:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/resource')
def get_resource():
if not resource_exists:
return jsonify(error="Resource not found"), 404
if not user_authorized:
return jsonify(error="Forbidden"), 403
# Success case
return jsonify(resource), 200
Python’s http.HTTPStatus enum (in the standard library) provides status codes and their descriptions.
60. How do you handle HTTP status codes in Java?
In Java, HTTP status codes are handled differently depending on whether you’re writing client or server code:
Client-side with HttpClient (Java 11+):
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data"))
.build();
try {
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
if (statusCode >= 200 && statusCode < 300) {
String body = response.body();
System.out.println(body);
} else {
System.out.println("Error: " + statusCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Server-side with Spring:
@RestController
public class ResourceController {
@GetMapping("/resource/{id}")
public ResponseEntity<Object> getResource(@PathVariable Long id) {
if (!resourceExists(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse("Resource not found"));
}
if (!userAuthorized()) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new ErrorResponse("Access denied"));
}
Resource resource = resourceService.findById(id);
return ResponseEntity.ok(resource);
}
}
Java provides the HttpURLConnection.HTTP_OK constants and HttpStatus enum in Spring for standard status codes.
61. How do you handle HTTP status codes in PHP?
In PHP, HTTP status codes can be handled as follows:
Setting status codes:
// Set header directly
header("HTTP/1.1 404 Not Found");
// Using http_response_code function (PHP 5.4+)
http_response_code(403); // Sets Forbidden status
Client requests with Guzzle:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
$client = new Client();
try {
$response = $client->request('GET', 'https://api.example.com/data');
$data = json_decode($response->getBody(), true);
echo "Success: " . $response->getStatusCode();
} catch (ClientException $e) {
echo "Error: " . $e->getResponse()->getStatusCode();
echo $e->getResponse()->getBody();
}
Framework example (Laravel):
// In a controller
public function getResource($id)
{
if (!$resource = Resource::find($id)) {
return response()->json(['error' => 'Resource not found'], 404);
}
if (!auth()->user()->can('view', $resource)) {
return response()->json(['error' => 'Forbidden'], 403);
}
return response()->json($resource, 200);
}
62. How do you handle HTTP status codes in Ruby?
In Ruby, especially in Rails applications, HTTP status codes are handled as follows:
Client-side with Net::HTTP:
require 'net/http'
require 'json'
uri = URI('https://api.example.com/data')
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
puts data
else
puts "Error: #{response.code} - #{response.message}"
end
Server-side with Rails:
class ResourcesController < ApplicationController
def show
@resource = Resource.find_by(id: params[:id])
if @resource.nil?
render json: { error: 'Resource not found' }, status: :not_found
return
end
unless current_user.can_access?(@resource)
render json: { error: 'Forbidden' }, status: :forbidden
return
end
render json: @resource
end
end
Rails provides symbolic names for status codes (like :not_found
for 404) to make code more readable.
HTTP Status Codes in Testing and Debugging
63. How should HTTP status codes be used in automated testing?
HTTP status codes are valuable in automated testing for:
- Verification of expected outcomes:
test('returns 404 for non-existent resources', async () => {
const response = await request(app).get('/api/resources/999');
expect(response.status).toBe(404);
});
- API contract validation:
test('returns 201 when resource created successfully', async () => {
const response = await request(app)
.post('/api/resources')
.send(validResource);
expect(response.status).toBe(201);
expect(response.headers.location).toBeDefined();
});
- Error handling verification:
test('returns 422 for invalid input', async () => {
const response = await request(app)
.post('/api/resources')
.send(invalidResource);
expect(response.status).toBe(422);
expect(response.body.errors).toBeDefined();
});
- Auth/authorization testing:
test('returns 401 for unauthenticated requests', async () => {
const response = await request(app).get('/api/protected');
expect(response.status).toBe(401);
});
Status codes provide clear, standardized assertions for API behavior verification.
64. How can you debug HTTP status code issues?
To debug HTTP status code issues:
- Use browser developer tools:
- Network tab shows all requests with status codes
- Filter by status code type (e.g., 4xx, 5xx)
- Examine request/response headers and bodies
- Server-side logging:
- Ensure detailed error logging for unexpected status codes
- Log request parameters that lead to errors
- Use correlation IDs across system components
- API testing tools:
- Tools like Postman or Insomnia for isolated API testing
- Modify request parameters to identify trigger conditions
- Compare working vs. failing requests
- Common checks:
- For 401/403: Check authentication tokens, permissions
- For 404: Verify URL paths, resource IDs
- For 400: Validate request payload format
- For 415: Verify Content-Type headers
- For 5xx: Check server logs for exceptions
- Proxy tools:
- Tools like Charles or Fiddler to intercept and modify requests
- Useful for HTTPS inspection and request manipulation
Systematic debugging with these approaches typically resolves most status code issues.
65. What tools help monitor HTTP status codes in production?
Several tools help monitor HTTP status codes in production:
- Web analytics:
- Google Analytics captures 404 errors and other client-side errors
- Custom events can track other status codes
- Application Performance Monitoring (APM):
- New Relic, Datadog, and Dynatrace track status codes across services
- Alert on unusual error rates or patterns
- Correlate status codes with performance metrics
- Log management systems:
- ELK Stack (Elasticsearch, Logstash, Kibana)
- Splunk
- Graylog
- Create dashboards for status code distribution
- Uptime monitoring:
- Pingdom, UptimeRobot, StatusCake
- Alert on unexpected status codes from key endpoints
- Synthetic monitoring:
- Run scheduled API tests and verify expected status codes
- Simulate user journeys and validate responses
- Status code dashboards:
- Custom dashboards showing status code distribution
- Alerts for abnormal error rates
- Historical trends for comparison
These tools provide visibility into application health through status code patterns and anomalies.
66. How should a QA team test for proper HTTP status code implementation?
QA teams should test HTTP status code implementation through:
- Functional testing:
- Verify expected status codes for normal operations
- Test error conditions trigger appropriate status codes
- Validate response bodies match status codes
- Edge case testing:
- Malformed requests (400)
- Invalid authentication credentials (401)
- Insufficient permissions (403)
- Non-existent resources (404)
- Method not allowed scenarios (405)
- Concurrency issues (409)
- Validation failures (422)
- Load testing:
- Verify status codes under load (429 for rate limiting)
- Check for unexpected 5xx errors under stress
- Security testing:
- Ensure sensitive endpoints return appropriate 401/403 codes
- Verify CSRF protection (403 for invalid tokens)
- Test for information disclosure in error responses
- API contract validation:
- Automated tests verifying all endpoints return documented status codes
- OpenAPI/Swagger specification compliance
- Integration testing:
- Verify status code handling between services
- Test client-side error handling for various status codes
Comprehensive testing across these dimensions ensures correct status code implementation throughout the system.
HTTP Status Codes Best Practices
67. What are best practices for implementing HTTP status codes in web applications?
Best practices for HTTP status code implementation include:
- Use standard codes correctly:
- Follow HTTP specifications for status code meanings
- Don’t repurpose standard codes with different semantics
- Use the most specific applicable code
- Be consistent:
- Use the same status codes for similar situations across your application
- Document expected status codes in API documentation
- Ensure machine-readable error details in response bodies
- Include helpful information:
- Provide descriptive error messages with status codes
- Include request IDs for error correlation
- Add links to documentation where appropriate
- Security considerations:
- Don’t leak sensitive information in error messages
- Use appropriate codes for auth/authorization failures
- Consider using 404 instead of 403 when appropriate
- Client experience:
- Implement meaningful HTTP status codes for automated clients
- Create user-friendly error pages for human users
- Use appropriate cache headers with status codes
- Monitoring and logging:
- Log all non-200 status codes with context
- Set up alerts for unexpected error rates
- Monitor status code trends over time
Following these practices creates a more robust, maintainable, and user-friendly application.
68. When should custom error responses accompany status codes?
Custom error responses should accompany status codes in these situations:
- Client errors (4xx):
- Include specific validation errors for 400/422 responses
- Explain why authentication failed for 401 (without revealing security details)
- Clarify permission issues for 403
- Suggest alternatives for 404 (similar resources, search)
- Provide rate limit information with 429 (limits, reset time)
- Server errors (5xx):
- Include a request ID for support reference
- Provide generic error information without exposing internals
- Add retry suggestions when appropriate
- Redirects (3xx):
- Optionally include information about the nature of the redirect
- Specify cache duration for permanent redirects
A structured error format is recommended:
{
"status": 400,
"title": "Bad Request",
"detail": "The name field is required",
"instance": "/api/users/create",
"requestId": "a7c53e4b-9260-4b5d-8144-6c6fb84c0a32",
"errors": [
{ "field": "name", "message": "Field is required" }
]
}
This approach provides both human-readable and machine-processable error information.
69. How should mobile applications handle HTTP status codes?
Mobile applications should handle HTTP status codes with specific considerations:
- Network reliability:
- Implement retry logic for transient errors (502, 503, 504)
- Use exponential backoff for repeated failures
- Cache data locally to handle offline scenarios
- User experience:
- Translate status codes to user-friendly messages
- Handle connectivity issues gracefully (airplane mode, weak signal)
- Provide offline functionality where possible
- Authentication:
- Properly handle 401 by refreshing tokens or prompting for login
- Securely store and manage credentials
- Implement
- Authentication:
- Securely store and manage credentials
- Implement graceful session timeouts for 401 responses
- Handle multi-device sign-out scenarios
- Error recovery:
- Allow users to retry failed operations
- Preserve form data when submissions fail
- Provide clear next steps for resolving issues
- Status code specific handling:
- 429: Implement client-side rate limiting and scheduling
- 404: Provide search or alternative navigation paths
- 304: Properly leverage for bandwidth efficiency
- 5xx: Differentiate between app issues and server problems
- Sync considerations:
- Track failed synchronization attempts for retry
- Resolve conflicts from 409 Conflict responses
- Implement idempotent requests for safe retries
A proper mobile implementation balances automatic recovery with user transparency about errors.
70. What are common mistakes when implementing HTTP status codes?
Common mistakes in HTTP status code implementation include:
- Using incorrect status codes:
- Returning 200 OK when an error occurred (with error in body)
- Using 404 for authorization failures instead of 403
- Returning 500 for client errors that should be 4xx
- Inconsistent implementation:
- Different status codes for the same error condition
- Mismatched status codes and response bodies
- Inconsistent error formats across services
- Inadequate error details:
- Generic error messages that don’t help resolution
- Missing context in error responses
- No request/correlation IDs for troubleshooting
- Security issues:
- Revealing sensitive system information in error messages
- Stack traces exposed in production
- Different response times for 401/403 enabling user enumeration
- Poor client experience:
- No human-friendly error messages
- Missing retry-after headers with 429/503
- Inappropriate caching headers with error responses
- Technical problems:
- Status code in JSON but not in HTTP header
- Content-lengths not matching actual response size
- Incorrect content-type headers with responses
Avoiding these mistakes leads to more robust and maintainable applications.
71. How should HTTP status codes be documented in API specifications?
HTTP status codes should be documented in API specifications as follows:
- OpenAPI/Swagger example:
paths:
/users/{id}:
get:
summary: Get user by ID
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'200':
description: Successful user retrieval
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'401':
description: Unauthorized - Authentication required
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'403':
description: Forbidden - Insufficient permissions
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: User not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: Server error
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
- Best practices:
- Document all possible status codes for each endpoint
- Include example responses for each status code
- Describe conditions that trigger each status code
- Define consistent error response structures
- Document any custom headers returned with specific status codes
- Additional documentation:
- Explain general error handling patterns
- Document retry strategies for specific codes
- Provide authentication/authorization error guidance
- Include correlation ID usage for troubleshooting
Complete status code documentation enables developers to properly handle all possible API responses.
HTTP Status Codes in Specialized Scenarios
72. How does a Content Delivery Network (CDN) use HTTP status codes?
CDNs use HTTP status codes in several specialized ways:
- Cache behavior:
- 200: Cacheable content served to users
- 304: Validates that cached content is still fresh
- 204: Often used for beacon/tracking endpoints
- Origin shield:
- 5xx from origin: May serve stale content with special headers
- 503: May be returned during origin capacity protection
- Custom status codes indicating CDN-specific conditions
- Security functions:
- 403: Often used for WAF blocks, geographic restrictions
- 429: Rate limiting and DDoS protection
- 495-499: Custom codes for SSL/TLS negotiation issues
- Performance optimization:
- 301/302: Edge redirects without origin requests
- 404: Edge-level negative caching
- Custom error pages for various status codes
- Custom error handling:
- Custom branded error pages for different status codes
- Different error handling based on content type
- A/B testing of error responses
- Operational indicators:
- Custom headers with cache status along with status codes
- Debugging headers for cache operations
- Server timing headers for performance analysis
CDNs often allow configuration of status code-specific behaviors like custom TTLs, fallback content, and bypass rules for different response codes.
73. How do HTTP status codes work with WebSockets?
WebSockets have a unique relationship with HTTP status codes:
- Connection establishment:
- The WebSocket handshake begins as an HTTP request
- Server returns 101 Switching Protocols to indicate successful upgrade
- Other HTTP status codes (400, 403, 500) may be returned if the upgrade fails
- After connection establishment:
- Once established, WebSockets don’t use HTTP status codes
- WebSockets have their own protocol for frames and control messages
- Connection closure uses WebSocket close codes, not HTTP status codes
- Common HTTP status codes during handshake:
- 400: Invalid WebSocket handshake request
- 401: Authentication required
- 403: WebSockets might be forbidden for this resource
- 426: Upgrade Required (if WebSocket protocol is required)
- 503: Service unavailable (server can’t accept WebSocket connections)
- WebSocket close codes:
- These are different from HTTP status codes (e.g., 1000 for normal closure)
- They exist in the WebSocket protocol, not HTTP
Once a WebSocket connection is established, communication no longer uses the HTTP protocol or its status codes.
74. How are HTTP status codes used in webhooks?
In webhook implementations, HTTP status codes serve several important purposes:
- For webhook senders:
- 2xx from the receiver indicates successful delivery
- 429 indicates receiver throttling (should retry with backoff)
- 4xx indicates problems with the webhook payload or authentication
- 5xx indicates receiver is experiencing issues (temporary failure)
- For webhook receivers:
- 200 OK: Successfully processed the webhook
- 202 Accepted: Received webhook but processing asynchronously
- 400 Bad Request: Invalid payload format
- 401/403: Authentication/authorization issues
- 405: If webhook endpoint only accepts POST
- 410 Gone: Receiver no longer accepts webhooks
- 422: Payload validation failed
- 429: Rate limiting webhook sender
- Best practices:
- Implement idempotency using webhook IDs
- Use signature verification for security
- Return appropriate status codes quickly, process asynchronously
- Include retry-after headers with 429/503 responses
- Maintain delivery logs with status codes for troubleshooting
Proper status code usage in webhooks ensures reliable event delivery and processing.
75. How do HTTP status codes relate to web scraping?
HTTP status codes provide essential information for web scraping operations:
- Access control indicators:
- 200: Content is accessible
- 401/403: Scraping may be unauthorized or blocked
- 429: Rate limiting in effect, need to slow down
- 503: Server protection against scraping may be active
- Content availability:
- 404: Resource doesn’t exist, may indicate pattern issues
- 410: Content permanently removed
- 301/302: Content has moved, need to follow redirects
- Scraping best practices:
- Respect robots.txt restrictions
- Implement exponential backoff for 429/503 responses
- Log and analyze status code patterns
- Rotate IPs/user agents if legitimate and permitted
- Maintain session cookies when required
- Legal and ethical considerations:
- 403 may indicate scraping is not permitted
- Terms of service violations may result in IP blocks
- Some sites use CAPTCHA after suspicious patterns
- Technical approaches:
- Handle redirects (3xx) properly
- Properly process different content types
- Deal gracefully with rate limiting (429)
- Implement request delays to minimize server load
Status codes help scrapers understand access permissions, content availability, and server load tolerances.
76. How are HTTP status codes used in IoT device communication?
IoT devices use HTTP status codes in several specific ways:
- Device to cloud communication:
- 200/201/204: Successful data transmission or command reception
- 401/403: Authentication or authorization issues (expired credentials)
- 413: Payload too large (bandwidth or size restrictions)
- 429: Rate limiting (device sending too frequently)
- 5xx: Cloud service issues
- Cloud to device commands:
- 200: Command successfully received by device
- 202: Command accepted for processing
- 408: Device timeout (common in power-constrained devices)
- 503: Device busy or unavailable
- Firmware updates:
- 200: Successful retrieval of update package
- 304: Device already has the latest firmware
- 206: Partial content for chunked firmware delivery
- 426: Upgrade required (mandatory firmware update)
- Resource constraints:
- Simplified HTTP implementations may support limited status codes
- Bandwidth and power optimization may use numeric codes without text
- Some implementations use only 200 for success and 400 for all errors
- IoT-specific considerations:
- Limited retry logic based on status codes
- Sleep/wake cycles affect response handling
- Batch processing of status codes after reconnection
The constrained nature of IoT devices often requires efficient handling of HTTP status codes.
Performance and Caching
77. How do HTTP status codes affect caching behavior?
HTTP status codes significantly influence caching behavior:
- Cacheable by default (unless otherwise specified):
- 200 (OK)
- 203 (Non-Authoritative Information)
- 204 (No Content)
- 206 (Partial Content)
- 300 (Multiple Choices)
- 301 (Moved Permanently)
- 404 (Not Found)
- 405 (Method Not Allowed)
- 410 (Gone)
- 414 (URI Too Long)
- 501 (Not Implemented)
- Never cached:
- 401 (Unauthorized)
- 403 (Forbidden)
- All responses with Authorization header (unless explicitly allowed)
- Special cases:
- 304 (Not Modified): Validates cache but doesn’t transfer body
- 302/307/303: Cacheable only if explicitly indicated with Cache-Control or Expires
- Cache control headers interaction:
- Cache-Control: no-store, no-cache override cacheability
- Expires and max-age indicate how long to cache
- ETag and Last-Modified enable validation
- Practical implications:
- 301 redirects are cached by browsers, 302/307 typically aren’t
- Error pages (404, 500) may be cached unless specified otherwise
- Authenticated responses typically aren’t cached by shared caches
Understanding these interactions is crucial for proper cache strategy implementation.
78. How does a 304 Not Modified response improve performance?
A 304 Not Modified response significantly improves performance through:
- Bandwidth savings:
- No response body is transferred, only headers
- Can reduce data transfer by 100% for page resources
- Especially valuable for large files like images, CSS, and JavaScript
- How it works:
- Client sends request with validation headers:
- If-Modified-Since (date-based validation)
- If-None-Match (ETag-based validation)
- Server checks if resource has changed
- If unchanged, returns 304 with minimal headers and no body
- Client uses its cached copy
- Client sends request with validation headers:
- Performance benefits:
- Reduced server load (less data processing and transfer)
- Faster page loads (browser uses cached resources immediately)
- Lower bandwidth consumption for both parties
- Reduced monthly data usage for mobile users
- Implementation:
<!-- Server response headers -->
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 123456
Cache-Control: max-age=86400
ETag: "abc123"
Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT
<!-- Later request from client -->
GET /image.jpg HTTP/1.1
If-None-Match: "abc123"
If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT
<!-- Server response if unchanged -->
HTTP/1.1 304 Not Modified
ETag: "abc123"
Cache-Control: max-age=86400
The 304 mechanism is one of the most important optimizations in HTTP for reducing unnecessary data transfer.
79. How should HTTP status codes be used with CDN edge caching?
When using CDNs with edge caching, HTTP status codes should be implemented with these considerations:
- Cache control by status code:
- Configure different cache TTLs for different status codes
- Common settings:
- 200: Long cache (hours/days) for static content
- 301: Very long cache (days/months)
- 404: Short-to-medium cache (minutes/hours)
- 5xx: No cache or very short cache
- Origin shield configurations:
- Configure stale-if-error behavior for 5xx responses
- Set stale-while-revalidate for improved performance
- Define custom error page caching policies
- Cache invalidation:
- Use cache-control headers with status codes
- Implement purge/invalidation APIs for content updates
- Configure status code-specific bypass rules
- Custom status code handling:
- Create custom error pages for different status codes
- Generate redirects at the edge (avoiding origin requests)
- Implement different behaviors per status code (retry, failover)
- Monitoring considerations:
- Track origin vs. edge-generated status codes
- Monitor cache hit ratios by status code
- Alert on unexpected error code patterns
- Optimization strategies:
# Example Cloudflare Worker modifying cache behavior by status addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const response = await fetch(request) // Modify cache behavior based on status if (response.status === 404) { return new Response(response.body, { status: response.status, headers: { ...response.headers, 'Cache-Control': 'public, max-age=300' } }) } return response }
Properly configured status code handling at CDN edges can significantly improve performance and reliability.
80. What’s the relationship between HTTP status codes and browser performance?
HTTP status codes influence browser performance in several ways:
- Connection management:
- 301/308: Browser caches permanent redirects, saving future requests
- 429/503 with Retry-After: Browsers may delay subsequent requests
- 5xx: May trigger connection retry logic
- Resource loading:
- 304: Enables efficient reuse of cached resources
- 206: Allows partial content loading for large resources
- 403/404: Browser stops attempting to load the resource
- Redirect chains (multiple 301/302): Introduce significant delays
- Render blocking:
- CSS/JS 404s can block rendering or script execution
- Different browsers handle resource errors differently
- Error status codes for critical resources may delay page rendering
- Performance metrics impact:
- Time to First Byte affected by redirect chains
- Largest Contentful Paint delayed by status code errors
- Cumulative Layout Shift potentially increased by late-loading errors
- Optimization strategies:
- Minimize redirect chains
- Ensure critical resources never 404
- Use preconnect/prefetch for resources after redirects
- Implement proper cache validation for 304 responses
- Measurement:
- Use Performance API to measure status code impact
- Navigation Timing API captures redirect time
- Resource Timing API shows individual resource performance
Understanding these relationships allows developers to optimize status code handling for better performance.
HTTP Status Codes and API Design
81. How should HTTP status codes be used in REST API versioning?
HTTP status codes play several roles in REST API versioning:
- Version negotiation:
- 406 Not Acceptable: When client requests a version the server doesn’t support
- 300 Multiple Choices: When multiple versions are available (rare)
- 301/302: Redirects to newer API versions when appropriate
- Deprecation handling:
- 200 OK with Deprecation header for working but deprecated versions
- 410 Gone for completely removed API versions
- 301 Moved Permanently to direct clients to newer versions
- Version-specific behaviors:
- Status codes might differ between versions as API design matures
- Newer versions might use more specific codes (e.g., 422 instead of 400)
- Response format for errors might change while status codes remain consistent
- Implementation examples:
# Version negotiation via headers GET /api/resources HTTP/1.1 Accept: application/json API-Version: 2 # Response for unsupported version HTTP/1.1 406 Not Acceptable Content-Type: application/json { "error": "API version 2 is not supported. Supported versions: 3, 4" } # Deprecated version response HTTP/1.1 200 OK Content-Type: application/json Deprecation: Sun, 31 Dec 2023 23:59:59 GMT Sunset: Sun, 30 Jun 2024 23:59:59 GMT Link: <https://api.example.com/v3/resources>; rel="successor-version" { "data": {...} }
- Documentation requirements:
- Clearly document version-specific status codes
- Explain transition paths between versions
- Document sunset dates for API versions
Proper status code usage helps guide clients through the API lifecycle and versioning transitions.
82. What status codes should be used for CRUD operations in RESTful APIs?
CRUD operations in RESTful APIs should use appropriate status codes:
- Create (POST):
- 201 Created: Resource successfully created
- 202 Accepted: Creation request accepted but processing isn’t complete
- 400 Bad Request: Invalid input data
- 409 Conflict: Resource already exists with conflicting data
- 422 Unprocessable Entity: Validation errors
- Read (GET):
- 200 OK: Resource found and returned
- 206 Partial Content: For range requests or pagination
- 304 Not Modified: For conditional requests when resource hasn’t changed
- 404 Not Found: Resource doesn’t exist
- Update (PUT/PATCH):
- 200 OK: Resource updated (with updated resource returned)
- 204 No Content: Resource updated successfully (no response body)
- 400 Bad Request: Invalid input data
- 404 Not Found: Resource to update doesn’t exist
- 409 Conflict: Update conflicts with current state
- 422 Unprocessable Entity: Validation errors
- Delete (DELETE):
- 200 OK: Resource deleted (with deleted resource returned)
- 204 No Content: Resource deleted successfully (no response body)
- 404 Not Found: Resource to delete doesn’t exist
- 409 Conflict: Resource cannot be deleted (e.g., has dependencies)
- Additional considerations:
- 401 Unauthorized: Authentication required
- 403 Forbidden: Authenticated but insufficient permissions
- 405 Method Not Allowed: HTTP method not supported for this resource
- 413 Payload Too Large: Request body exceeds limits
- 429 Too Many Requests: Rate limiting applied
Consistent use of these status codes makes APIs more intuitive and easier to integrate with.
83. How do GraphQL APIs differ in HTTP status code usage?
GraphQL APIs have a different approach to HTTP status codes:
- Standard GraphQL response pattern:
- Almost always return 200 OK status code, regardless of errors
- Errors are communicated in the response JSON structure
- Multiple errors can be returned in a single response
- Success/failure is indicated by presence of “data” and/or “errors” in response
- GraphQL error handling:
// GraphQL response with error
HTTP/1.1 200 OK
Content-Type: application/json
{
"data": {
"user": null
},
"errors": [
{
"message": "User with ID 123 not found",
"locations": [{"line": 2, "column": 3}],
"path": ["user"],
"extensions": {
"code": "NOT_FOUND"
}
}
]
}
- Exceptions to the 200 pattern:
- 400 Bad Request: Malformed GraphQL syntax or invalid JSON
- 401/403: Authentication/authorization before GraphQL processing
- 413: Query too complex or response too large
- 429: Rate limiting
- 500: Server errors preventing GraphQL execution
- Practical implications:
- Clients must check response JSON, not rely on HTTP status
- Error handling is more uniform but requires more client parsing
- Network-level errors still use appropriate HTTP status codes
- Custom error codes typically placed in “extensions” field
- Benefits of this approach:
- Partial success can be represented (some data, some errors)
- Multiple errors can be returned simultaneously
- More detailed error information is possible
- Consistent client-side handling pattern
This approach represents a fundamental difference between REST and GraphQL API design philosophies.
84. What status codes are appropriate for batch operations?
Batch operations (processing multiple resources at once) should use these status codes:
- Atomic batch operations (all succeed or all fail):
- 200 OK: All operations successful (with results)
- 201 Created: All resources successfully created
- 400 Bad Request: Invalid batch format
- 422 Unprocessable Entity: Validation errors in batch
- Non-atomic batch operations (partial success possible):
- 200 OK: Always used for response with detailed per-operation status
- Response body contains individual status for each operation
- Example response for non-atomic batch:
HTTP/1.1 200 OK
Content-Type: application/json
{
"operations": [
{
"id": "op1",
"status": 201,
"resource": {"id": "123", "name": "New Item"}
},
{
"id": "op2",
"status": 404,
"error": "Resource not found"
},
{
"id": "op3",
"status": 200,
"resource": {"id": "456", "name": "Updated Item"}
}
],
"summary": {
"total": 3,
"successful": 2,
"failed": 1
}
}
- Alternative approach: Batch creation with URI templates:
- 207 Multi-Status: Contains response for each operation
- Uses WebDAV-inspired response format
- Special considerations:
- 202 Accepted: For asynchronous batch processing
- 413 Payload Too Large: Batch exceeds size limits
- 429 Too Many Requests: Too many operations in batch
- Best practices:
- Provide operation IDs for correlation
- Include individual status codes for each operation
- Return both successful and failed results
- Support idempotency for safe retries
The key principle is providing detailed per-operation status while maintaining a consistent response structure.
85. How should HTTP status codes be used in API pagination?
HTTP status codes in API pagination should be implemented as follows:
- Successful pagination responses:
- 200 OK: Standard response for paginated results
- 206 Partial Content: Alternative for range-based pagination
- 204 No Content: When the requested page is valid but empty (alternative to empty array with 200)
- Pagination error scenarios:
- 400 Bad Request: Invalid pagination parameters
- 404 Not Found: Page number exceeds available pages
- 416 Range Not Satisfiable: Requested range not valid
- Headers for pagination:
HTTP/1.1 200 OK Content-Type: application/json Link: <https://api.example.com/resources?page=3>; rel="next", <https://api.example.com/resources?page=1>; rel="prev", <https://api.example.com/resources?page=10>; rel="last" X-Total-Count: 97
- Response body pagination information:
{ "data": [ { "id": 31, "name": "Item 31" }, { "id": 32, "name": "Item 32" } ], "pagination": { "page": 2, "per_page": 10, "total_items": 97, "total_pages": 10, "links": { "next": "https://api.example.com/resources?page=3", "prev": "https://api.example.com/resources?page=1" } } }
- Cursor-based pagination:
- 200 OK: With next_cursor in response
- 400 Bad Request: Invalid cursor value
The key is consistency in status code usage while providing enough pagination metadata for clients to navigate the collection.
HTTP Status Codes and Security
86. How do HTTP status codes impact Cross-Origin Resource Sharing (CORS)?
HTTP status codes have important interactions with CORS:
- CORS preflight requests (OPTIONS):
- 200 OK: Preflight successful, actual request can proceed
- 403 Forbidden: Cross-origin request not allowed
- 405 Method Not Allowed: Requested method not supported for cross-origin
- 501 Not Implemented: OPTIONS method not supported
- Response headers needed with status codes:
# Successful preflight HTTP/1.1 200 OK Access-Control-Allow-Origin: https://example.com Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Max-Age: 86400
- Actual CORS request responses:
- All status codes must include Access-Control-Allow-Origin
- Error status codes (4xx/5xx) still need CORS headers
- Browsers block access to response if CORS headers missing
- Security implications:
- Different status codes without proper CORS headers cause request failure
- 401/403 without CORS headers leak existence of protected resources
- Error responses need CORS headers to be visible to JavaScript
- Common issues:
- Server returns error status but forgets CORS headers
- Preflight succeeds (200) but actual request fails CORS check
- Error handling bypasses CORS header addition
Proper implementation ensures security while allowing legitimate cross-origin access.
87. How can status codes reveal information during security testing?
Status codes provide valuable information during security testing:
- Authentication probing:
- 401 vs. 403 can reveal valid usernames
- Timing differences in responses may enable enumeration
- Inconsistent responses may reveal implementation details
- Resource enumeration:
- 404 vs. 403 reveals resource existence
- 503 may indicate protection mechanisms triggered
- Custom error codes may reveal specific security tools
- Injection testing:
- Different status codes for different injection attempts
- 500 errors may indicate successful injection points
- Status code changes when adding special characters
- Security misconfiguration:
- Verbose error messages with stack traces (500)
- Directory listing enabled (200 with directory contents)
- Different environments showing different error behaviors
- API security:
- Inconsistent authorization checks (some endpoints 200, others 403)
- Rate limiting implementation (429 behavior)
- Sensitive operations lacking proper verification
- Mitigation strategies:
- Consistent error responses regardless of error type
- Avoiding timing differences in responses
- Using misleading status codes where appropriate (404 instead of 403)
- Generic error messages across all error types
Security testers analyze status code patterns to identify potential vulnerabilities, while defenders aim to minimize information disclosure through status codes.
88. How should status codes be used in authentication flows?
Status codes in authentication flows should be implemented with security in mind:
- Login/Authentication requests:
- 200 OK: Successful authentication
- 400 Bad Request: Malformed credentials
- 401 Unauthorized: Invalid credentials
- 403 Forbidden: Account disabled or locked
- 429 Too Many Requests: Too many failed attempts (rate limiting)
- Security considerations:
- Use consistent response times to prevent timing attacks
- Don’t reveal whether username or password was incorrect
- Consider using 404 instead of 403 for sensitive endpoints
- Include appropriate WWW-Authenticate headers with 401
- OAuth/OpenID flows:
- 302 Found: Redirects during authorization flow
- 400 Bad Request: Invalid OAuth requests
- 401 Unauthorized: Invalid tokens
- 403 Forbidden: Token lacks required scopes
- Password reset flows:
- 202 Accepted: Reset request received (don’t confirm email exists)
- 400 Bad Request: Invalid reset token
- 429 Too Many Requests: Too many reset attempts
- Multi-factor authentication:
- 401 + WWW-Authenticate: Additional authentication required
- 403: MFA specifically forbidden for user/resource
- Examples:
# Login failure HTTP/1.1 401 Unauthorized Content-Type: application/json WWW-Authenticate: Bearer realm="example" { "error": "invalid_credentials", "message": "Username or password is incorrect" } # Rate limiting HTTP/1.1 429 Too Many Requests Content-Type: application/json Retry-After: 300 { "error": "too_many_attempts", "message": "Too many login attempts, please try again later" }
The key is balancing usability (helpful error messages) with security (not revealing sensitive information).
89. What status codes are relevant to Cross-Site Request Forgery (CSRF) protection?
CSRF protection involves several specific status codes:
- CSRF token validation:
- 403 Forbidden: Missing or invalid CSRF token
- 400 Bad Request: Malformed CSRF token
- 419 Page Expired: Custom code used by some frameworks for CSRF failures
- Example CSRF error response:
HTTP/1.1 403 Forbidden Content-Type: application/json { "error": "csrf_validation_failed", "message": "CSRF token validation failed" }
- Preflight requests (CORS):
- 200 OK: Allows browsers to check if cross-origin requests are permitted
- OPTIONS requests with CORS headers prevent many CSRF attacks
- SameSite cookie attribute effects:
- With SameSite=Strict or Lax, cross-site requests may receive 401/403
- These failures may appear as CSRF protection even without tokens
- Secure implementation notes:
- Return same status code for all CSRF failures (timing attack prevention)
- Don’t provide different messages for missing vs. invalid tokens
- Consider CSRF token rotation after authentication changes
CSRF protection status codes should be consistent and reveal minimal information about why validation failed.
90. How do status codes factor into security headers and Content Security Policy?
Status codes interact with security headers and Content Security Policy in several ways:
- Content Security Policy violations:
- Blocked content doesn’t affect HTTP status code (still 200)
- CSP violations are reported via separate requests to report-uri
- Violation reports typically receive 204 No Content responses
- CSP reporting API:
# CSP header in response HTTP/1.1 200 OK Content-Security-Policy: default-src 'self'; report-uri /csp-report # Browser sends violation report POST /csp-report HTTP/1.1 Content-Type: application/csp-report {"csp-report":{...}} # Server acknowledges report HTTP/1.1 204 No Content
- Security headers with different status codes:
- All responses (including errors) should include security headers
- Content-Security-Policy
- Strict-Transport-Security
- X-Content-Type-Options
- X-Frame-Options
- Referrer-Policy
- Middleware implementation:
// Express middleware example app.use((req, res, next) => { // Add security headers to all responses regardless of status code res.setHeader('Content-Security-Policy', "default-src 'self'"); res.setHeader('X-Frame-Options', 'DENY'); // More headers... next(); });
- Error pages and redirects:
- Security headers must be included with error status codes (4xx/5xx)
- Redirect responses (3xx) should include security headers
- Different status codes might need different CSP policies
Consistent security header inclusion across all status codes is essential for maintaining security protections.
Status Codes for Specific Technologies
91. How are HTTP status codes used in Progressive Web Apps (PWAs)?
HTTP status codes play specific roles in Progressive Web Apps:
- Service Worker lifecycle:
- 200: Successful service worker registration and update
- 404: Service worker not found (registration fails)
- 500: Service worker execution error
- Offline capabilities:
- Service workers intercept network requests and can return custom responses with appropriate status codes
- 200 OK: Cached resources served offline
- 504 Gateway Timeout: Often returned if offline and no cache available
- Example offline response from service worker:
// Service worker handling offline requests self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => { if (response) { // Return cached response with original status return response; } // No cache, offline fallback if (!navigator.onLine) { return new Response( JSON.stringify({ error: 'You are offline' }), { status: 503, headers: { 'Content-Type': 'application/json' } } ); } return fetch(event.request); }) ); });
- Cache management:
- 304 Not Modified: Important for efficient cache updates
- Headers like ETag and If-None-Match optimize bandwidth usage
- App manifest:
- 200: Successful manifest loading
- 404: Missing manifest can prevent installability
- Push notifications:
- 201: Successful subscription creation
- 410: Indicates subscription has expired or been revoked
PWAs must handle status codes gracefully to provide smooth experiences both online and offline.
92. How do HTTP status codes work with JSON API specification?
The JSON API specification (jsonapi.org) defines specific status code usage:
- Success responses:
- 200 OK: Standard success for most operations
- 201 Created: New resources
- 204 No Content: Successful operations returning no content
- 200 with meta-only responses for operations not affecting resources
- Error format:
HTTP/1.1 422 Unprocessable Entity Content-Type: application/vnd.api+json { "errors": [ { "status": "422", "source": { "pointer": "/data/attributes/title" }, "title": "Invalid Attribute", "detail": "Title cannot be blank" } ] }
- Error objects contain:
- “status”: String version of HTTP status code
- “title”: Short, human-readable summary
- “detail”: Human-readable explanation
- “source”: Object pointing to error origin
- Additional metadata as needed
- Common status codes in JSON API:
- 400: Bad Request (malformed JSON or parameters)
- 403: Forbidden (permissions)
- 404: Resource not found
- 409: Conflict (version conflicts)
- 422: Unprocessable Entity (validation errors)
- 500: Server errors
- Compound documents:
- Status code reflects the primary operation
- Additional issues may be indicated in response body
JSON API standardizes both status code usage and error response structure for consistent client experiences.
93. How do single-page applications (SPAs) handle HTTP status codes?
Single-page applications handle HTTP status codes differently than traditional websites:
- Client-side routing challenges:
- Browser only makes HTTP request for initial page load
- Client-side route changes don’t generate HTTP status codes
- Search engines need proper status codes for indexing
- AJAX/fetch API calls:
- SPAs handle status codes programmatically in JavaScript
- API responses determine application state
- Error handling based on status codes (e.g., redirect to login on 401)
- SEO considerations:
- Server-side rendering (SSR) or pre-rendering provides proper status codes
- Static generation of error pages (404.html)
- Dynamic rendering for search engines
- Implementation approaches:
// React Router example with status codes import { Route, Switch, useHistory } from 'react-router-dom'; function App() { // Set up status code handling const history = useHistory(); // Listen for 401 responses useEffect(() => { const interceptor = axios.interceptors.response.use( response => response, error => { if (error.response && error.response.status === 401) { history.push('/login'); } return Promise.reject(error); } ); return () => axios.interceptors.response.eject(interceptor); }, [history]); return ( <Switch> <Route path="/products/:id" component={ProductDetail} /> <Route path="/not-found" component={NotFound} /> {/* Redirect to not-found for unmatched routes */} <Redirect to="/not-found" /> </Switch> ); }
- Server configuration options:
- Fallback to index.html for all routes (client handles 404s)
- Configure server to return appropriate status codes for known routes
- Use service workers to handle offline status codes
SPAs require specific strategies to properly communicate status codes to both users and search engines.
94. How are HTTP status codes used in streaming media applications?
Streaming media applications use HTTP status codes in specialized ways:
- Adaptive bitrate streaming (HLS, DASH):
- 200 OK: Successful manifest and segment delivery
- 206 Partial Content: Range requests for media segments
- 404: Missing segments (can cause playback interruption)
- 503: Server unable to deliver segments (may trigger fallback)
- Range requests for seeking:
# Client request GET /video.mp4 HTTP/1.1 Range: bytes=10485760-20971519 # Server response HTTP/1.1 206 Partial Content Content-Range: bytes 10485760-20971519/104857600 Content-Length: 10485760
- Live streaming considerations:
- 408: Timeout for long-polling segment requests
- 410: Expired segments no longer available
- 204: No new segments available yet (with retry)
- DRM and content protection:
- 403: Unauthorized access to protected content
- 451: Unavailable for legal reasons (geo-restrictions)
- Player behavior:
- Different status codes trigger different recovery strategies
- 5xx: May retry with exponential backoff
- 404: May skip segment or reload manifest
- 403: May prompt for authentication
- Optimization techniques:
- 304 Not Modified for manifest updates
- Cache-Control headers for different content types
- Predictive segment loading based on past status codes
Proper status code handling is critical for smooth media playback experiences.
95. How do HTTP status codes function in WebDAV environments?
WebDAV (Web Distributed Authoring and Versioning) extends HTTP with additional status codes for file management operations:
- WebDAV-specific status codes:
- 207 Multi-Status: Response to a batch operation
- 422 Unprocessable Entity: Semantic errors in request
- 423 Locked: Resource is locked
- 424 Failed Dependency: Operation failed due to previous failure
- 507 Insufficient Storage: Server storage full
- 207 Multi-Status example:
HTTP/1.1 207 Multi-Status Content-Type: application/xml; charset="utf-8" <d:multistatus xmlns:d="DAV:"> <d:response> <d:href>/collection/resource1.html</d:href> <d:status>HTTP/1.1 200 OK</d:status> </d:response> <d:response> <d:href>/collection/resource2.html</d:href> <d:status>HTTP/1.1 423 Locked</d:status> <d:error><d:lock-token-submitted/></d:error> </d:response> </d:multistatus>
- Standard HTTP status codes in WebDAV context:
- 200 OK: Successful operations (GET, OPTIONS)
- 201 Created: Resource creation (PUT, MKCOL)
- 204 No Content: Successful operation with no response body
- 403 Forbidden: Permission denied
- 409 Conflict: Collection cannot be created (MKCOL)
- WebDAV methods and status codes:
- PROPFIND: 207 Multi-Status for property retrieval
- LOCK: 200 OK with lock token or 423 Locked
- MKCOL: 201 Created or 409 Conflict
- COPY/MOVE: 201 Created, 204 No Content, or 207 Multi-Status
- Lock-related status codes:
- 423 Locked: Resource is already locked
- 409 Conflict: Can’t create a conflicting lock
- 412 Precondition Failed: If-Lock header didn’t match
WebDAV’s extended status codes enable richer file operations and consistency checking in distributed environments.
Historical and Future Status Codes
96. How have HTTP status codes evolved across different HTTP versions?
HTTP status codes have evolved across different protocol versions:
- HTTP/0.9 (1991):
- No explicit status codes
- Simple request-response model without headers
- HTTP/1.0 (1996 – RFC 1945):
- Introduced the three-digit status codes
- Defined basic categories (1xx, 2xx, 3xx, 4xx, 5xx)
- Established core codes still used today:
- 200, 201, 204
- 301, 302
- 400, 401, 403, 404
- 500, 501, 502, 503
- HTTP/1.1 (1997/1999 – RFC 2068/2616):
- Added numerous status codes:
- 100 Continue, 101 Switching Protocols
- 203, 205, 206
- 303, 304, 305, 307
- 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417
- 504, 505
- Refined definitions of existing codes
- Better distinction between similar codes
- Added numerous status codes:
- HTTP/2 (2015 – RFC 7540):
- Maintained the same status codes as HTTP/1.1
- Changed how status codes are transmitted (binary encoding)
- No new status codes specific to HTTP/2
- HTTP/3 (QUIC-based HTTP):
- Continues to use the same status codes
- Further changes in transmission method
- Status code semantics remain consistent
- WebDAV and extensions:
- Added specialized codes (207, 422, 423, 424, 507)
- Extended the HTTP status code ecosystem
Throughout evolution, backward compatibility has been maintained, with core status codes retaining their original meaning while the set has expanded to address new use cases.
97. What are some lesser-known HTTP status codes with specific use cases?
Some lesser-known but useful HTTP status codes include:
- 418 I’m a teapot (RFC 2324):
- Originally an April Fools’ joke
- Indicates the server refuses to brew coffee with a teapot
- Sometimes used as an Easter egg or deliberate error code
- Some frameworks use it as a placeholder for custom errors
- 425 Too Early (RFC 8470):
- Server is unwilling to process a request that might be replayed
- Protects against replay attacks with TLS early data
- Important for zero round trip time resumption (0-RTT)
- 451 Unavailable For Legal Reasons (RFC 7725):
- Named after Ray Bradbury’s “Fahrenheit 451”
- Used when content is blocked due to legal restrictions
- Censorship, DMCA takedowns, geo-restrictions
- Should include explanation of the restriction
- 444 No Response (Nginx):
- Non-standard Nginx code
- Server returns no information and closes the connection
- Used to deny malicious software and bad bots
- 508 Loop Detected (WebDAV):
- Infinite loop detected during processing
- Server terminated operation to prevent resource consumption
- 226 IM Used (RFC 3229):
- Server has fulfilled a GET request using delta encoding
- Response is a representation of the result of instance manipulations
- 511 Network Authentication Required (RFC 6585):
- Used by captive portals
- Client needs to authenticate to gain network access
- Common in hotel/airport Wi-Fi
These specialized status codes address specific technical scenarios that aren’t encountered in everyday web usage.
98. What custom HTTP status codes do major platforms use?
Major platforms sometimes implement custom or non-standard status codes:
- Twitter API:
- 420 Enhance Your Calm: Rate limit exceeded (deprecated)
- Now uses standard 429 Too Many Requests
- Nginx:
- 444 No Response: Connection closed without sending headers
- 494 Request Header Too Large
- 495 SSL Certificate Error
- 496 SSL Certificate Required
- 497 HTTP Request Sent to HTTPS Port
- 499 Client Closed Request
- Cloudflare:
- 520 Web Server Returning Unknown Error
- 521 Web Server Is Down
- 522 Connection Timed Out
- 523 Origin Is Unreachable
- 524 A Timeout Occurred
- 525 SSL Handshake Failed
- 526 Invalid SSL Certificate
- 527 Railgun Error
- 530 Origin DNS Error
- AWS:
- Standard codes with custom meanings in specific services
- S3: 301 moved permanently for bucket name changes
- Microsoft:
- 450 Blocked by Windows Parental Controls (Internet Explorer)
- Exchange uses enhanced 440-449 codes for authentication
- Other examples:
- 509 Bandwidth Limit Exceeded (hosting providers)
- 555 Used for authenticating to Electrum Bitcoin servers
While non-standard codes can be useful within specific ecosystems, they may cause compatibility issues and should be used cautiously.
99. What status codes might we see in the future of HTTP?
Potential future HTTP status codes might include:
- AI-related status codes:
- Potential codes for AI-generated content identification
- Status codes indicating machine learning processing delays
- Codes for consent to AI training usage
- Extended authentication statuses:
- More granular authentication failure reasons
- Codes for multi-factor requirements
- Biometric authentication specific codes
- Enhanced privacy indicators:
- Codes indicating data handling policies
- Consent and tracking transparency statuses
- Region-specific privacy compliance indicators
- Distributed systems coordination:
- More detailed consistency status indicators
- Partition-aware status codes
- Eventual consistency indicators
- IoT and edge computing:
- Battery status indicators
- Device capability negotiation
- Mesh network path indicators
- Proposed status families:
- 6xx codes for distributed/blockchain consensus issues
- 7xx for client hints and capability negotiation
While HTTP status codes have remained remarkably stable over decades, evolving technologies may drive the standardization of new codes to address emerging patterns.
100. How should developers prepare for changing status code usage in the future?
Developers should prepare for evolving status code usage by:
- Follow robust status code handling practices:
- Group status codes by class (1xx, 2xx, etc.) for general handling
- Build flexibility for new codes within each class
- Don’t hardcode checks for specific status codes when category checks work
- Implement forward-compatible error handling:
// Bad - brittle implementation if (response.status === 400 || response.status === 422) { // Handle validation errors } // Better - category-based with specific enhancement if (response.status >= 400 && response.status < 500) { // Handle all client errors generically if (response.status === 422) { // Special handling for Unprocessable Entity if needed } }
- Stay informed about HTTP specifications:
- Monitor IETF standards and drafts
- Subscribe to web standards groups
- Follow browser implementation status
- Document your API’s status code usage:
- Clearly specify which status codes your API returns
- Document the semantic meaning for each code
- Version your API properly when changing status code usage
- Implement graceful degradation:
- Handle unexpected status codes reasonably
- Provide fallback behaviors
- Log unexpected status codes for analysis
- Design for extensibility:
- Use response bodies to augment status codes
- Implement detailed error types beyond status codes
- Consider hypermedia responses that guide next actions
By building flexible, standards-compliant systems that handle status codes by category while accommodating specific codes where needed, developers can adapt to evolving HTTP standards.