Códigos de status HTTP

Todos os códigos de status HTTP registrados: o que significam, quando aparecem e onde são definidos.

100ContinueThe server received the request headers and the client should send the body.
101Switching ProtocolsThe server is switching to the protocol the client asked for in the Upgrade header.
102ProcessingThe server accepted the request and is still working on it.
103Early HintsHeaders sent ahead of the final response so the client can start preloading resources.
104Upload Resumption SupportedThe server supports resuming this upload if it is interrupted.
200OKThe request succeeded.
201CreatedThe request succeeded and created a new resource.
202AcceptedThe request was accepted for processing, which hasn't finished.
203Non-Authoritative InformationSuccess, but a proxy changed the response the origin server sent.
204No ContentThe request succeeded and there is no body.
205Reset ContentSuccess; the client should reset the form or view that sent the request.
206Partial ContentThe response holds only the byte range the client asked for.
207Multi-StatusThe body holds separate status codes for several operations.
208Already ReportedMembers of this collection were already listed earlier in the same 207 response.
226IM UsedThe response is a delta applied to the current instance, not the full resource.
300Multiple ChoicesThe resource has several representations and the client should choose one.
301Moved PermanentlyThe resource has a new permanent URL, given in the Location header.
302FoundThe resource is temporarily at the URL in the Location header.
303See OtherThe result is at another URL, which the client should fetch with GET.
304Not ModifiedThe cached copy is still valid, so no body is sent.
305Use ProxyThe resource must be accessed through the proxy in the Location header.
306(Unused)Reserved; it was once used for Switch Proxy and is no longer used.
307Temporary RedirectThe resource is temporarily at another URL; repeat the request there with the same method and body.
308Permanent RedirectThe resource has moved permanently; repeat the request at the new URL with the same method and body.
400Bad RequestThe server can't process the request because it is malformed.
401UnauthorizedThe request has no valid credentials for this resource.
402Payment RequiredReserved for future use.
403ForbiddenThe server understood the request but refuses to allow it.
404Not FoundThe server has nothing at this URL.
405Method Not AllowedThe resource exists but doesn't support this HTTP method.
406Not AcceptableThe server can't produce a response in any format the Accept headers allow.
407Proxy Authentication RequiredThe client must authenticate with the proxy first.
408Request TimeoutThe server gave up waiting for the client to finish sending the request.
409ConflictThe request conflicts with the current state of the resource.
410GoneThe resource existed but has been removed permanently.
411Length RequiredThe server needs a Content-Length header.
412Precondition FailedA condition in the request headers, such as If-Match, is false.
413Content Too LargeThe request body is larger than the server accepts.
414URI Too LongThe URL is longer than the server accepts.
415Unsupported Media TypeThe server doesn't accept the body's format.
416Range Not SatisfiableThe requested byte range is outside the resource.
417Expectation FailedThe server can't meet the Expect header.
418I'm a teapotA joke code from RFC 2324, kept reserved as "(Unused)" because so much software already recognizes it.
421Misdirected RequestThe request reached a server that can't answer for this host.
422Unprocessable ContentThe request is well formed but its content fails validation.
423LockedThe resource is locked.
424Failed DependencyThe request failed because a request it depended on failed.
425Too EarlyThe server won't process a request that might be replayed.
426Upgrade RequiredThe client must switch to another protocol, named in the Upgrade header.
428Precondition RequiredThe server requires a conditional request, such as one with If-Match.
429Too Many RequestsThe client has sent too many requests in a given time and is being rate limited.
431Request Header Fields Too LargeThe headers, or one header, are too large.
451Unavailable For Legal ReasonsThe resource can't be served for legal reasons.
500Internal Server ErrorThe server hit an unexpected condition.
501Not ImplementedThe server doesn't support the functionality needed, such as the request method.
502Bad GatewayA gateway or proxy got an invalid response from the server behind it.
503Service UnavailableThe server can't handle the request right now.
504Gateway TimeoutA gateway or proxy didn't get a response from the server behind it in time.
505HTTP Version Not SupportedThe server doesn't support the HTTP version of the request.
506Variant Also NegotiatesContent negotiation is misconfigured on the server.
507Insufficient StorageThe server can't store what it needs to complete the request.
508Loop DetectedThe server found an infinite loop while processing the request.
510Not ExtendedThe request needs an HTTP extension the server requires.
511Network Authentication RequiredThe client must authenticate to get network access.
419Page ExpiredLaravelThe CSRF token is missing or expired.
420Enhance Your CalmTwitter (historical)The client is being rate limited.
444No Responsenginxnginx closed the connection without sending a response.
494Request Header Too Largenginxnginx's code for headers over its buffer limits.
495SSL Certificate ErrornginxThe client certificate failed verification.
496SSL Certificate RequirednginxA required client certificate wasn't sent.
497HTTP Request Sent to HTTPS PortnginxA plain HTTP request reached a port that expects TLS.
499Client Closed RequestnginxThe client closed the connection before nginx sent the response.
509Bandwidth Limit ExceededApache / cPanelThe site has used up its bandwidth allowance.
520Web Server Returned an Unknown ErrorCloudflareThe origin server returned something Cloudflare couldn't use.
521Web Server Is DownCloudflareThe origin server refused Cloudflare's connection.
522Connection Timed OutCloudflareCloudflare couldn't establish a TCP connection to the origin in time.
523Origin Is UnreachableCloudflareCloudflare can't reach the origin server.
524A Timeout OccurredCloudflareCloudflare connected to the origin, but it didn't respond in time.
525SSL Handshake FailedCloudflareThe TLS handshake between Cloudflare and the origin failed.
526Invalid SSL CertificateCloudflareCloudflare couldn't validate the origin's certificate.
530Origin DNS ErrorCloudflareCloudflare returns 530 together with a 1xxx error, most often 1016 (origin DNS error).

