Effective Test Cases to Uncover 400 Bad Request Errors in APIs
What 400 Bad Request means?
The 400 Bad Request error indicates that the server cannot understand or process a request due to a problem with the request itself. This typically results from syntax errors, missing required information, or malformed data.
Test Cases focused on 400 Bad Request errors
To ensure your application handles these errors properly, consider including test cases for the following scenarios:
Incorrect Parameter Format: send a parameter with an incorrect data type (e.g., providing a string instead of a number for an ID).
Extra parameters: include extra parameters in the request that are not expected by the API.
Malformed JSON: send a request with a JSON body that is invalid (e.g., missing quotes, incorrect syntax).
Incorrect Content-Type header: set an incorrect Content-Type header for the request body (e.g., application/json for a form submission).
Missing required parameters
- URL path: simulate a request that omits a required parameter in the URL path.
- Query string: send a request that lacks a necessary query parameter.
- Request body: submit a request body that is missing a required field; send a request without a request body.
- Headers: exclude a mandatory header from the request.
400 Bad Request vs. 404 Not Found
Distinguishing between a 400 Bad Request and a 404 Not Found can be tricky. Consider this scenario: imagine that you need to pass an ID as path parameter for a DELETE/GET/PATCH/UPDATE endpoint. What is expected about this ID?
- The ID must follow a specific format. E.g: 10 numbers
- The ID must correspond to an existing resource on the server.
Suppose you passed the ID as ‘abc#$123’. The format is incorrect, and the resource doesn’t exist.
In this scenario, the most appropriate HTTP status code to return is 400 Bad Request. The server cannot interpret or process the request because of the format issue, not because the resource doesn’t exist.
The Result?
By testing these mistakes, we find problems early on. This makes the API stronger and easier to use for everyone.