HTTP Status Codes: Guida Completa con Esempi
HTTP Status Codes: guida completa con esempi pratici. 200 OK, 301 redirect, 404 not found, 500 server error. Impara tutti i codici per le tue API REST.
Cosa Sono gli HTTP Status Code
Gli HTTP status code sono risposte numeriche a 3 cifre che i server web inviano per comunicare l'esito di una richiesta. Comprendere questi codici è fondamentale per sviluppare e debuggare applicazioni web, API REST, e integrazioni di servizi. Questa guida copre tutti i codici importanti, organizzati per categoria, con esempi pratici di quando e come usarli.
Struttura dei Codici
Le 5 Classi
| Range | Categoria | Significato |
|---|---|---|
| 1xx | Informational | Richiesta ricevuta, processo continua |
| 2xx | Success | Richiesta completata con successo |
| 3xx | Redirection | Azione ulteriore richiesta |
| 4xx | Client Error | Errore nella richiesta del client |
| 5xx | Server Error | Errore nel server |
1xx - Informational
# 100 Continue
# Il server ha ricevuto gli header e il client può inviare il body
# Utile per richieste con body grandi
# Request
POST /upload HTTP/1.1
Expect: 100-continue
Content-Length: 10485760
# Response
HTTP/1.1 100 Continue
# Client invia il body
# 101 Switching Protocols
# Upgrade da HTTP a WebSocket
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
2xx - Success
200 OK
# Il più comune: richiesta completata con successo
GET /api/users/1 HTTP/1.1
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"name": "Mario Rossi",
"email": "mario@example.com"
}
201 Created
# Risorsa creata con successo (POST)
POST /api/users HTTP/1.1
Content-Type: application/json
{"name": "Luigi", "email": "luigi@example.com"}
HTTP/1.1 201 Created
Location: /api/users/2
Content-Type: application/json
{
"id": 2,
"name": "Luigi",
"email": "luigi@example.com"
}
204 No Content
# Successo ma nessun contenuto da restituire
# Tipico per DELETE e alcuni PUT
DELETE /api/users/1 HTTP/1.1
HTTP/1.1 204 No Content
# Nessun body nella risposta
206 Partial Content
# Risposta parziale (range request)
# Usato per download resumable e streaming
GET /video.mp4 HTTP/1.1
Range: bytes=0-1023
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/1048576
Content-Length: 1024
# Primi 1024 byte del file
3xx - Redirection
301 Moved Permanently
# La risorsa è stata spostata definitivamente
# I motori di ricerca aggiornano l'indice
# Il browser può cachare
GET /old-page HTTP/1.1
HTTP/1.1 301 Moved Permanently
Location: https://example.com/new-page
# Uso tipico: migrazione URL, HTTPS redirect
302 Found (Temporary Redirect)
# Redirect temporaneo
# Non cachato, il browser richiede sempre l'URL originale
GET /promo HTTP/1.1
HTTP/1.1 302 Found
Location: /current-promotion
# Uso: A/B testing, promozioni temporanee
304 Not Modified
# Risorsa non modificata, usa cache locale
# Risparmia bandwidth
GET /style.css HTTP/1.1
If-Modified-Since: Wed, 01 Jan 2024 00:00:00 GMT
If-None-Match: "abc123"
HTTP/1.1 304 Not Modified
# Nessun body, usa versione in cache
307 e 308
# 307 Temporary Redirect
# Come 302 ma mantiene il metodo HTTP (POST rimane POST)
# 308 Permanent Redirect
# Come 301 ma mantiene il metodo HTTP
POST /old-form HTTP/1.1
HTTP/1.1 307 Temporary Redirect
Location: /new-form
# Il browser fa POST a /new-form, non GET
4xx - Client Error
400 Bad Request
# Richiesta malformata o invalida
POST /api/users HTTP/1.1
Content-Type: application/json
{invalid json}
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Invalid JSON",
"details": "Unexpected token 'i' at position 1"
}
401 Unauthorized
# Autenticazione richiesta o fallita
GET /api/protected HTTP/1.1
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
{
"error": "Authentication required",
"message": "Please provide a valid access token"
}
# NOTA: Il nome è fuorviante
# 401 = non autenticato (chi sei?)
# 403 = non autorizzato (non hai permesso)
403 Forbidden
# Autenticato ma non autorizzato
GET /api/admin/users HTTP/1.1
Authorization: Bearer user-token
HTTP/1.1 403 Forbidden
{
"error": "Forbidden",
"message": "Admin access required"
}
# Anche per risorse che non vuoi rivelare esistano
404 Not Found
# Risorsa non trovata
GET /api/users/99999 HTTP/1.1
HTTP/1.1 404 Not Found
{
"error": "Not Found",
"message": "User with ID 99999 does not exist"
}
# NOTA: Usa 404 anche quando non vuoi rivelare
# che una risorsa esiste (sicurezza)
405 Method Not Allowed
# Metodo HTTP non supportato per questa risorsa
DELETE /api/readonly-resource HTTP/1.1
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD
{
"error": "Method Not Allowed",
"allowed": ["GET", "HEAD"]
}
409 Conflict
# Conflitto con lo stato attuale della risorsa
POST /api/users HTTP/1.1
Content-Type: application/json
{"email": "existing@example.com"}
HTTP/1.1 409 Conflict
{
"error": "Conflict",
"message": "Email already registered"
}
# Usato per: duplicati, conflitti di versione
422 Unprocessable Entity
# JSON valido ma dati non validi
POST /api/users HTTP/1.1
Content-Type: application/json
{"email": "invalid-email", "age": -5}
HTTP/1.1 422 Unprocessable Entity
{
"error": "Validation Error",
"details": {
"email": "Invalid email format",
"age": "Must be positive"
}
}
# 400 = sintassi errata
# 422 = sintassi corretta, semantica errata
429 Too Many Requests
# Rate limiting
GET /api/data HTTP/1.1
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{
"error": "Rate limit exceeded",
"limit": 100,
"remaining": 0,
"reset": 1704067200
}
5xx - Server Error
500 Internal Server Error
# Errore generico del server
# Il server non sa cosa è andato storto
HTTP/1.1 500 Internal Server Error
{
"error": "Internal Server Error",
"message": "An unexpected error occurred"
}
# In produzione: non esporre dettagli
# In sviluppo: includi stack trace
502 Bad Gateway
# Errore dal server upstream (proxy/gateway)
# Il server proxy non riesce a raggiungere il backend
HTTP/1.1 502 Bad Gateway
{
"error": "Bad Gateway",
"message": "Unable to reach upstream server"
}
# Cause comuni:
# - Backend down
# - Timeout upstream
# - Risposta invalida dal backend
503 Service Unavailable
# Server temporaneamente non disponibile
# Manutenzione, sovraccarico
HTTP/1.1 503 Service Unavailable
Retry-After: 3600
{
"error": "Service Unavailable",
"message": "Server under maintenance",
"expected_recovery": "2024-01-15T14:00:00Z"
}
# Includere Retry-After quando possibile
504 Gateway Timeout
# Timeout dal server upstream
# Il proxy non ha ricevuto risposta in tempo
HTTP/1.1 504 Gateway Timeout
{
"error": "Gateway Timeout",
"message": "Upstream server did not respond in time"
}
Best Practices per API
Scegliere il Codice Giusto
# CREATE risorsa
POST /api/items
→ 201 Created (con Location header)
→ 400/422 se dati invalidi
→ 409 se duplicato
# READ risorsa
GET /api/items/1
→ 200 OK
→ 404 se non esiste
# UPDATE risorsa
PUT /api/items/1
→ 200 OK (con risorsa aggiornata)
→ 204 No Content (senza body)
→ 404 se non esiste
# DELETE risorsa
DELETE /api/items/1
→ 204 No Content
→ 404 se non esiste (o 204 se idempotente)
Error Response Format
// Formato consistente per errori
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
},
"requestId": "abc-123",
"timestamp": "2024-01-15T10:30:00Z"
}
Debugging
# Chrome DevTools → Network tab
# Vedi status code per ogni richiesta
# curl con verbose
curl -v https://api.example.com/data
# Node.js logging
app.use((req, res, next) => {
res.on('finish', () => {
console.log(`${req.method} ${req.url} → ${res.statusCode}`);
});
next();
});
Strumenti Correlati
Per testing e debug API:
- JSON Formatter - Formatta risposte API
- URL Encoder - Codifica parametri
- Base64 Encoder - Decodifica token
Conclusione
Usare i codici HTTP corretti è fondamentale per:
- Client: Gestire errori appropriatamente
- Monitoring: Alerting basato su status code
- SEO: Redirect corretti per motori di ricerca
- Cache: Comportamento corretto del browser
Ricorda: 4xx = problema del client, 5xx = problema del server.
Per altri strumenti utili, esplora i nostri tool online gratuiti. Per la reference completa, consulta MDN HTTP Status Codes.