Select a code

Pick a code from the list to see when it is used, the specification that defines it and a command to try it. Use the arrow keys to move through the list.
64 registered codes · 17 unofficial

O que são códigos de status HTTP?

Toda resposta HTTP começa com um código de status de três dígitos que diz o que aconteceu com a requisição. O primeiro dígito indica a classe: 1xx é informativo, 2xx significa sucesso, 3xx significa redirecionamento, 4xx significa que a requisição estava errada e 5xx que o servidor falhou.

Os códigos são definidos na RFC 9110, HTTP Semantics, que substituiu a RFC 7231 em 2022, e em algumas outras RFCs, como a RFC 6585 para o 429 Too Many Requests. A IANA mantém o registro oficial. A RFC 9110 renomeou dois códigos: o 413 agora é Content Too Large (antes Payload Too Large) e o 422 é Unprocessable Content (antes Unprocessable Entity). Os números e o comportamento não mudaram.

Alguns códigos que você encontra não estão no registro. O nginx registra 499 quando um cliente fecha a conexão antes de a resposta ficar pronta, o Cloudflare envia de 520 a 526 quando não consegue uma resposta utilizável do servidor de origem, e o Laravel envia 419 quando o token CSRF de um formulário expirou. Eles aparecem separados, marcados como não oficiais.

O código de status é a primeira coisa que um teste de API deve conferir, porque o resto da resposta depende dele. Um 201 Created diz que um POST criou um recurso novo, um 404 que o recurso não existe e um 500 que o servidor falhou, caso em que o body pode ser uma página de erro em vez do JSON que você esperava.

Como usar esta ferramenta

  1. 1Navegue pela lista, agrupada de 1xx a 5xx com os códigos não oficiais no final, ou filtre com os botões de classe.
  2. 2Busque por número, nome ou sintoma, como 404, 5xx, redirect, timeout ou um nome antigo como Unprocessable Entity. Pressione / para ir à caixa de busca de qualquer ponto da página.
  3. 3Selecione um código, ou percorra a lista com as setas do teclado, para ver o que ele significa, quando aparece, a especificação que o define e códigos relacionados para comparar.
  4. 4Copie o comando curl em Try it para fazer o endpoint de status do testingapis.com devolver esse código, ou copie um link: /pt-br/tools/http-status/#429 abre o 429 direto.

Solução de problemas

Um 401 mesmo enviando um token
O token está expirado, malformado, foi enviado no header errado ou está sem o prefixo Bearer . O header de resposta WWW-Authenticate costuma dizer qual. Já um 403 significa que o token é válido, mas não tem permissão.
Um 415 para um body JSON
A requisição não tem o header Content-Type: application/json, então o servidor não trata o body como JSON. O -d do curl envia application/x-www-form-urlencoded, a menos que você defina o header.
Um POST vira GET depois de um redirecionamento
Os clientes seguem 301 e 302 repetindo a requisição como GET, sem o body. Servidores que precisam manter o método devem enviar 307 ou 308.
Um 502 ou 504 vindo de um load balancer
O proxy na frente da aplicação não recebeu uma resposta válida: 502 quando a aplicação caiu ou fechou a conexão, 504 quando ela demorou mais que o timeout do proxy. Os logs da própria aplicação mostram a causa.
499 nos logs do nginx
O cliente desistiu antes de a resposta ficar pronta: um usuário saiu da página, ou um cliente ou proxy intermediário estourou o timeout. Requisições lentas ao backend são a causa mais comum.

Perguntas frequentes

Qual a diferença entre 401 e 403?

401 Unauthorized significa que o servidor não sabe quem você é: as credenciais estão faltando, expiradas ou erradas. 403 Forbidden significa que ele sabe quem você é, mas essa identidade não tem permissão para fazer isso. Fazer login de novo pode resolver um 401, não um 403.

Uma API deve devolver 400 ou 422 para entrada inválida?

Os dois são usados. Uma convenção comum é 400 para uma requisição que o servidor nem consegue ler, como JSON malformado, e 422 para dados bem formados que quebram uma regra, como um campo obrigatório faltando ou um email inválido.

Qual a diferença entre 502, 503 e 504?

Os três costumam vir de um proxy ou load balancer na frente da aplicação. 502 Bad Gateway significa que ele recebeu uma resposta inválida do servidor por trás, 503 Service Unavailable que o serviço está sobrecarregado ou em manutenção, e 504 Gateway Timeout que o servidor por trás não respondeu a tempo.

Qual código de redirecionamento devo usar?

301 e 308 são permanentes, 302 e 307 temporários. 307 e 308 exigem que o cliente repita a requisição com o mesmo método e o mesmo body, enquanto os clientes costumam transformar um POST em GET depois de um 301 ou 302. Use 303 See Other para mandar o cliente a uma página de resultado depois de um POST.

418 I'm a teapot é um código de status de verdade?

Ele vem da RFC 2324, uma piada de 1º de abril de 1998 sobre controlar cafeteiras. A RFC 9110 lista o 418 como não usado, mas reservado, porque muito software já o reconhece. Ele não foi feito para erros reais.

Como testo como meu app lida com um código de status específico?

Chame um endpoint que devolve o código que você pedir. GET https://api.testingapis.com/api/status/503 responde com um 503 e os headers que esse status costuma trazer, como Retry-After. Qualquer código de 200 a 599 funciona.