4xx Client Error Codes
Introduction
4xx client error status codes are HTTP responses that indicate the server received the request, but it could not process the request because something about the client side of the request was wrong. The problem may be invalid input, missing data, an incorrect URL, missing authentication, insufficient permission, a resource conflict, an unsupported content type, a payload that is too large, or a rate limit that has been exceeded.
For API testers, 4xx codes are extremely important because they prove how well an API handles negative scenarios. A good API is not judged only by successful 200 OK or 201 Created responses. It is also judged by how clearly, consistently, and securely it rejects invalid requests. If an API returns the wrong 4xx code, exposes internal error details, accepts invalid data, or returns 500 Internal Server Error for simple client mistakes, the API contract is weak and the user experience becomes confusing.
Unlike 5xx server errors, 4xx errors generally mean the client must correct something before the request can succeed. This does not always mean a human user made a mistake. The client may be a frontend application, mobile app, third-party integration, automation script, API gateway, or backend service. In all cases, the response should help the client understand what went wrong without exposing sensitive implementation details.
What Are 4xx Client Error Codes?
The 4xx status code range covers HTTP responses from 400 to 499. These codes are used when the server understands the request enough to respond, but the request cannot be completed because of a client-side problem. A simple definition is this: 4xx client error codes indicate that the request contains a problem that must be corrected by the client before it can be processed successfully.
The most common 4xx codes in API testing include 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 406 Not Acceptable, 408 Request Timeout, 409 Conflict, 410 Gone, 412 Precondition Failed, 413 Content Too Large, 414 URI Too Long, 415 Unsupported Media Type, 422 Unprocessable Entity, and 429 Too Many Requests.
Each code has a different meaning. A missing authentication token should not be treated the same as a nonexistent resource. A validation failure should not be treated the same as a rate-limit failure. A duplicate username should not be treated the same as malformed JSON. Accurate status codes make APIs easier to consume, automate, monitor, and debug.
400 Bad Request
400 Bad Request is used when the server cannot process the request because it is malformed, syntactically invalid, or contains invalid request data. It is one of the most common client error responses in API testing. A request body with broken JSON, missing required fields, wrong query-parameter format, invalid date format, or unacceptable basic input may produce a 400 response.
For example, a client may submit malformed JSON:
POST /users
Content-Type: application/json
{
"name":
}
The server may respond:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Invalid request body"
}
The key point is that the request itself is not acceptable. The server is not failing internally; it is rejecting a client request that cannot be processed as submitted. A good API should return a clear error message and, where appropriate, field-level validation details. However, it should not expose stack traces, SQL errors, framework exceptions, or internal class names.
In testing, verify invalid JSON, missing required fields, invalid query parameters, incorrect date formats, invalid enum values, unsupported pagination values, and malformed request paths. A 400 response should be consistent across endpoints and should follow the standard error schema used by the application.
401 Unauthorized
401 Unauthorized means authentication is required or the provided authentication credentials are missing, invalid, expired, malformed, or otherwise unacceptable. The name can be slightly confusing because it sounds like authorization, but in practice 401 is about authentication: the server does not know who the client is, or it cannot trust the credentials provided.
A client may request a protected profile endpoint without a token:
GET /profile
The server may respond:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": "Authentication required"
}
Common causes include missing JWT token, expired token, invalid token signature, incorrect API key, malformed Authorization header, revoked session, or unsupported authentication scheme. In API testing, these are not optional edge cases. Authentication failure handling is part of core API security.
A strong 401 test suite validates missing credentials, invalid credentials, expired credentials, revoked credentials, malformed tokens, wrong token issuer, wrong audience, and attempts to use credentials in the wrong environment. The response should not reveal sensitive details such as whether a username exists, how token validation is implemented, or which internal authentication provider failed.
403 Forbidden
403 Forbidden means the client is authenticated, but the authenticated identity does not have permission to access the requested resource or perform the requested action. This is the important difference between 401 and 403. A 401 response says "you are not authenticated." A 403 response says "you are authenticated, but you are not allowed."
For example, a regular user may attempt to access an admin endpoint:
GET /admin/users
Authorization: Bearer valid-user-token
The server may respond:
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": "Access denied"
}
Authorization testing is one of the most important uses of 403. Testers should verify role-based access control, permission-based access control, ownership rules, tenant isolation, organization boundaries, feature permissions, and administrative restrictions. A user should not be able to view or modify resources that belong to another user, another tenant, or another permission group.
Some APIs intentionally return 404 instead of 403 for certain sensitive resources to avoid revealing whether the resource exists. That can be valid if it is a documented security design. However, teams should not casually mix 403 and 404. The expected behavior should be clear, consistent, and tested.
404 Not Found
404 Not Found means the requested resource could not be found. This may happen because the endpoint path is wrong, the resource ID does not exist, the resource was deleted, or the resource is not visible to the current user. It is one of the most familiar HTTP status codes, but it still needs careful testing in APIs.
A request may look like this:
GET /users/9999
If no user exists with that ID, the server may respond:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": "User not found"
}
Testing 404 responses should cover invalid endpoints, nonexistent resource IDs, deleted resources, hidden resources, wrong parent-child combinations, and tenant isolation. For example, GET /orders/123/items/999 may return 404 because item 999 does not exist, or because it does not belong to order 123. These relationships matter in real APIs.
A useful error response should be clear but not overly revealing. For public APIs, avoid exposing database details or internal routing information. For security-sensitive resources, consider whether returning 404 instead of 403 is part of the security strategy. API tests should match the agreed design.
405 Method Not Allowed
405 Method Not Allowed means the requested resource exists, but the HTTP method used by the client is not supported for that resource. For example, an endpoint may support GET and POST but not DELETE. If the client sends DELETE, the server should reject the request with 405 rather than pretending the endpoint does not exist.
For example:
DELETE /users
If /users supports only GET and POST, the server may respond:
HTTP/1.1 405 Method Not Allowed
In many APIs, a 405 response should include an Allow header listing supported methods. This helps clients understand what operations are valid. For example, Allow: GET, POST tells the client that DELETE is not permitted on that resource.
Testing 405 responses is useful for verifying routing and method contracts. Try unsupported methods against valid paths. Confirm that the API rejects them consistently, does not accidentally execute a state-changing operation, and returns a useful method-not-allowed response. This is especially important when API gateways or framework routing rules are involved.
406 Not Acceptable
406 Not Acceptable means the server cannot generate a response that matches the format requested by the client. This usually relates to the Accept header. If the client requests XML but the API supports only JSON, the server may return 406.
For example:
GET /users/101
Accept: application/xml
If only JSON is supported, the response may be:
HTTP/1.1 406 Not Acceptable
In practice, many APIs ignore unsupported Accept headers and return JSON anyway. Whether that is acceptable depends on the API contract. If the contract promises strict content negotiation, 406 should be tested. If the contract says all responses are JSON regardless of Accept, tests should validate that behavior instead.
Content negotiation defects can affect clients that depend on specific formats, languages, or media types. Testers should verify supported response formats, unsupported formats, default behavior when no Accept header is provided, and behavior when multiple acceptable formats are listed.
408 Request Timeout
408 Request Timeout means the client took too long to send the complete request. The server waited for the request but did not receive it within the configured time limit. This can happen during slow uploads, unstable network conditions, interrupted connections, or clients that open a connection and then do not send the full request.
For API testers, 408 is less common in normal functional testing because it often depends on network timing and server configuration. However, it is important in performance, reliability, and upload testing. If the application supports large uploads or long client submissions, timeout behavior should be tested carefully.
A good system should fail gracefully. It should close the request safely, not create partial corrupt data, not keep server resources locked forever, and not expose internal timeout details. If partial data was received, the system should handle cleanup correctly. For resumable uploads, the API should document whether the client can resume from a checkpoint.
409 Conflict
409 Conflict means the request conflicts with the current state of the resource. This is common when a client tries to create a duplicate record, update an outdated version, submit a state transition that is not allowed, or perform an operation that conflicts with existing business rules.
A user registration request may try to create an already-used username:
POST /users
Content-Type: application/json
{
"username": "john"
}
The server may respond:
HTTP/1.1 409 Conflict
Content-Type: application/json
{
"error": "Username already exists"
}
Conflict testing is important in systems with uniqueness rules, concurrency, inventory, booking, payments, order state changes, and versioned updates. For example, two users may try to book the same seat. Two clients may update the same profile version. A user may try to cancel an order that has already shipped. These are not malformed requests; they are requests that conflict with current state.
A 409 response should explain the conflict clearly enough for the client to recover. It may include a conflict code, field name, current state, or retry guidance. It should not expose sensitive internal data or database constraint names.
410 Gone
410 Gone means the requested resource has been permanently removed and is no longer available. It is different from 404 because 404 may simply mean the resource was not found, while 410 indicates the server knows the resource existed and was intentionally removed.
For example:
GET /old-api
The server may respond:
HTTP/1.1 410 Gone
This code can be useful for deprecated endpoints, removed content, deleted public resources, or APIs that want to signal permanent removal clearly. In many projects, 404 is used more often than 410, but 410 can improve clarity when the removal is intentional and permanent.
Testing 410 involves verifying lifecycle rules. If an API endpoint is retired after a deprecation period, does it return 410? Does the response guide clients to replacement documentation? Does it avoid redirecting clients forever? Does the sitemap, documentation, and SDK behavior match the removal strategy?
412 Precondition Failed
412 Precondition Failed means the request included a condition that was not satisfied. It is commonly used with conditional headers such as If-Match, If-Unmodified-Since, and If-None-Match. These headers help prevent lost updates and support optimistic concurrency control.
Imagine a client reads a resource with version information, modifies it, and sends an update only if the version has not changed. If another client already updated the resource, the precondition fails and the server can return 412.
PUT /documents/25
If-Match: "version-3"
If the current document version is now version 4, the server may respond:
HTTP/1.1 412 Precondition Failed
Testing 412 is important in collaborative editing, inventory management, document workflows, and APIs where concurrent updates are possible. Without proper precondition handling, one user's update can silently overwrite another user's changes.
413 Content Too Large
413 Content Too Large, historically known as Payload Too Large, means the request body exceeds the maximum size the server is willing or able to process. This is common in file uploads, large JSON payloads, image uploads, video uploads, and bulk import APIs.
For example, if the maximum upload size is 2 GB and a client attempts to upload a 10 GB video, the server should reject the request with 413. The response may include guidance about the allowed size. In some cases, the server may close the connection early to avoid receiving an enormous body.
Testing 413 should include boundary values. Verify payloads just below the limit, exactly at the limit, and above the limit. Confirm that the response is controlled, clear, and does not create partial records. If resumable upload or chunked upload is supported, test those paths separately.
Security is relevant here. APIs should defend against excessively large payloads that can consume memory, disk, bandwidth, or processing capacity. A correct 413 response protects system stability.
414 URI Too Long
414 URI Too Long means the request URL is longer than the server can process or is willing to accept. This can happen when clients send too many query parameters, encode large filter objects into the URL, or accidentally create recursive redirect URLs.
For example:
GET /products?filter=very-long-query-string...
If the URL exceeds configured limits, the server may return 414. In API design, this often suggests that the client should use a POST search endpoint with a request body for complex search criteria, rather than placing everything in the query string.
Testing 414 is useful for search APIs, reporting APIs, filter-heavy endpoints, and systems that accept encoded state in URLs. Verify reasonable limits, controlled error responses, and guidance for clients when the URL is too long.
415 Unsupported Media Type
415 Unsupported Media Type means the request body format is not supported by the server. This usually relates to the Content-Type header. If an API accepts only JSON and the client sends XML, plain text, form data, or an incorrect content type, the server may return 415.
For example:
POST /users
Content-Type: application/xml
If only JSON is accepted, the response may be:
HTTP/1.1 415 Unsupported Media Type
Testing 415 should include missing Content-Type, wrong Content-Type, unsupported but valid payload formats, mismatched body and header, and supported media types. A request with Content-Type: application/json but an XML body may produce 400 or 415 depending on the API design. The important requirement is consistency.
This code helps clients correct the request format. A useful error response may say that application/json is required. It should not expose parser stack traces or framework-specific exceptions.
422 Unprocessable Entity
422 Unprocessable Entity means the request syntax is valid, but the submitted data fails semantic, validation, or business rules. It is commonly used when the JSON is well-formed and the content type is correct, but the values are not acceptable.
For example:
POST /users
Content-Type: application/json
{
"email": "invalid-email"
}
The server may respond:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Validation failed",
"fields": {
"email": "Email format is invalid"
}
}
The difference between 400 and 422 depends on project conventions. Many APIs use 400 for all validation problems. Others use 400 for malformed requests and 422 for validly structured requests that fail business validation. Both approaches can work if they are documented and consistent.
Testing 422 involves invalid email formats, invalid phone numbers, dates outside allowed ranges, business-rule violations, invalid state transitions, values below minimum limits, values above maximum limits, and cross-field validation rules. A good response should identify the failing fields and help the client correct the request.
429 Too Many Requests
429 Too Many Requests means the client has exceeded the API's rate limit. Rate limiting protects the API from abuse, accidental traffic spikes, scraping, brute-force attacks, and resource exhaustion. It also helps ensure fair usage among clients.
For example, if the API allows 100 requests per minute and the client sends 500 requests within that minute, the server may respond:
HTTP/1.1 429 Too Many Requests
Retry-After: 60
The Retry-After header is useful because it tells the client when to try again. Some APIs also return rate-limit headers showing the limit, remaining requests, and reset time. These headers make client behavior more predictable.
Testing 429 requires controlled traffic generation. Verify the request limit, window behavior, reset behavior, per-user limits, per-IP limits, per-token limits, and whether different endpoints have different thresholds. Also test that rate limiting does not incorrectly block unrelated users. A broken rate limiter can either fail to protect the API or block legitimate traffic.
Summary of Common 4xx Codes
The 4xx family can be summarized by the client-side problem each code represents. 400 means invalid request. 401 means authentication failed or is missing. 403 means permission is denied. 404 means the resource is not found. 405 means the method is not allowed. 406 means the requested response format is not available. 408 means the client took too long. 409 means a resource-state conflict occurred. 410 means the resource is permanently gone. 412 means a precondition failed. 413 means the request body is too large. 414 means the URL is too long. 415 means the content type is unsupported. 422 means validation failed even though the syntax may be valid. 429 means the client exceeded a rate limit.
Memorizing the numbers is useful for interviews, but understanding the scenario is more important for real testing. When a test fails, the question is not only "which code did we get?" The better question is "does this code accurately describe the client-side problem and guide the client toward the correct fix?"
Real-World Examples
A customer submits an incomplete registration form. The email field is missing, the password is too short, or the JSON body is malformed. Depending on the API's validation strategy, the server may return 400 Bad Request or 422 Unprocessable Entity. The tester should verify the error schema and field-level messages.
A user tries to access a profile endpoint without logging in. The API returns 401 Unauthorized. If the same user logs in successfully but then attempts to access an admin endpoint, the API returns 403 Forbidden. These two tests together prove the difference between authentication and authorization.
A customer opens a deleted product link. The API may return 404 Not Found if the product is unavailable, or 410 Gone if the product was permanently removed and the system intentionally exposes that lifecycle state. The expected behavior depends on business rules.
A user attempts to register with an email address that already exists. This is usually a 409 Conflict because the request conflicts with a uniqueness rule. A different validation issue, such as an invalid email format, may return 422 or 400.
An automated script sends thousands of requests within seconds and exceeds the configured rate limit. The API returns 429 Too Many Requests, ideally with retry guidance. This proves that the API protects itself from excessive traffic.
API Testing Considerations
Testing 4xx responses should be systematic. Start with request validation. Send invalid JSON, missing required fields, invalid parameter values, unsupported enum values, invalid dates, boundary values, and malformed paths. Verify that the API rejects bad input gracefully and consistently.
Then test authentication. Cover missing tokens, invalid tokens, expired tokens, revoked tokens, malformed Authorization headers, wrong API keys, and credentials from the wrong environment. The response should be 401 when authentication fails. It should not leak sensitive details about token validation internals.
Next, test authorization. Use users with different roles, permissions, organizations, and ownership relationships. A normal user should not access admin APIs. A user from one tenant should not access another tenant's records. An authenticated but unauthorized request should generally return 403, unless the API intentionally hides resource existence with 404.
Resource validation is also essential. Test existing resources, nonexistent resources, deleted resources, invalid IDs, wrong parent-child relationships, and hidden resources. Confirm whether the expected response is 404, 410, 403, or another code based on the contract.
Finally, validate error response structure. Every error response should include the expected status code, message, application error code, response schema, correlation ID where applicable, and field-level details when useful. Error formats should be consistent across endpoints.
Error Response Quality
A good 4xx response helps the client fix the request. It should be specific enough to be useful and generic enough to be safe. For example, "Email format is invalid" is useful. "NullPointerException in UserValidationService line 82" is unsafe and unprofessional. Error responses should not expose SQL queries, table names, framework stack traces, server file paths, token secrets, or internal network information.
Consistency matters. If one endpoint returns {"error":"Invalid email"}, another returns {"message":"Bad input"}, and another returns an HTML error page, automation becomes harder and client code becomes messy. A shared error schema improves testability. It also improves documentation and support because every error has a predictable shape.
Field-level errors are valuable for validation responses. If a request contains invalid email, missing password, and invalid date of birth, the response should ideally identify each field. This helps frontend applications display useful validation messages and helps API testers assert exact validation behavior.
Correlation IDs or request IDs are also useful. They allow support teams and developers to trace a failed request through logs. A tester can include the correlation ID in a defect report, making debugging faster.
Common Mistakes
A common mistake is returning 500 Internal Server Error for invalid client input. If the client sends malformed JSON, a missing required field, or an unsupported parameter value, the API should usually return a 4xx response. A 500 response suggests the server failed unexpectedly, which misleads clients and monitoring systems.
Another mistake is using 404 Not Found for authentication problems. If the user has not authenticated, 401 Unauthorized is generally the correct response. Use 404 for missing resources or intentionally hidden resources, not as a blanket response for every access issue.
A third mistake is confusing 401 and 403. If authentication is missing or invalid, use 401. If authentication succeeded but permission is denied, use 403. This distinction is important for client behavior. A 401 response may trigger login or token refresh. A 403 response should usually tell the client that login alone will not solve the issue.
Another common mistake is returning vague messages such as "Something went wrong" for all 4xx errors. That message does not help clients fix their request. It may be acceptable for security-sensitive cases, but for normal validation errors the response should be more actionable.
APIs also sometimes return 200 OK with an error message in the body. This is poor HTTP usage for most APIs. Client errors should usually use 4xx codes so clients, logs, dashboards, and monitoring tools can correctly classify the result.
Best Practices
Return the most appropriate 4xx status code for the scenario. Use 400 for malformed or broadly invalid requests, 401 for missing or invalid authentication, 403 for authenticated users who lack permission, 404 for missing resources, 405 for unsupported methods, 409 for state conflicts, 415 for unsupported content types, 422 for semantic validation failures if your API uses that convention, and 429 for rate-limit violations.
Keep error responses consistent across the API. Use a standard schema with fields such as error code, message, details, timestamp, path, and correlation ID if those fields are part of your platform convention. Avoid returning different error shapes from different services unless there is a documented reason.
Provide meaningful validation details where appropriate. If multiple fields are invalid, list them. If a value is outside an allowed range, explain the range. If a rate limit is exceeded, include retry guidance when possible. Useful errors reduce support effort and help clients recover.
Never expose sensitive internal information. A 4xx response should help the client correct the request, not reveal database design, security rules, server stack traces, or internal infrastructure. Security review should include error-message review.
Automate negative scenarios. Many teams automate only happy paths and manually test failures late. This creates risk. Negative API tests are stable, fast, and valuable because they validate contract behavior without depending heavily on UI flows.
Interview-Ready Explanation
4xx client error HTTP status codes indicate that the server received the request but could not process it because of a problem with the client's request. The issue may be invalid input, missing authentication, insufficient permission, an incorrect URL, a method that is not allowed, unsupported media type, validation failure, conflict, or rate-limit violation.
Common examples include 400 Bad Request for invalid request syntax or data, 401 Unauthorized for missing or invalid authentication, 403 Forbidden for insufficient permissions, 404 Not Found when the resource does not exist, 405 Method Not Allowed when the HTTP method is unsupported, 409 Conflict for resource-state conflicts, 415 Unsupported Media Type for unsupported request formats, 422 Unprocessable Entity for validation failures, and 429 Too Many Requests when rate limits are exceeded.
In API testing, 4xx codes are essential for validating request validation, authentication, authorization, resource handling, rate limiting, and error response quality. A good API should return the correct 4xx code, a consistent error format, useful messages, and no sensitive internal details.
Key Takeaway
4xx status codes are the API's way of telling the client that the request must be corrected. They are not server crashes. They are controlled rejections of invalid, unauthorized, forbidden, conflicting, unsupported, or excessive requests. When used correctly, they make APIs easier to consume and safer to operate.
For API testers, the practical rule is clear: do not stop at happy-path success testing. Validate how the API fails. Check the exact status code, error body, headers, schema, security behavior, and business rule behind the failure. Strong 4xx testing proves that the API handles real-world misuse, invalid input, permission boundaries, and traffic limits with clarity and control.