401 means failed authentication, 403 forbidden access, 400 a bad request, 422 unacceptable content, 500 a server failure, 503 temporary unavailability. The code decides the client's reaction: on 401 the token is refreshed, on 403 it is not, on 503 the request is retried after Retry-After. The exact code is checked, not "any 4xx". APIs split 400 and 422 differently; the contract decides; a 500 on invalid input is a defect.
API · Status codes
The token has expired and the API answered 403. A bug, or is that by design?
A mobile client has a rule: on 401 refresh the token and repeat the request, on 403 show "No access". The server rejects an expired token with 403, and the user sees "No access" to their own profile when a silent token refresh was all that was needed. A test for "a 4xx response" stays green. The difference between 401 and 403 decides what the client does, so the pairs below are checked exactly.
Three pairs that get mixed up
401 and 403. Per RFC 9110, 401 Unauthorized means the request lacks valid credentials for this resource. The response must contain a WWW-Authenticate header with a scheme (for example Bearer). The name is misleading: in meaning it is about authentication ("who are you?"). 403 Forbidden means the server understood the request and the identity but refuses, and new credentials will not change that. It is about authorisation ("you are not allowed").
The token is missing, expired or corrupted. The client refreshes it or goes to login and repeats the request.
403
The user is known but has no rights. Logging in again will not help, "No access" is shown.
Figure 1. The same kind of refusal, but a different client reaction. That is why the code cannot be swapped.
400 and 422. 400 Bad Request: the server cannot or will not process the request because of a client error, most often syntax: broken JSON, an unparseable header, a missing required parameter. 422 Unprocessable Content (called "Entity" before RFC 9110): the content type is supported and the syntax is correct, but the server cannot carry out the content. A negative amount, an end date before the start date, an unknown currency. Many APIs return 400 in both cases, and that is fine if the contract says so and all endpoints behave the same.
500 and 503. 500 Internal Server Error: the server met an unexpected condition it did not handle, most often an unhandled exception. The client does not know whether a retry will help. 503 Service Unavailable: the server is temporarily unable to handle the request (overload, maintenance, a dependency not answering) and may send Retry-After with a pause. A service returns 503 on purpose, while 500 is always a reason for a defect.
Why it is built this way. A response code is a contract between the server, the client and the intermediaries: it decides whether to retry a request, refresh a token, show an error or page the on-call. So the question is not "is it an error" but "whose is it and does a retry make sense".
Example: from "any 4xx" to the exact status
Before: expect(res.status()).toBeGreaterThanOrEqual(400). A test like that does not notice that an expired token gives 403, or that a request without a token has no WWW-Authenticate. After: three requests, three different expectations.
import { test, expect, request as pw } from'@playwright/test';
test('admin endpoint: 401 vs 403', async () => {
const api = await pw.newContext({ baseURL: process.env.BASE_URL });
const url = '/v1/admin/users';
constas = (t: string) => ({ headers: { Authorization: 'Bearer ' + t } });
const anon = await api.get(url);
expect(anon.status()).toBe(401);
expect(anon.headers()['www-authenticate']).toMatch(/^Bearer/i);
const expired = await api.get(url, as(process.env.EXPIRED_TOKEN!));
expect(expired.status()).toBe(401); // a new login helpsconst user = await api.get(url, as(process.env.USER_TOKEN!));
expect(user.status()).toBe(403); // known user, no admin roleawait api.dispose();
});
An expired token is 401, because a new login helps even though the user is "known". A role without access is 403. The test keeps tokens in environment variables, and a client without headers is created with newContext: then there is no token from the config to "erase". For 400 and 422 two curl requests show the difference:
The first breaks the JSON syntax (400), the second has valid JSON with an invalid value (422, or 400 by contract). 503 needs a controllable server state: a test environment with a maintenance or dependency switch, and a check of the header:
An unexpected error in the code. For QA it is a defect: file a bug, add a case that reproduces it.
503
Deliberate temporary unavailability. Retry-After is expected, and the client repeats the request after a pause.
Figure 2. Different reactions: 500 goes to the bug tracker, 503 is checked for the header and for client behaviour.
Limits and alternatives
The contract outranks the RFC. Some APIs deliberately return 403 for an expired token or 400 instead of 422. That is not a bug if it is documented and works the same everywhere. A bug is a mismatch with the contract or different behaviour on neighbouring endpoints.
For someone else's resource 404 is more common than 403, so as not to reveal that an id exists. It is a deliberate approach, verified against the contract.
Some gateways and WAFs return 403 before the request reaches the service. They are told apart by the body and headers.
409 Conflict often fits better than 422 when the resource state is violated (a duplicate email, a stale version).
Common mistakes
Checking the status class instead of the code. Swapping 401 for 403 or 422 for 500 goes unnoticed, and the client reacts wrongly.
401 without WWW-Authenticate. The RFC requires it, and some clients and proxies rely on it.
Treating 500 on bad input as acceptable. It is an unhandled exception, and the same input may turn out to be an injection.
Not checking precedence. A request with no token and a bad body must give 401, not 400: authentication comes first.
Check yourself
An expired token gives 403 with the body "Forbidden". What breaks in the client, and what goes into the defect?
Answer
A client that refreshes the token on 401 gets no signal and shows "No access" instead of refreshing silently. In the defect: expected 401 with WWW-Authenticate: Bearer error="invalid_token", actual 403, and the consequence for the client.
A POST with the amount -5 returns 500 and a stack trace. Why is this more than "a wrong code"?
Answer
The server did not handle validation and failed with an exception: this is a server error, not a client one. The body also exposes internal details. A 400 or 422 with a clear error is expected, and the 500 plus the leak both go into a defect.
Related lessons: “Groups and a table of codes”, “The most popular traps”, “Error format and service response headers”, “JWT and testing tokens”.
In an interview.Junior: 401 means the client is not authenticated, 403 means it is authenticated but has no rights. 400 is a malformed request, 422 is syntactically correct but fails the rules. 500 is a server error, 503 means the service is temporarily unavailable. Middle/Senior: The code decides the client reaction: on 401 you refresh the token, on 403 you do not, on 503 you retry after Retry-After. So in tests I check the exact code and the accompanying headers, not "any 4xx", and compare with the contract, because different APIs split 400 and 422 differently. A 500 on invalid input is always a defect.
Groups and a table of codes
The first digit of a code sets the response class: 2xx success, 3xx redirection, 4xx client error, 5xx server error. A client reads an unknown code as the x00 of its class, so logic by class survives new codes. A 4xx usually means the request must change (408 and 429 are exceptions), a 5xx that the request may have been correct. To check a 301 or 307, a test disables redirects.
API · Status codes
The response is 304 with an empty body. A failure, or normal?
A test calls the catalogue a second time with If-None-Match, gets 304 with no body, and the code reads res.json() and fails. The developer says: "It all works, it is the cache." They are right, the mistake is in the test's expectations. To avoid memorising the table, first understand how the codes are grouped and what each group promises the client. Then the table is a hint, not a list to cram.
Five classes
Per RFC 9110 the first digit sets the response class. A client that does not know a specific code must treat it as the x00 of its class: an unknown 499 is read as 400, an unknown 599 as 500. So logic by class is robust against new codes.
Five classes and what they promise
Figure 1. 4xx and 5xx are highlighted: defects are searched there, but a 4xx can be the right reaction, while a 5xx almost never is.
Why it is built this way. The class answers two client questions: "did it work" and "whose fault is it". 4xx says that repeating the same request usually changes nothing until the client fixes it (the exceptions are 408 and 429, which are retried after a pause). 5xx says the request may have been fine, and a retry sometimes helps. That is enough for a client, a cache, a gateway and monitoring to decide without understanding the content.
Code
Meaning
When to expect
200 OK
Success with a body
GET, a successful PUT or PATCH
201 Created
Resource created
POST, the Location header
202 Accepted
Accepted, processing goes on
A long operation
204 No Content
Success without a body
DELETE, PUT without a body
301 / 308
Permanent redirect
A changed URL (308 keeps the method)
302 / 307
Temporary redirect
A redirect to login (307 keeps the method)
304 Not Modified
Unchanged, use the cache
A conditional GET with ETag
400 Bad Request
Invalid request
Broken JSON, missing parameter
401 / 403
Not authenticated / no rights
Token, roles
404 Not Found
No such resource
A non-existent id
405 Method Not Allowed
Method not supported
The Allow header is present
409 Conflict
State conflict
A duplicate, a parallel change
410 Gone
Removed for good
A retired API version
412 / 428
Condition failed / condition required
If-Match
415 Unsupported Media Type
Unsupported body format
A wrong Content-Type
422 Unprocessable Content
Syntax ok, content not acceptable
A rule is broken
429 Too Many Requests
Limit exceeded
Rate limiting, Retry-After
500 Internal Server Error
Unhandled error
Always a defect
502 / 503 / 504
Gateway, unavailable, timeout
A crash, overload
Example: two cases the client hides
Most HTTP clients follow redirects by default. A test calls an http:// address, sees 200 and does not notice that it is the result of a redirect, and of the wrong kind. The response:
HTTP/1.1 301 Moved Permanently
Location: https://api.shop.test/v1/orders/17
To check the redirect itself, it is switched off:
import { test, expect } from'@playwright/test';
test('http redirects to https', async ({ playwright }) => {
const api = await playwright.request.newContext();
const res = await api.get('http://api.shop.test/v1/orders/17', {
maxRedirects: 0, // otherwise the client follows and you see only 200
});
expect(res.status()).toBe(301);
expect(res.headers()['location']).toBe('https://api.shop.test/v1/orders/17');
await api.dispose();
});
Before: the test sees only the final 200. After: it checks 301, not 302, and the exact Location. The difference matters: a cache remembers 301 (and 308) for good, so a wrong permanent redirect breaks clients for a long time. One more subtlety: after 301 and 302 many clients change POST to GET, while 307 and 308 keep the method and the body. The second case, 304:
test('304 has no body', async ({ request }) => {
const first = await request.get('/v1/catalog');
const etag = first.headers()['etag'];
expect(etag).toBeTruthy();
const second = await request.get('/v1/catalog', {
headers: { 'If-None-Match': etag },
});
expect(second.status()).toBe(304);
expect(await second.text()).toBe('');
});
A 304 has no body, so reading res.json() makes no sense. The client uses its stored copy, and the test checks exactly that contract: 304 and an empty body.
Limits and alternatives
1xx is almost invisible in an API test: 100 Continue and 103 Early Hints are handled by the client or the server, and an HTTP library returns only the final response.
The table describes typical matches. When the contract says otherwise (422 instead of 400, 404 instead of 403), the contract is right.
Codes outside the table exist: 207 (WebDAV), 418 (a joke from RFC 2324). An unknown code is read by its class.
In a browser the browser itself hides redirects and 304: JS sees the final response. These codes cannot be checked through the UI, only at the API level or in DevTools.
Common mistakes
Expecting 200 everywhere. Creation is 201, deletion is 204, and a test for 200 misses an inexact code or fails on the right one.
Reading JSON from 204 and 304. There is no body, and the test fails, not the API.
Mixing up 301 and 302. A permanent redirect where a temporary one belongs gets cached and cannot be rolled back easily.
Dismissing 3xx as "not an error". A redirect to a login page instead of 401 in an API is a defect: the client gets HTML where it expected JSON.
Check yourself
A GET test gets 200, but the developer says it should be a 302 to login. Why does the test not see it, and how to fix it?
Answer
The client followed the redirect and returned the final login page with 200. Switch redirects off (maxRedirects: 0 in Playwright) and check 302 and Location. For an API it is even better to expect 401, not a redirect to HTML.
A server returns code 499 (not from an RFC). How should a client read it?
Answer
As 400, a generic client error: an unknown code is handled as the x00 of its class. So logic by class is robust against new codes, and the details come from the error body.
Related lessons: “401 vs 403, 400 vs 422, 500 vs 503”, “ETag, 304 and Cache-Control”, “The most popular traps”, “Key headers”.
In an interview.Junior: 2xx is success, 3xx is redirection, 4xx is a client error, 5xx is a server error. Creation gives 201, deletion 204, a missing resource 404. Middle/Senior: The class answers whose fault it is and whether a retry makes sense: 4xx must be fixed (except 408 and 429), 5xx can be retried. An unknown code is read as the x00 of its class. In tests I switch off automatic redirects to see 301 or 307, and I do not read JSON from 204 and 304. I check specific codes against the contract.
The most popular traps
The main trap is a dishonest status, such as 200 with an error in the body, since clients, caches, retries and monitoring read only the status. Others: 500 on malformed input, 404 on an empty list instead of an empty array, 201 without Location or an id, 204 with a body, different responses for another's and a non-existent resource. GraphQL is the exception: field errors arrive in errors with a 2xx status.
API · Status codes
The response is 200 and the body says "Insufficient funds". Why is the monitoring dashboard green?
A payment failed, the response is { "error": "Insufficient funds" }, but the status is 200. The status test is green, the error dashboard is empty, and clients complain. This "error in a success wrapper" is one of the most popular traps. There are others, and each has a cause and a consequence for the client. Below: the traps and a way to catch them with tests.
Why the status must be honest
The status is read by everything that does not understand the body: HTTP clients (what counts as success, what to retry), proxies and CDNs (what to cache), monitoring (counts 5xx and 4xx), retry logic. Only your code parses the body. If the status says "success", all of these nodes believe it and act accordingly: a cache stores the response with the error, a retry does not fire, an alert does not come.
An error in the body with status 200, and an honest response
Typical
200 and error in the body
The client, the cache and monitoring see success. Only whoever parses the body notices the error.
Better
4xx or 5xx with the error in the body
The status signals every node, the body explains the details. The dashboard and retries work.
Figure 1. The status and the body do not duplicate each other, they complement each other.
Traps and how to catch them
200 with an error in the body. Clients, monitoring and autotests consider the request successful. An exception: GraphQL, where by convention execution errors go into the errors array together with status 200. There you check the body, and that is normal.
500 on malformed input. The server did not handle validation and failed with an exception. Such a response often leaks a stack trace, and the same input may turn out to be an injection.
404 for an empty list./orders?status=archived with no results is 200 and an empty array: the collection exists, there are no items. 404 says the address itself does not exist.
201 without Location or an id. The client does not know where the created resource is.
204 with a body. Per RFC 9110 a 204 has no content, a client ignores the body or gets a length mismatch.
404 or 403 for someone else's resource. Both are acceptable: 404 does not reveal that the id exists. A defect is different behaviour for "someone else's" and "non-existent", which lets ids be enumerated.
A stack trace, SQL or paths in the error body. A leak of internals even when the code is right.
The first trap is caught by a helper that can be attached to every positive case:
import { expect, typeAPIResponse } from'@playwright/test';
exportasyncfunctionexpectNoHiddenError(res: APIResponse) {
if (!res.ok()) return; // 4xx and 5xx are honest about itconst body = await res.json().catch(() => null);
expect(body?.error, 'error inside a 2xx body').toBeUndefined();
expect(body?.errors ?? [], 'errors inside a 2xx body').toHaveLength(0);
}
It lets 4xx and 5xx through (they are honest), and in a 2xx it looks for error and errors. Add it to the base of your tests and you learn about all "successes with an error" without a separate case for each. For a 500 on malformed input a table of "garbage" values fits:
const garbage = ['', 'abc', '-1', '9'.repeat(40), "' OR 1=1 --", '%00'];
for (const value of garbage) {
test('no 5xx for page=' + JSON.stringify(value), async ({ request }) => {
const res = await request.get('/v1/orders', { params: { page: value } });
expect(res.status()).toBeLessThan(500);
});
}
The test does not check the exact code (the contract knows it), it asserts the main thing: a client error must not turn into a 5xx. The empty-list and 204 traps are checked directly:
test('empty list is 200, not 404', async ({ request }) => {
const res = await request.get('/v1/orders', { params: { status: 'archived' } });
expect(res.status()).toBe(200);
expect((await res.json()).items).toEqual([]);
});
test('204 has no body', async ({ request }) => {
const res = await request.delete('/v1/orders/17');
expect(res.status()).toBe(204);
expect(await res.text()).toBe('');
});
Someone else's and a non-existent resource
403 for someone else's
Honestly says "not allowed", but reveals that the resource exists. If ids are predictable, it is a hint for enumeration.
404 for someone else's
Does not reveal existence. The point is that "someone else's" and "non-existent" answer the same way.
Figure 2. Both approaches are legitimate if they are described in the contract and the same on all endpoints.
Limits and alternatives
Some teams deliberately return 200 with an application error code (old SOAP-like integrations, some payment gateways). For QA it is a risk that is raised, but the decision is the contract's.
The helper must be adapted to the project's error format (error, errors, code) and exclude fields that legitimately contain these words.
For batch operations (an array of items, some with errors) partial success is expressed by 207 or by 200 with a status per item. This too must be described in the contract.
A no-5xx test with garbage values is not a replacement for fuzzing: it only guarantees that known kinds of input do not break the server.
Common mistakes
Checking only the status and not looking at the body. A 2xx with an error in the body passes.
Treating "an error was returned" as enough. A 500 with a message is still an unhandled situation.
Accepting 404 for an empty collection. A client cannot tell "no items" from "no such address".
Checking 403 and 404 only for someone else's resource. They forget to compare with a non-existent id: a different response reveals that the resource exists.
Check yourself
A payment endpoint returns 200 and {"status":"failed","reason":"insufficient_funds"}. Is it a bug?
Answer
It depends on the contract. If status is the state of a payment (a payment was created and its status is "failed"), 200 or 201 is acceptable. If it is a refusal of the operation, a 4xx is more honest (for example 422 or 409), because clients and monitoring go by the code. It is a question for the contract, raised as a remark when the code and the body disagree.
A GraphQL request returned 200 and errors in the body. Should a defect be filed?
Answer
No, by convention GraphQL returns 200 when the request was parsed and executed (with partial errors in errors). There you check the errors array. A request that fails to parse or validate gets a 4xx under the GraphQL over HTTP spec (application/graphql-response+json).
Related lessons: “401 vs 403, 400 vs 422, 500 vs 503”, “Error format and service response headers”, “Error format: Problem Details and stable codes”, “Contract and performance: breaking change, 200 with an error, N+1”.
In an interview.Junior: A 500 on invalid input is a bug, and so is a 200 with an error in the body: clients and autotests go by the status. A 201 must return an id or Location, a 204 has no body. Middle/Senior: The status is read by caches, proxies, retries and monitoring, which do not parse the body, so a 200 with an error hides a failure. I attach a check that a 2xx has no error to the positive tests and run garbage values separately so that a client error never becomes a 5xx. GraphQL is the exception, with execution errors in errors under status 200 (a request that fails to parse or validate gets a 4xx under GraphQL over HTTP with graphql-response+json). For someone else's resource I accept 404 or 403 per the contract, but require the same response for "someone else's" and "non-existent".
Which status to expect in typical scenarios
The expected status comes from the contract (OpenAPI, documentation) and is written before the first run, not adjusted to the server's answer. If the contract is silent, rely on RFC 9110 semantics and ask developers. Typically: creation 201 with Location, deletion 204, duplicate 409 or 422, wrong type 400, someone else's resource 404 or 403. Also check headers and unchanged state after a negative case.
API · Status codes
A user was created twice with the same email. Which status should you expect?
This is a typical scenario question. There is a risk of answering with what you see in Postman and calling it the expectation: the server returned 200, so that must be the intent. Then the test merely records behaviour instead of checking it. The expected status must be known before the run, and there is an order of sources for that. Below: where to take it from, how to turn it into a test, and a table of typical scenarios.
How to determine the expected status
Three sources, in order of priority. The contract (OpenAPI, documentation, team agreements) always comes first. If the contract is silent, take the semantics of RFC 9110: what the code means by the standard. If there is nothing there either, rely on established practice and record the assumption as a question to the developers. A mismatch is visible only if the expectation was written down in advance, so fix it before the first run.
An expectation before the run and fitting to the response
Typical
Ran it and wrote down what came back
The test is green under any behaviour, including 500 or 200 on a duplicate. It checks nothing.
Better
An expectation from the contract before the run
A mismatch is a defect or an inaccuracy in the documentation. Both outcomes are useful, both must be recorded.
Figure 1. The same test, a different result: the question is who sets the expectation.
Situation
Status
A resource was created
201 and Location
Updated, a body is returned / not returned
200 / 204
Deleted
204; a repeated delete is 404 or 204 by the contract
A long operation, the result comes later
202 and Location of the job
A duplicate of a unique field, a state conflict
409 (some APIs give 422 here)
Broken JSON, an invalid type
400
A syntactically correct body breaks a rule
422
Someone else's resource
404 (does not reveal existence) or 403, as in the contract
Someone else changed the resource (If-Match)
412; if If-Match is required and missing, 428
The body format is not supported
415
The client asks for a format that does not exist (Accept)
406
The body is too large
413
The method is not allowed for the address
405 and Allow
Too many requests
429 and Retry-After
The server is unavailable, maintenance
503 and Retry-After
A gateway got no response from the server
502 (invalid response) or 504 (timeout)
Why it is built this way. Each row has a reason, not just "that is customary". Conditional requests (If-Match) exist so that two clients do not overwrite each other's changes: 412 says the version is stale, 428 says the client sent no condition at all. 202 says the work was accepted but not done, and the client has to poll the job. 405 together with Allow hints which methods are permitted, and 429 and 503 with Retry-After say when to retry.
Example: a duplicate email
The scenario from the question: create a user twice with the same email. Suppose the contract says: the first is 201, the second is 409 with a description of the conflict.
Before: the test reproduced what it saw, expect(second.status()).toBe(200), because that is how the server answered. But 200 means the server "created" a duplicate or silently overwrote an existing record. After: the expectation 409 comes from the contract, and the test fails, exposing the mismatch. The same logic works for conditional requests:
import { test, expect } from'@playwright/test';
test('PUT with a stale If-Match gives 412', async ({ request }) => {
const url = '/v1/orders/17'; // 412 is written from the contract, before the runconst etag = (await request.get(url)).headers()['etag'];
await request.put(url, { headers: { 'If-Match': etag }, data: { qty: 2 } });
const res = await request.put(url, {
headers: { 'If-Match': etag }, // the resource has changed since
data: { qty: 3 },
});
expect(res.status()).toBe(412);
});
The 412 test has three steps: get the version (ETag), change the resource, and repeat the request with the old version. The expected 412 is written from the contract before you have seen the response. For 405 and 429 the headers are checked too:
HTTP/1.1 405 Method Not Allowed
Allow: GET, POST
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Allow is mandatory here (RFC 9110), Retry-After is expected in rate-limited responses. A test that checks only the code misses a missing header the client relies on.
Limits and alternatives
The table is typical, not mandatory. For a duplicate 409 and 422 are equally legitimate. What is not acceptable is an API answering differently on neighbouring endpoints.
A repeated delete (DELETE is idempotent by semantics) may give 204 or 404: both fit the idea that the final state is the same. What matters is that it is written in the contract.
Long operations are sometimes easier to run synchronously, but then gateway timeouts give 504. For 202 you also test polling the job and the final status.
The body is also part of the expectation: a 4xx with an empty body makes the client's life harder, and a 5xx on a client error is always a defect.
Common mistakes
Writing the expectation after the run. The test becomes a snapshot of behaviour, not a check.
Not checking that the resource was not created. A 409 on a duplicate while the database still got a second record: the status is right, the state is corrupted. After a negative case, look at the state.
Ignoring accompanying headers. A 405 without Allow, a 429 without Retry-After, a 201 without Location break clients even though the code is right.
One "universal" code for all errors. A 400 for everything, from bad JSON to a duplicate, deprives the client of the chance to react differently.
Check yourself
Scenario: a repeated DELETE of the same resource. The test expects 404, the API returns 204. A bug or not?
Answer
Not necessarily. Both responses are compatible with idempotency: after the first delete the resource state is the same. The contract decides. If it says 404 and the API gives 204, it is a mismatch to fix or to document. If the contract is silent, the question goes to the developers.
A PUT without an If-Match header where the server requires a conditional request. Which status, and what is this code for?
Answer
428 Precondition Required. The server demands a condition to prevent a "lost update", when two clients overwrite each other's changes. If the condition is present but the version is stale, that is 412.
Related lessons: “401 vs 403, 400 vs 422, 500 vs 503”, “Positive and negative cases”, “ETag, 304 and Cache-Control”, “The methods table”.
In an interview.Junior: Creation gives 201 and Location, deletion 204, invalid data 400 or 422, a duplicate email 409, someone else's resource 404 or 403. Middle/Senior: I take the expected status from the contract and write it down before the run, not fit it to the response. If the contract is silent I rely on RFC 9110 and raise a question. Besides the code I check the headers (Location, Allow, Retry-After) and the state after a negative case. For a duplicate email the right answer is 409 or 422 by the contract, not 500 and not 201.