400 Bad Request in Rest API - Time & Space Complexity
When a server returns a 400 Bad Request error, it means the request sent by the client is not understood or is malformed.
We want to understand how the server's processing time changes as the size or complexity of the bad request grows.
Analyze the time complexity of this simple request validation process.
// Pseudocode for request validation
function validateRequest(request) {
if (!request.headers || !request.body) {
return 400; // Bad Request
}
for (let field of requiredFields) {
if (!request.body.hasOwnProperty(field)) {
return 400; // Bad Request
}
}
return 200; // OK
}
This code checks if the request has required headers and body fields, returning 400 if something is missing.
Look for loops or repeated checks that affect time.
- Primary operation: Loop over required fields in the request body.
- How many times: Once for each required field.
The time to validate grows as the number of required fields increases.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time grows directly with the number of fields to check.
Time Complexity: O(n)
This means the time to detect a bad request grows linearly with the number of required fields checked.
[X] Wrong: "The 400 Bad Request check is always constant time because it just returns an error."
[OK] Correct: The server must check each required field, so the time depends on how many fields it verifies before deciding the request is bad.
Understanding how validation scales helps you write efficient APIs and shows you can reason about server performance in real projects.
"What if the validation also checked nested objects inside the request body? How would the time complexity change?"