401 vs 403, 400 vs 422, 500 vs 503
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").
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="expired"
Content-Type: application/problem+json
{ "type": "https://api.shop.test/errors/token-expired",
"title": "Token expired", "status": 401 }
What a client does after 401 and after 403
401
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.
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';
const as = (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 helps
const user = await api.get(url, as(process.env.USER_TOKEN!));
expect(user.status()).toBe(403); // known user, no admin role
await 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:
# 1. broken JSON syntax: expect 400
curl -i -X POST "$BASE/v1/transfers" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"amount": 150,'
# 2. valid JSON, rule broken (negative amount): 422, or 400 by contract
curl -i -X POST "$BASE/v1/transfers" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" -d '{"amount": -5}'
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:
HTTP/1.1 503 Service Unavailable
Retry-After: 30
Content-Type: application/problem+json
{ "title": "Service unavailable", "status": 503 }
500 and 503 for a client and for a tester
500
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.
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.
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.