HTTP Verbs and Status Codes
Use of HTTP Methods
The correct definition and application of HTTP methods are essential for the design and functionality of our APIs. Each HTTP method—such as GET, POST, PUT, DELETE, and PATCH—has a specific purpose and should be used according to established standards. This ensures that our APIs are well-structured, user-friendly, and able to interact easily with other systems. Additionally, this approach reduces the development effort when integrating multiple interfaces and different resources.
GET
The GET method must (MUST) be used to retrieve data from a server. This method should not have side effects on the data on the server and should not modify the resource.
Examples:
GET /products – Retrieve a list of all products.
GET /products/{id} – Retrieve details of a specific product.
In general, GET requests should (SHOULD) be idempotent, meaning repeated requests should return the same result without changing the state of the resource.
POST
The POST method must (MUST) be used to create new resources on the server or to send data that should be processed server-side.
Examples:
POST /products – Create a product.
POST /orders – Create an order.
In general, POST requests should (SHOULD) not be idempotent, meaning repeated requests may produce different results.
PUT
The PUT method must (MUST) be used to completely update or replace a resource. This method replaces the entire resource on the server.
Examples:
PUT /products/{id} – Fully replace the information of a product.
PUT /orders/{id} – Replace the information of an order.
In general, PUT requests should (SHOULD) be idempotent, meaning repeated requests should produce the same result.
PATCH
The PATCH method must (MUST) be used to partially update a resource. It allows changing specific attributes of a resource without replacing the entire resource.
Examples:
PATCH /products/{id} – Update specific attributes of a product such as price or description.
PATCH /orders/{id} – Modify specific details of an order.
In general, PATCH requests should (SHOULD) be idempotent if implemented in a way that multiple identical requests produce the same result.
DELETE
The DELETE method must (MUST) be used to remove a resource from the server. This method should completely remove the specified resource.
Examples:
DELETE /products/{id} – Delete a specific product.
DELETE /orders/{id} – Remove an order.
In general, DELETE requests should (SHOULD) be idempotent, meaning repeated requests to delete the same resource should not cause further changes.
Note: Additionally, the OPTIONS method is permissible and is used in preflight requests to check which HTTP methods and headers are supported by the API, particularly for cross-origin requests. Details on the use of the OPTIONS method and CORS configuration are discussed in the "CORS" section.
Standardized HTTP Status Codes
Status codes help describe the state of a request accurately, making error handling and debugging easier. Below are the most important status codes, along with their meaning and recommended usage:
Successful Responses (2xx)
-
200 OK: Must (MUST) be used when a GET, PUT, or PATCH request is successful and the response contains the requested data. This status code indicates that the request was processed successfully and data is returned.
Example:
GET /orders returns a list of orders. -
201 Created: Must (MUST) be used when a POST request successfully creates a new resource. The status code indicates that the resource was created successfully and that its details are included in the response. A Location header SHOULD be included to indicate the URI of the newly created resource. A response body containing resource data is allowed; however, the full URI MUST ONLY be returned in the Location header, not in the body.
Example:
POST /orders creates a new order and returns the details of the new order. -
204 No Content: Must (MUST) be used when a DELETE request is successful, and no data needs to be returned. This status code is used when the request was processed successfully, but the response does not require further content.
Example:
DELETE /orders/123 removes the order with ID 123.
Redirection Responses (3xx)
-
308 Permanent Redirect: Should (SHOULD) be used when a resource is permanently available at a new URL. This indicates that the requested resource has been permanently moved, and future requests should be directed to the new URL using the same request method.
Example:
An old API URL is redirected to a new URL. -
302 Found: Should (SHOULD) be used when a resource is temporarily available at a different URL. This status code indicates that the redirection is temporary, and the original URL remains valid.
Example:
Temporary redirection due to maintenance or special requests.
Client Errors (4xx)
-
400 Bad Request: Must (MUST) be used when the request cannot be processed due to invalid syntax. This means that the request does not comply with API specifications or contains invalid data. A detailed and helpful error message must (MUST) be returned to inform API users precisely what went wrong.
Example:
Invalid parameters in a POST request. -
401 Unauthorized: Must (MUST) be used when authentication is required but is either missing or invalid. This status code indicates that the client must authenticate to gain access.
Example:
Missing or invalid authentication token. -
403 Forbidden: Must (MUST) be used when the client is authenticated but does not have the necessary permissions to access the requested resource.
Example:
The client tries to access a resource they are not authorized to view. -
404 Not Found: Must (MUST) be used when the requested resource cannot be found. This indicates that the specified URL does not exist.
Example:
GET /products/999 for a non-existent product ID.
Server Errors (5xx)
-
500 Internal Server Error: Must (MUST) be used when a general server error occurs, preventing the request from being processed. This status code signals an unexpected issue on the server. Recommended return values for 5xx status codes are further specified in the section "Error Handling and Communication".
Example:
A database error that prevents the request from being processed. -
502 Bad Gateway: Should (SHOULD) be used when the server receives an invalid response from a downstream server or service. This occurs when the server acts as a gateway and an error occurs from an external service.
Example:
The API server is connected through a gateway that does not respond correctly. -
503 Service Unavailable: Should (SHOULD) be used when the server is temporarily unavailable, such as during maintenance or due to overload. This status code indicates that the server is temporarily unreachable.
Example:
The API is temporarily unavailable due to scheduled maintenance.
For clear and understandable communication between our APIs and when exchanging data with various internal and external applications, a consistent use of HTTP status codes is necessary. Ensuring uniform status code rules across all APIs within the company promotes seamless collaboration. These best practices ensure that errors are clearly reported, and problems are effectively resolved, both within the APIs and in conjunction with the API gateway and development portal.
Error Handling and Communication
Error handling and communication are important to provide developers with clear and consistent feedback on issues that may occur during API interactions. The following guidelines for error handling and communication apply when developing and deploying APIs in our company.
Error Status Codes
Appropriate HTTP status codes MUST be used (see Standardized HTTP Status Codes) to communicate the status of a request. Examples of error codes include:
- 4xx - Client errors: e.g., 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
- 5xx - Server errors: e.g., 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable
Error Messages in the Body of the Response
If error messages are provided in the body of the response (SHOULD), they must (MUST) be in JSON format and included in an errors array, regardless of whether a single or multiple errors are present. This ensures consistency in API responses and facilitates processing by client applications. The structure of an error should contain the following fields:
- code (machine-readable): A unique and concise code that describes the type of error (e.g., "INVALID_PARAMETER", "NOT_FOUND"). Words should be separated by underscores (_) and written in uppercase.
- message (human-readable): A clear and detailed description explaining why the request failed (e.g., "The 'leasingPeriod' parameter must be a positive integer.").
- details (optional, human-readable): Additional information providing specific details about the error, such as invalid parameters or affected resources (e.g., "Invalid value for parameter 'leasingPeriod': -3").
- translations (optional, human-readable): A collection of translations of the error message content into other languages to provide multilingual support, with each translation object representing a specific language.
Example:
{
"errors": [
{
"code": "INVALID_PARAMETER",
"message": "The 'leasingPeriod' parameter must be a positive integer.",
"details": "Invalid value for parameter 'leasingPeriod': -3",
"translations": {
"de": "Der Parameter 'leasingPeriod' muss eine positive ganze Zahl sein."
}
}
]
}
Example of multiple errors:
{
"errors": [
{
"code": "INVALID_PARAMETER",
"message": "The 'leasingPeriod' parameter must be a positive integer.",
"details": "Invalid value for parameter 'leasingPeriod': -3",
"translations": {
"de": "Ungültiger Wert für Parameter 'leasingPeriod': -3"
}
},
{
"code": "MISSING_PARAMETER",
"message": "The 'startDate' parameter is required but was not provided.",
"details": null,
"translations": {
"de": "Der Parameter 'startDate' ist erforderlich, wurde jedoch nicht bereitgestellt."
}
}
]
}
The code field must (MUST) contain a specific and concise error code to clearly identify the issue. Error codes should be standardized and documented, making them easy for developers to reference. Consistent naming for error codes should (SHOULD) be used to avoid confusion, and error codes could be prefixed with something like ERR_ (e.g., "ERR_INVALID_PARAM").
The message must be clear and understandable, providing developers with concrete information about what went wrong and how the issue can be resolved. The message should (SHOULD) be as precise as possible and avoid technical details that may not be helpful for most users.
If additional information about the error is available, it MUST be provided in the details field to enable a more accurate diagnosis. As many relevant details as possible should (SHOULD) be included without exposing sensitive information. The details might also contain guidance for resolving the issue, e.g., "Please provide a valid integer value for 'leasingPeriod'." Translations should (SHOULD) be designed to be directly displayable in applications, allowing users to view error messages in their preferred language.
The API documentation must (MUST) provide examples of common error responses to help developers understand and appropriately react to error messages.
Example of an Invalid Request:
{
"errors": [
{
"code": "INVALID_REQUEST",
"message": "The request body is missing required fields.",
"details": "Required field 'email' is missing.",
"translations": {
"de": "Erforderliches Feld 'email' fehlt."
}
}
]
}
Example of an Unauthorized Request:
{
"errors": [
{
"code": "UNAUTHORIZED",
"message": "Authentication credentials were missing or invalid.",
"details": "Ensure that the Authorization header is present and contains a valid token.",
"translations": {
"de": "Stellen Sie sicher, dass die Autorisierungs-Header vorhanden ist und ein gültiges Token enthält."
}
}
]
}
Examples of Standard Error Codes:
- INVALID_PARAMETER - The 'email' field is required.
- UNAUTHORIZED - Authentication is required to access this resource.
- FORBIDDEN - You do not have permission to perform this action.
- NOT_FOUND - The resource you are looking for does not exist.
- METHOD_NOT_ALLOWED - The HTTP method used is not allowed for this endpoint.
- CONFLICT - A resource with the same ID already exists.
- TOO_MANY_REQUESTS - Rate limit exceeded. Please try again later.
- INTERNAL_SERVER_ERROR - An unexpected error occurred on the server.
- SERVICE_UNAVAILABLE - The service is temporarily unavailable. Please try again later.
Logging and Monitoring of Errors
Effective logging and monitoring are crucial for detecting, diagnosing, and resolving errors in APIs. A system for error logging and monitoring helps quickly identify and address the root causes of problems. Therefore, the following measures MUST be implemented for our interfaces:
-
Logging of Errors: All errors occurring in an API must (MUST) be logged. This includes both HTTP error codes and detailed error messages, along with the specific circumstances under which the error occurred.
Error logs should (SHOULD) contain sufficiently detailed information to facilitate troubleshooting. This includes timestamps, endpoints, HTTP methods used, user information (if available), and the full error message.
Logs should (SHOULD) be structured and consistently formatted to allow for automated processing and analysis. JSON format or similar structured formats are recommended.
-
Monitoring of Errors: A monitoring system must (MUST) be implemented to track error events in real-time. This system should be able to trigger alerts or notifications in the event of critical errors or unusual error rates.
The monitoring system should (SHOULD) provide dashboards and reports that offer an overview of the frequency and types of errors. These reports should be regularly reviewed to identify and address potential issues early.
It is recommended should (SHOULD) to use a centralized logging system that consolidates all API logs. Tools such as the ELK Stack (Elasticsearch, Logstash, Kibana), Splunk, or other specialized logging and monitoring platforms can assist in this process.
-
Error Analysis and Resolution: Error logs must (MUST) be regularly reviewed and analyzed to identify the causes of problems and take appropriate corrective actions.
A systematic process for error analysis and resolution should (SHOULD) be established to ensure that recurring or critical errors are addressed quickly.
-
Privacy and Security: Logging and monitoring must (MUST) comply with privacy and security policies. Sensitive information, such as personal data, MUST be anonymized or encrypted to ensure the security of the data.