HTTP 401 Unauthorized means the request lacks valid authentication credentials. Despite its name, this status is about authentication (who are you?), not authorization (what are you allowed to do?). The server MUST include a WWW-Authenticate header indicating the authentication scheme(s) accepted. This is the gateway status for protected resources — before any authorization check, the server verifies identity.
Response includes the status code, standard headers (including Content-Type), and a small diagnostic JSON body describing the request and returned status.
Simulator URL (copy in the app after load — not a normal link):
https://httpstatus.com/api/status/401
Example request:
curl -i "https://httpstatus.com/api/status/401"Authentication is required and has failed or has not yet been provided. Response must include WWW-Authenticate header.
On this code, Inspector focuses on semantics, headers, and correctness warnings that commonly affect clients and caches.
HTTP 401 Unauthorized has specific technical implications for API design, caching, and client behavior. Understanding the precise semantics helps distinguish it from similar status codes and implement correct error handling. The response should include a descriptive body following a consistent error schema (like RFC 7807 Problem Details) so clients can programmatically handle the error.
// Handle 401 Unauthorized in Express
app.use((err, req, res, next) => {
if (err.status === 401) {
return res.status(401).json({
type: 'https://api.example.com/errors/unauthorized',
title: 'Unauthorized',
status: 401,
detail: err.message
});
}
next(err);
});from fastapi import HTTPException
# Raise 401 Unauthorized
raise HTTPException(
status_code=401,
detail={
'type': 'unauthorized',
'message': 'Descriptive error for 401 Unauthorized'
}
)// Spring Boot 401 Unauthorized handling
@ExceptionHandler(CustomUnauthorizedException.class)
public ResponseEntity<ErrorResponse> handleUnauthorized(
CustomUnauthorizedException ex) {
return ResponseEntity.status(401)
.body(new ErrorResponse("Unauthorized", ex.getMessage()));
}// Return 401 Unauthorized
func errorHandler(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(401)
json.NewEncoder(w).Encode(map[string]any{
"status": 401,
"error": "Unauthorized",
"message": message,
})
}