HTTP Responses
HTTP responses provide the client with the outcome of their HTTP request. These responses include status codes, headers, and body content.
Status Codes
Status codes indicate the result of the HTTP request. Here are some common status codes:
Status Code | Description |
---|---|
200 OK | The request was successful. |
404 Not Found | The requested resource could not be found. |
500 Internal Server Error | The server encountered an error processing the request. |
403 Forbidden | The client does not have access rights to the content. |
401 Unauthorized | The client must authenticate itself to get the requested response. |
Headers
Headers provide additional context about the response. Common headers include:
- Content-Type: Indicates the media type of the resource.
- Set-Cookie: Used to send cookies from the server to the client.
- Cache-Control: Directives for caching mechanisms in both requests and responses.
Body Content
The body of the response contains the data being returned to the client. This can be in various formats such as JSON, XML, or HTML.
JSON Response
{
"message": "Success",
"data": {
"id": 1,
"name": "Item Name"
}
}
XML Response
Success
1
Item Name
Handling Errors
Properly handling HTTP errors ensures that clients understand why a request failed. Here are examples of error responses:
404 Not Found
{
"error": "Not Found",
"message": "The requested resource could not be found."
}
500 Internal Server Error
{
"error": "Internal Server Error",
"message": "An error occurred while processing your request."
}
Best Practices
Follow these best practices for crafting HTTP responses:
- Use appropriate status codes to indicate the result of the request.
- Include informative error messages and details in the response body.
- Set relevant headers to provide additional context.
For more details on HTTP responses, refer to the HTTP Response Specification .