Bookmarks
ReferenceBackendFrontendVerified

HTTP and REST

HTTP and REST — the protocol for exchanging data on the web and the API style built on top of it. The reference covers: methods, status codes, cache, CORS, REST APIs, OpenAPI, HTTP/2 and HTTP/3.

checked 1 Nov · next check 8 Nov · 57 min read

Sections
13
Reading
57 min
Languages
RU · UZ · EN
Written from
developer.mozilla.org/en-US/docs/Web/HTTP

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What HTTP and REST are and how they work

HTTP (Hypertext Transfer Protocol) is an application-layer request–response protocol: the client sends a request for the resource identified by a URI, and the server sends back a response whose status code reports the result. REST is an architectural style for APIs on top of HTTP: every resource has its own address, and a standard method sets the action.

HTTP keeps no state between requests: the meaning of each request follows from the request itself and does not depend on which requests have passed over the same connection before it. Requests from one client can therefore be spread across servers and sent through shared proxies. Sessions on top of HTTP are built on cookies: the server issues a cookie in the Set-Cookie header field, and the browser returns it in Cookie.

Who takes part in the exchange

ParticipantWhat it does
Client (user agent)Opens a connection and sends requests: a browser, curl, a mobile app, a crawler
Origin serverStores the resource and answers a request for it with an authoritative response
ProxyAn intermediary chosen by the client: forwards requests, may cache and filter
Gateway, reverse proxyLooks like the origin server to the client and passes requests to the servers behind it: balances load, caches
TunnelForwards bytes between two connections without reading them: this is how TLS passes through a proxy
CacheStores responses and answers repeated requests itself, shortening the path to the server

Message semantics are the same for every version of HTTP: the methods, status codes and header fields are defined by RFC 9110. The versions differ in how they carry the data. HTTP/1.1 and HTTP/2 run over TCP, and for https addresses inside TLS as well. HTTP/3 runs over QUIC — a transport on top of UDP with TLS 1.3 built in (details in the section “HTTP/1.1, HTTP/2 and HTTP/3”). Underneath them all lies IP.

For http:// addresses there is no TLS layer above TCP; in QUIC, TLS 1.3 is always built in.

What a REST API is

REST (Representational State Transfer) needs no commands of its own — the standard HTTP methods are enough: the resource is given by its address, the action by a method whose meaning is the same for every resource, the result by a status code. The meaning is set by the method, not by the words in the address: on a GET the client may expect that the resource will not change, whatever the URI says.

The HTTP standard sets no ready-made rules for REST, so every API describes its own resources — with documentation or an OpenAPI contract. How to choose addresses, status codes, pagination and versions — in the section “REST API design”.

How it differs from gRPC and GraphQL

AspectRESTgRPCGraphQL
Model and addressesResources, each with its own URIService methods (RPC), each with a fixed pathA graph of entities behind one address, usually /graphql
TransportHTTP of any versionHTTP/2, streams in both directions at onceMost often HTTP: POST, and GET for reads as well
Data formatAny media type, for example JSONUsually Protocol Buffers; clients are generated from the service descriptionJSON: a request document and variables; the response is data and errors
ErrorsHTTP status codes and problem detailsIts own set of error codesA 2xx status code when the response has data, even with errors in errors

Choose REST when an API has many different clients, browsers included: such an API relies on standard HTTP semantics that caches, proxies and any HTTP library understand. gRPC is designed for distributed systems with low latency and mobile clients: the service description sets the contract, and calls can stream in both directions; from a browser it works through gRPC-Web — details in the gRPC reference. GraphQL is the choice when a client works with a graph of related entities through a single address.

What to know in advance

  • TCP connections, ports, name resolution — the “TCP/IP and DNS” reference
  • What happens when a connection is made over https — the “TLS and PKI” reference
  • The JSON format: the request and response bodies in the reference’s examples are written in it

Section sources

the section is written from these pages

Cheat sheet: methods, status codes, headers

Methods, status codes, headers and curl commands for everyday use; each line is explained in its own section.

Methods

ValueWhat it means
GETRetrieve a representation of the resource; safe, the response is cacheable
HEADSame as GET, but without a response body
POSTSubmit data for processing, create a resource in a collection
PUTReplace the resource in full, or create it at a known URI
PATCHModify part of a resource with a patch document
DELETEDelete a resource
OPTIONSDiscover what the resource can do; this is how the browser makes a CORS preflight request
QUERYA safe request with a body: a search that does not fit in a URL

Status codes: success and redirects

ValueWhat it means
200 OKSuccess; the body content depends on the method
201 CreatedA resource has been created; its address is in Location
204 No ContentSuccess with no body
301 and 308The resource has moved permanently; 308 preserves the method and body
302 and 307The resource is temporarily at another address; 307 preserves the method and body
304 Not ModifiedThe client’s copy is still valid; the response has no body

Status codes: client errors

ValueWhat it means
400 Bad RequestThe request cannot be parsed: syntax, format, malformed JSON
401 UnauthorizedNo valid credentials; the authentication scheme is in WWW-Authenticate
403 ForbiddenThe request was understood, but access is forbidden
404 Not FoundThe resource does not exist, or the server does not reveal that it does
405 Method Not AllowedThe method is not supported; allowed methods are listed in Allow
409 ConflictThe request conflicts with the current state of the resource
412 Precondition FailedThe If-Match or If-Unmodified-Since condition was not met
415 Unsupported Media TypeThe server will not accept a body with this Content-Type
422 Unprocessable ContentThe format is correct, but the data fails validation
429 Too Many RequestsThe request limit has been exceeded; when to retry is in Retry-After

Status codes: server errors

ValueWhat it means
500 Internal Server ErrorAn unexpected error on the server
502 Bad GatewayA gateway or proxy received an invalid response from the next server
503 Service UnavailableThe server is temporarily overloaded or down for maintenance
504 Gateway TimeoutThe gateway did not receive a response from the next server in time

Request headers

ValueWhat it means
HostThe server name and port; mandatory in HTTP/1.1
AcceptWhich response media types are acceptable to the client
Content-TypeThe media type of the request body
AuthorizationCredentials, such as Bearer and a token
If-None-MatchA condition: send the body only if the ETag has changed
If-MatchA condition: modify the resource only if the ETag matches
OriginThe origin of the page that made the request (CORS)

Response headers

ValueWhat it means
Content-TypeThe media type of the response body
LocationThe address of the created resource or the redirect target
Cache-ControlWho may store the response and for how long
ETagA version of the representation for conditional requests
VaryWhich request headers affected the response
Retry-AfterWhen to retry the request: seconds or a date
Access-Control-Allow-OriginWhich origin the browser may expose the response to
Set-CookieStore a cookie in the browser

Diagnostics

TaskCommand
Show the connection, request and responsecurl -v https://api.example.com/items/42
Response headers only (HEAD)curl -I https://api.example.com/items/42
Headers and body of the responsecurl -i https://api.example.com/items/42
Send JSON with the POST methodcurl --json '{"name":"notebook"}' https://api.example.com/items
A different methodcurl -X DELETE https://api.example.com/items/42
Pass a tokencurl -H "Authorization: Bearer $TOKEN" https://api.example.com/me
Status code and HTTP versioncurl -s -o /dev/null -w '%{http_code} %{http_version}\n' https://api.example.com/
Check HTTP/2 and HTTP/3curl -I --http2 https://example.com, curl -I --http3 https://example.com
Follow redirectscurl -L https://example.com/old

Section sources

the section is written from these pages

Messages: request and response

An HTTP message consists of a start line, header fields, a blank line and an optional body. In a request, the start line carries the method, the target and the version (GET /items/42 HTTP/1.1); in a response, the version, the status code and the reason phrase (HTTP/1.1 200 OK).

This is what a message looks like in HTTP/1.1, where it is sent as text. In HTTP/2 and HTTP/3 the same parts travel in binary frames, and the start line is replaced by the pseudo-header fields :method, :path, :scheme, :authority and :status. What the parts mean does not depend on the version, so messages are parsed as HTTP/1.1 — that is also how curl -v shows them.

The blank line (CRLF) separates the headers from the body; without it the recipient cannot tell where the headers end.
httprequest
GET /items/42 HTTP/1.1Host: api.example.comAccept: application/json
httpresponse
HTTP/1.1 200 OKContent-Type: application/jsonContent-Length: 46ETag: "v7" {"id": 42, "name": "notebook", "price": 12000}

Start line

The request line is the method, the request target and the version separated by single spaces. The method is case-sensitive: get and GET are different methods. The target is almost always written in origin-form, as a path with a query string, and the server name is carried in Host. A client sends a full URL as the target to a proxy, the host:port form only in CONNECT, and the asterisk only in OPTIONS *.

The status line is the version, a three-digit code and an optional reason phrase. Rely on the code alone: intermediaries can replace, translate or lose the reason phrase when forwarding a message over a different version of HTTP.

Header fields

A header field is a name, a colon and a value: Accept: application/json. The name is case-insensitive: content-type and Content-Type are the same field. A space between the name and the colon is forbidden; a server must respond to such a request with 400 Bad Request. The recipient ignores fields it does not know, and a proxy forwards them along, which is why new headers appear without a change of protocol version.

If a field value is a list, repeated lines are equivalent to a single line with the values separated by commas: Accept-Encoding: gzip and Accept-Encoding: br mean gzip, br. The exception is Set-Cookie: each cookie arrives on its own line, and the lines must not be merged. In HTTP/1.1 the Host field is mandatory and there must be exactly one; otherwise the server responds with 400.

The body and its length

The body (content) is described by the representation headers: Content-Type sets the media type (for text, the character encoding as well, charset), Content-Length sets the size in bytes. If the size is not known in advance, HTTP/1.1 sends the body in chunks: Transfer-Encoding: chunked. Each chunk is preceded by its length in hexadecimal, and a chunk of zero length ends the message.

httpchunked response
HTTP/1.1 200 OKContent-Type: text/plainTransfer-Encoding: chunked 5Hello7, world0

Content-Length and Transfer-Encoding are never sent together: if both arrive, Transfer-Encoding determines the length, and the server closes the connection after responding. When a proxy and the server disagree about the length, that is the road to request smuggling. Responses to HEAD and responses with the codes 1xx, 204 and 304 have no body.

Content negotiation

The client lists what it finds acceptable in the Accept (media types), Accept-Language (languages) and Accept-Encoding (compression) headers. The server uses them to pick one of the resource’s representations — this is content negotiation. The q parameter sets the weight of a preference.

httprequest
GET /items/42 HTTP/1.1Host: api.example.comAccept: application/jsonAccept-Language: uz, ru;q=0.8, en;q=0.5Accept-Encoding: br, gzip

A server that has chosen the response based on these headers lists them in Vary, for example Vary: Accept-Language; the cache then keeps a separate copy for each language. If none of the representations fits, the server responds with 406 Not Acceptable or serves a default variant.

Media types in an API

Media typeWhat it carries
application/jsonData in JSON format
application/problem+jsonAn error description; details in the “Status codes” section
application/x-www-form-urlencodedHTML form fields: name=value&...
multipart/form-dataA form with files: the body consists of several parts
text/plainPlain text

Cookies

A cookie is a “name=value” pair that the server sends in the Set-Cookie header and the browser returns in the Cookie header on subsequent requests to the same host. This is how sessions are built on top of stateless HTTP. The Secure, HttpOnly and SameSite attributes and the __Host- prefix are described in the “HTTP security” section.

httpserver response
HTTP/1.1 200 OKSet-Cookie: __Host-sid=8f2c1e; Secure; HttpOnly; Path=/Set-Cookie: lang=uz; Path=/
httpnext request
GET /profile HTTP/1.1Host: app.example.comCookie: __Host-sid=8f2c1e; lang=uz

Section sources

the section is written from these pages

HTTP methods

The method is the first word of the request and its main source of meaning: GET reads a resource, PUT replaces it, DELETE deletes it, POST submits data for processing. Choose the method to match the operation: caching, retrying after a failure and the behaviour of intermediaries all depend on it.

A safe method only reads: the client neither asks for nor expects changes on the server. An idempotent method can be repeated: several identical requests produce the same result as one. Every safe method is idempotent, but the converse is not true: DELETE changes state, yet repeating it adds nothing.

MethodSafeIdempotentCacheable response
GETyesyesyes
HEADyesyesyes
QUERYyesyesyes; the request body is part of the cache key
OPTIONSyesyesno
POSTnonoonly with an explicit freshness lifetime and Content-Location
PUTnoyesno
PATCHnonosame as POST
DELETEnoyesno

A request body makes sense with POST, PUT, PATCH and QUERY. With GET, HEAD and DELETE the body has no defined meaning: some servers and intermediaries reject such requests, seeing them as an attempt at request smuggling.

GET and HEAD

GET asks for the current representation of a resource, and its response can be cached. HEAD returns the same header fields without a body: it is used to check whether a resource exists, how large it is and when it changed, without downloading the content. A general-purpose server must support both methods.

bashin the terminal
curl -i https://api.example.com/items/42# only the headers: curl sends HEADcurl -I https://api.example.com/items/42

POST, PUT and PATCH

POST asks the resource to process the data in its own way: create an entry in a collection, run an action, accept a form. The server reports the created resource with the 201 Created status code and its address in Location. PUT replaces the state of the resource at a URI known to the client in full: if there was no resource, the server creates it and responds 201; if there was one, it responds 200 or 204.

bashin the terminal
# create: the address of the new resource arrives in Locationcurl -i --json '{"name":"notebook","price":12000}' \  https://api.example.com/items# replace the resource in fullcurl -X PUT --json @item.json \  https://api.example.com/items/42

The --json flag (curl 7.82 and later) sends the body with the POST method and sets the Content-Type and Accept header fields to application/json; -X changes the method.

PATCH (RFC 5789) changes part of a resource: the body is a change document whose format is set by Content-Type, and the server applies the changes atomically — all of them or none. JSON has two standard formats. JSON Merge Patch (application/merge-patch+json, RFC 7396) carries the new values of fields, and null removes a field. JSON Patch (application/json-patch+json, RFC 6902) is a list of add, remove, replace, move, copy and test operations.

bashin the terminal
curl -X PATCH \  -H 'Content-Type: application/merge-patch+json' \  -d '{"price":11500,"discount":null}' \  https://api.example.com/items/42

PATCH is not idempotent: an operation such as “add an item to a list” will run twice if repeated. To keep two clients from overwriting each other’s changes, send PATCH and PUT with an If-Match condition and the last known ETag. If the resource has already changed, the server responds 412 Precondition Failed.

DELETE and OPTIONS

DELETE removes the association between a URI and a resource. A successful response is 204 No Content, 200 OK with a description of the result, or 202 Accepted if the deletion has only been queued. OPTIONS asks what capabilities a resource has; browsers send it as a CORS preflight request — see the “CORS” section for details.

bashin the terminal
curl -i -X DELETE https://api.example.com/items/42curl -i -X OPTIONS https://api.example.com/items/42

Retrying after a failure

If the connection drops before a response arrives, the client may repeat an idempotent request on its own: the result will be the same even if the first request was already executed. POST and PATCH must not be retried this way — a second POST may create a second order. A proxy does not retry such requests by itself.

To make a POST safe to retry, the API gives the client a way to find out whether the request has been executed. For example, the API accepts a unique operation key and does not run the operation a second time with the same key. The name of such a header field and how long the keys are kept are up to the API.

QUERY: a safe request with a body

QUERY (RFC 10008) carries the search conditions in the body, like POST, but, like GET, it is safe and idempotent: it can be repeated and cached. It is needed when the conditions are too large for a URL or should not be left in logs, where URIs end up more often than bodies. Without Content-Type the server must reject QUERY, and it lists the supported request formats in the Accept-Query header field.

bashin the terminal
curl -i -X QUERY \  -H 'Content-Type: application/json' \  -d '{"category":"pens","maxPrice":20000}' \  https://api.example.com/items

Section sources

the section is written from these pages

Status codes

A status code is three digits, the first of which sets the class of the result: 2xx means success, 3xx redirection, 4xx a client error, 5xx a server error. Return the most specific standard code, and convey the error details in the body in the problem details format.

A client must understand at least the class of a code: an unfamiliar 471 will be treated as a 400. The 1xx codes are interim, such as 100 Continue: a final response always follows them. The IANA registry maintains the full list of codes with links to the RFCs where each one is defined; new codes are registered only through the IETF process, so do not invent your own.

Success: 2xx

CodeWhen to return
200 OKThe request has been completed; the body contains the resource (GET) or the result of the action (POST)
201 CreatedA new resource has been created; its address is in Location
202 AcceptedThe request has been accepted, but processing is not finished; the body says where to track the status
204 No ContentDone, and there is no body: a good choice for responses to PUT, PATCH and DELETE
httpResponse to POST
HTTP/1.1 201 CreatedLocation: /items/43Content-Type: application/json {"id": 43, "name": "notebook", "price": 12000}

Redirection: 3xx

CodeWhat it meansMethod on following
301 Moved PermanentlyThe resource has moved for goodPOST may become GET
308 Permanent RedirectThe resource has moved for goodPreserved along with the body
302 FoundThe resource is temporarily at a different addressPOST may become GET
307 Temporary RedirectThe resource is temporarily at a different addressPreserved along with the body
303 See OtherThe result is located at a different addressBecomes GET, the body is dropped

The new address arrives in Location. For redirections in an API, choose 307 and 308: with them the client will repeat the same method with the same body. 304 Not Modified is not a redirect but a response to a conditional request: the client’s copy is still valid, and the response has no body.

Client errors: 4xx

CodeWhen to return
400 Bad RequestThe request cannot be parsed: invalid syntax, malformed JSON
401 UnauthorizedNo valid credentials; the response must include WWW-Authenticate
403 ForbiddenThe request is understood, but the server refuses to carry it out
404 Not FoundThe resource does not exist, or the server does not want to reveal that it does
405 Method Not AllowedThe resource does not support the method; the response must include Allow
409 ConflictThe request conflicts with the current state of the resource, such as an outdated version
412 Precondition FailedThe If-Match or If-Unmodified-Since condition was not met
415 Unsupported Media TypeThe format of the body (Content-Type) is not supported
422 Unprocessable ContentThe format is valid, but the data fails validation
429 Too Many RequestsThe request limit has been exceeded; the wait is in Retry-After

401 and 403 are confused more often than any other pair. 401 means “I don’t know who you are”: there are no credentials or they are invalid, and the server says how to authenticate in WWW-Authenticate. 403 means “I know who you are, but you can’t”: repeating the request with the same credentials will not help. If the very existence of the resource is a secret, 404 can be returned instead of 403.

httpNo token
HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer realm="api"

The 429 code reports that the request limit has been exceeded, and the Retry-After header says when to retry: Retry-After: 120 means in 2 minutes; a date can be given instead of seconds. The same header is also appropriate on 503.

Server errors: 5xx

CodeWhat happenedWho is at fault
500 Internal Server ErrorAn unforeseen errorThe server that responded
502 Bad GatewayThe gateway or proxy received an invalid responseThe next server in the chain
503 Service UnavailableTemporary overload or maintenanceThe server that responded; when to retry — in Retry-After
504 Gateway TimeoutThe gateway did not receive the response in timeThe next server in the chain

Error body: problem details

So that a client can parse an error programmatically, return it in the problem details format (RFC 9457) with the media type application/problem+json. The standard fields:

  • type — a URI identifying the type of problem; if the field is absent, the type is about:blank
  • title — a short description of the type of problem
  • status — the same code as on the status line
  • detail — an explanation of this particular occurrence
  • instance — the URI of the occurrence itself

Extra fields are defined by the problem type, and a client must ignore any fields it does not know.

httpValidation error
HTTP/1.1 422 Unprocessable ContentContent-Type: application/problem+json {  "type": "https://api.example.com/problems/validation",  "title": "Request data is not valid",  "status": 422,  "errors": [    {"detail": "must be positive", "pointer": "#/price"}  ]}

In detail, write what will help the client fix the request, not debugging information: stack traces and internal names in a response show an attacker how the server is built. Generic situations such as a ban on writing are better expressed with a single status code, without a custom problem type.

Section sources

the section is written from these pages

Caching

The HTTP cache stores responses and serves them on repeat requests without going to the server, while the response is fresh. When the freshness lifetime has run out, the cache asks the server with a conditional request whether the resource has changed, and on 304 Not Modified keeps using its own copy.

Caches are private — the browser cache of a single user — and shared: a reverse proxy, a CDN, an organisation’s proxy. A shared cache serves one response to many users, so personal responses must not be stored in it. What is stored is governed by the server with the Cache-Control header.

The freshness lifetime is set by the max-age directive in seconds, and the cache counts the age of a response from the moment it was created on the server and reports it in the Age header. While the age is within the lifetime, the server is not needed at all. When the copy is stale, the cache revalidates it with the ETag validator and receives either 304 without a body or a new version.

While the copy is fresh, the server receives no requests; after a revalidation that ends in 304 the copy is fresh again for 60 seconds.
  1. The client requests /items/42; there is no copy in the cache, and the cache passes the request on to the server.
  2. The server responds 200 with ETag: "v7" and Cache-Control: max-age=60; the cache stores the response and hands it to the client.
  3. After 25 seconds the copy is still fresh: the cache answers itself and adds Age: 25.
  4. After 90 seconds the copy is stale: the cache sends the server a conditional request with If-None-Match: "v7".
  5. The resource has not changed, and the server responds 304 Not Modified without a body; the cache updates the lifetime and hands the stored copy to the client.

Cache-Control directives

DirectiveWhat it does
max-age=60The response is fresh for 60 seconds
s-maxage=300The lifetime for shared caches only; replaces max-age for them
no-cacheStoring is allowed, but check with the server before every use
no-storeStore neither the request nor the response
privateOnly a private cache may store it, a shared one may not
publicMay be stored even when it is a response to a request with Authorization
must-revalidateA stale copy must not be served without revalidation; with no connection to the server — respond 504
immutableWhile the response is fresh it will not change: do not revalidate, not even on a page reload
stale-while-revalidate=86400For a day after going stale, serve the copy while revalidating it in the background

If a response has neither Cache-Control nor Expires, the cache may set a lifetime itself — heuristically, usually about 10% of the time elapsed since Last-Modified; this may be done with 200, 301, 404 and other codes that RFC 9110 allows caching by default. To make the behaviour predictable, set Cache-Control explicitly in every response. With max-age in place, the Expires header is ignored.

Revalidation: ETag and Last-Modified

A validator is a version label of a representation. ETag is an opaque string that the server changes together with the resource; the cache sends it back in If-None-Match. Last-Modified is the date of modification, sent back in If-Modified-Since. If a request carries both conditions, If-None-Match decides. On a match the server responds 304 without a body; on a mismatch, 200 with the new version.

bashin the terminal
# save the ETag from the response to a filecurl -s --etag-save etag.txt -o item.json \  https://api.example.com/items/42# repeat with If-None-Match: on a match 304 arrivescurl -i --etag-compare etag.txt \  https://api.example.com/items/42
textexample output
HTTP/1.1 304 Not ModifiedETag: "v7"Cache-Control: max-age=60...

The same validators protect against lost updates: PUT or PATCH with If-Match: "v7" goes through only if the resource has not changed; otherwise the server responds 412 (the “HTTP methods” section).

Vary and the cache key

The cache looks up a stored response by the key — the method and the URI. If the response depended on request headers, the server lists them in Vary, and they become part of the key: with Vary: Accept-Language the Russian and Uzbek versions are stored separately. Vary: * does not allow serving a copy without the server, and Vary: User-Agent almost rules out reuse: this header has too many variants.

Which Cache-Control to choose for an API

API data that may change at any moment: store it, but revalidate every time. A repeat request costs a cheap 304 response instead of the full body.

httpAPI data
HTTP/1.1 200 OKCache-Control: no-cacheETag: "v7"

Personal and secret data — the profile, the balance, tokens: forbid storing it in any cache.

httppersonal data
HTTP/1.1 200 OKCache-Control: no-store

Unsafe methods are always passed on to the server by the cache, and a successful response to PUT, PATCH, POST or DELETE invalidates the stored copies of that URI. The cache strategy for static files with a hash in the file name and for HTML is described in the “Web performance” reference, section “Caching for speed”. The cache directives of Nginx — in the “Nginx” reference.

Section sources

the section is written from these pages

CORS

CORS (Cross-Origin Resource Sharing) is a mechanism of headers by which a server allows the browser to hand a response to a script on a page from a different origin. Without such permission the browser does not show the response to the page’s code. curl and server-to-server requests are unaffected by CORS: only the browser observes it.

An origin is a scheme, a host and a port. By default the browser follows the same-origin policy: fetch() on a page reads responses from its own origin only. For a page at https://app.example.com:

Request URLSame origin?Why
https://app.example.com/itemsYesScheme, host and port match
https://api.example.org/itemsNoA different host
http://app.example.com/itemsNoA different scheme
https://app.example.com:8443/itemsNoA different port

Simple requests

The browser sends some requests straight away, without a preliminary check. A request counts as simple if:

  • The method is GET, HEAD or POST
  • The script sets only the Accept, Accept-Language, Content-Language, Content-Type and Range headers, and Range with a single range
  • The body type is application/x-www-form-urlencoded, multipart/form-data or text/plain

An ordinary HTML form could send such a request too. The browser hands the response to the script only if the response carries a matching Access-Control-Allow-Origin.

Preflight requests

For every other request the browser first asks for permission: it sends an OPTIONS request with the Origin, Access-Control-Request-Method and Access-Control-Request-Headers headers. The actual request goes out only if the server’s response permits the origin, the method and the headers alike.

Blue arrows — the preflight request and the response to it; the red block — the outcome when step 3 grants no permission.
  1. The script on the https://app.example.com page calls fetch() with the PUT method and a JSON body.
  2. The browser sends an OPTIONS request to api.example.org with Origin, the method and the headers of the future request.
  3. The server responds 204 and lists the origin, methods and headers it permits.
  4. The browser sends the actual PUT request, again with Origin.
  5. The server responds with Access-Control-Allow-Origin, and the browser hands the response to the script. Without permission the PUT is not sent, and fetch() fails.
httppreflight request
OPTIONS /items/42 HTTP/1.1Host: api.example.orgOrigin: https://app.example.comAccess-Control-Request-Method: PUTAccess-Control-Request-Headers: content-type
httpthe server’s response
HTTP/1.1 204 No ContentAccess-Control-Allow-Origin: https://app.example.comAccess-Control-Allow-Methods: GET, PUT, PATCH, DELETEAccess-Control-Allow-Headers: Content-TypeAccess-Control-Max-Age: 600Vary: Origin

CORS response headers

HeaderWhat it permits
Access-Control-Allow-OriginThe origin to which the browser will hand the response: a single origin or *
Access-Control-Allow-MethodsMethods of the actual request (in the response to OPTIONS)
Access-Control-Allow-HeadersHeaders of the actual request (in the response to OPTIONS)
Access-Control-Allow-CredentialsThe value true: requests with cookies may be sent, and their responses handed to the script
Access-Control-Max-AgeHow many seconds the browser remembers the response to OPTIONS; 5 by default
Access-Control-Expose-HeadersWhich further response headers the script can see

If the server fills Access-Control-Allow-Origin with the request’s origin chosen from a list of permitted ones, add Vary: Origin. The cache will then store a copy of the response for each origin separately.

Cookies and credentials

By default fetch() to another origin sends no cookies or HTTP authentication data. To make it send them, the credentials: "include" option is needed. The server must reply with Access-Control-Allow-Credentials: true and name the origin explicitly: the asterisk in Access-Control-Allow-* and Access-Control-Expose-Headers does not work for such requests. The preflight request itself never carries cookies.

javascriptthe page’s code
const res = await fetch("https://api.example.org/me", {  credentials: "include",});
httpthe server’s response
HTTP/1.1 200 OKAccess-Control-Allow-Origin: https://app.example.comAccess-Control-Allow-Credentials: trueVary: OriginContent-Type: application/json

JavaScript will not learn the reason for the refusal: fetch() merely fails, and the browser writes the details only to the developer console. Common messages and their causes are covered in the “Common errors and troubleshooting” section; configuring CORS in frameworks is covered in the FastAPI and Django references.

Section sources

the section is written from these pages

REST API design

A REST API is built around resources: each resource has its own URI, and the action on it is set by the HTTP method, not by a word in the address. GET /users/42/orders reads a user’s orders, POST /users/42/orders creates a new order — the address is the same, the meaning is different.

The main rule of BCP 56 (RFC 9205) is not to redefine the general elements of HTTP. Methods, status codes and standard headers are already understood by proxies, caches and client libraries; put what is specific to your application in the body and in your own headers. Colloquially, “REST API” refers to any HTTP API that is called with ordinary web libraries, even if it does not follow all the constraints of REST.

Resources, addresses and operations

OperationRequestSuccessful response
List ordersGET /orders?status=paid200 and an array
One orderGET /orders/1001200; no order — 404
Create an orderPOST /orders201 and Location: /orders/1001
Replace an orderPUT /orders/1001200 or 204; created — 201
Modify part of an orderPATCH /orders/1001200 or 204
Delete an orderDELETE /orders/1001204; deletion queued — 202

HTTP does not prescribe the structure of addresses; the API owner chooses it. It is convenient to name collections with nouns and to show ownership through nesting: /users/42/orders. Verbs in the path are unnecessary, and with GET they are dangerous: any robot, prefetcher or link checker will open the link /orders/1001?do=delete, and the data will be gone. The resource owner must forbid such actions through safe methods. When an action does not come down to creating, reading, replacing or deleting, model it as a separate resource: POST /orders/1001/cancellation.

Give the client links instead of making it assemble URLs from a template: this way the server can change the structure of addresses and distribute resources across machines without breaking clients.

Example: creating a resource

The client sends data to the orders collection and takes the address of the new order from Location.

bashin the terminal
curl -i --json '{"itemId":42,"quantity":2}' \  https://api.example.com/users/7/orders
textexample output
HTTP/1.1 201 CreatedLocation: /users/7/orders/1001Content-Type: application/json {"id": 1001, "itemId": 42, "quantity": 2, "status": "new"}

Filters, sorting and pages

Filters and sorting go in the query string: GET /orders?status=paid&sort=-created. HTTP does not prescribe the names of these parameters — the API chooses limit and offset, a page number or an opaque cursor and documents them. The standardised part is links to neighbouring pages in the Link header (RFC 8288). The relation types next, prev, first and last come from the IANA registry, and the client follows the links instead of assembling URLs itself.

httplist page
HTTP/1.1 200 OKContent-Type: application/jsonLink: </orders?status=paid&cursor=c2Vq>; rel="next"Link: </orders?status=paid>; rel="first"

If the search criteria do not fit in a URL, use the QUERY method (the “HTTP methods” section). Searching through POST also works, but it loses caching and the ability to link to the result, so keep the GET option as well.

How to report errors

For each error, take the most specific standard code; when in doubt, the general 400 or 500. Pass the differences between errors in the body, for example in the problem details format from the “Status codes” section. Do not tie every application error to a separate code: the codes will soon run out. Moreover, 4xx and 5xx also come from proxies, CDNs and client libraries, and a client may mistake such a response for one from the application.

Versions and compatibility

A change is compatible when old clients can ignore it: new resources, new optional fields and parameters. Removing or renaming a field, changing its type or meaning, a new required parameter all break old clients — these are incompatible changes.

RFC 9205 suggests expressing an incompatible change through a new relation type, a new media type or a new header — old clients then keep working as before. A version prefix in the path such as /v1 is common practice for an API with a single deployment; RFC 9205 considers it inappropriate only in IETF specifications.

What not to do

  • Do not require a minimum HTTP version and do not cap the maximum: the connection can be handled by proxies and CDNs.
  • Do not invent your own methods and status codes: only registered ones are allowed.
  • Do not attach meaning to the reason phrase on the status line: HTTP/2 does not have one at all.
  • Do not rely on the order in which individual requests are processed: if it matters, send the second request when the final response to the first has begun to arrive.
  • Do not tie the requests of one connection to each other: HTTP is stateless.
  • Do not return resource metadata through OPTIONS: such a response cannot be linked to, and it is not cached. A separate resource with a link to it in Link is better.

Section sources

the section is written from these pages

OpenAPI

OpenAPI is a machine-readable format for describing an HTTP API in JSON or YAML: paths and operations, parameters, request and response bodies, data schemas and authentication methods. From a single OpenAPI Description, tools build documentation and client and server code, validate data and spin up mock servers.

The openapi field is the version of the specification the document is written against, and info.version is the version of the document itself: it is neither the specification version nor the API version. Patch releases within one branch only correct the text of the specification, and tools do not tell, for example, 3.2.0 from 3.2.1. Field names are case-sensitive.

yamlopenapi.yaml
openapi: 3.2.0info:  title: Items API  version: 1.4.0servers:  - url: https://api.example.compaths:  /items/{itemId}:    get:      operationId: getItem      parameters:        - name: itemId          in: path          required: true          schema: {type: integer}      responses:        "200":          description: The item          content:            application/json:              schema:                $ref: "#/components/schemas/Item"components:  schemas:    Item:      type: object      required: [id, name]      properties:        id: {type: integer}        name: {type: string}        price: {type: integer, minimum: 0}  securitySchemes:    bearerAuth:      type: http      scheme: bearer      bearerFormat: JWTsecurity:  - bearerAuth: []

Root fields

FieldWhat it contains
openapiRequired: the OpenAPI specification version
infoRequired: the document’s title and version, contacts, licence
serversBase URLs of the API; without the field — /
pathsPaths and the operations on them
componentsReusable schemas, parameters, responses and security schemes
securityWhich security schemes apply to the whole API
webhooksRequests the API itself sends to subscribers
tagsGroups of operations for documentation

Besides the required fields, the document must contain at least one of paths, components or webhooks.

Operations, parameters and bodies

A key in paths is a path template with parameters in curly braces: /items/{itemId}. Inside are operations keyed by the get, put, post, delete, options, head, patch and trace methods and, since 3.2, query; other methods are described in additionalOperations. An operation has an operationId unique across the whole description, plus parameters, a requestBody and responses.

A parameter is defined by its name and its location in: path, query, header, cookie or, since 3.2, querystring — the whole query string as one value. A path parameter is always required (required: true). The request body is described in requestBody.content by media type; for GET and DELETE it is best left out — bodies of such requests have no defined meaning. Responses are listed by quoted status codes ("200"), by a range ("4XX") or through default for everything else.

yamlopenapi.yaml, fragment
paths:  /items:    post:      operationId: createItem      requestBody:        required: true        content:          application/json:            schema:              $ref: "#/components/schemas/Item"      responses:        "201":          description: Created          headers:            Location:              schema: {type: string}        "4XX":          description: Client error          content:            application/problem+json:              schema: {type: object}

Data schemas and $ref

The Schema Object is a superset of JSON Schema Draft 2020-12: the same type, properties, required, enum, minimum and oneOf and other keywords, plus a few OpenAPI fields. This has been the case since OpenAPI 3.1; descriptions carried over from 3.0 change on the way — for example, binary data is described with contentMediaType, not format: binary.

$ref substitutes an object by URI: #/components/schemas/Item from this very document; Item.yaml or common.yaml#/Item from another file. Keep shared schemas, parameters and responses in components and reference them: then one and the same entity is described in one place.

Security schemes

typeWhat it describesKey fields
apiKeyA key in a header, the query string or a cookiename, in
httpAn HTTP authentication scheme in Authorizationscheme (bearer, basic), bearerFormat
mutualTLSA client TLS certificate—
oauth2OAuth 2.0 flowsflows, since 3.2 — oauth2MetadataUrl
openIdConnectSettings from OpenID Connect DiscoveryopenIdConnectUrl

Schemes are declared in components.securitySchemes and applied with the security field — to the whole API or to an operation. The items of the security list are alternatives: satisfying one is enough, and an empty object {} makes authentication optional. The OAuth 2.0 and OpenID Connect protocols are covered in the “OAuth and OIDC” reference.

What is new in 3.2

The 3.2 branch is backwards compatible with 3.1: to move over, changing the value of openapi is enough. What is new:

  • The QUERY method (the query field) and any other methods through additionalOperations
  • The in: querystring parameter — the whole query string as one value
  • Sequential and streaming data: Server-Sent Events, JSON Lines, application/json-seq; the item schema — itemSchema
  • Tag hierarchy: the parent, kind and summary fields
  • OAuth 2.0 Device Authorization, the oauth2MetadataUrl field and the deprecated flag on security schemes
  • The $self field with the document’s own URI, and name on servers

How a framework builds the description itself — in the FastAPI and Django references; how to check responses against it in tests — in the “API testing” reference, section “Schemas: JSON Schema and OpenAPI”.

Section sources

the section is written from these pages

HTTP/1.1, HTTP/2 and HTTP/3

HTTP/1.1, HTTP/2 and HTTP/3 carry the same semantics: methods, status codes and header fields. What differs is how the data is carried — as text over TCP, as binary frames in one TCP connection, or as independent QUIC streams over UDP. Application code hardly depends on the version: it is the client and the server that agree on it.

AspectHTTP/1.1HTTP/2HTTP/3
FormatTextBinary framesBinary frames
TransportTCPTCPQUIC over UDP
Parallel requestsSeveral connectionsStreams in one connectionQUIC streams in one connection
Header compressionNoneHPACKQPACK
A lost packet delaysIts own connectionEvery stream of the connectionOnly its own stream
How it is chosenBy default; over TLS — ALPN http/1.1ALPN h2 in the TLS handshakeAlt-Svc and ALPN h3
SpecificationRFC 9112RFC 9113RFC 9114

The main difference is what happens when a packet is lost. HTTP/1.1 handles the requests of a connection one after another, so clients open several connections. HTTP/2 interleaves the frames of all requests in one TCP connection, but TCP delivers bytes in strict order, and a single lost packet delays every stream. In HTTP/3 the streams are independent at the QUIC level: a loss delays only the stream whose data is missing.

The letters are request frames A, B, C and D; a red cell — a lost packet, a yellow bar — waiting for the retransmission.

HTTP/1.1: persistent connections

By default the connection is persistent: after a response the next request is sent over the same connection, until one of the sides sends Connection: close. For this, the length of every message must be known — Content-Length or chunked. Pipelining allows several requests to be sent in a row, but the responses arrive in strictly the same order, and one slow response delays the rest.

HTTP/2: frames and streams

The unit of exchange in HTTP/2 is a frame: HEADERS carries the header fields, DATA — the body. Each request–response pair travels in its own stream, and the frames of different streams are interleaved in one TCP connection — this is multiplexing. The header fields are compressed by HPACK, and the start line is replaced by the pseudo-header fields :method, :scheme, :authority, :path and :status.

For https the version is chosen in the TLS handshake through the ALPN extension with the identifier h2. Without TLS, HTTP/2 works only if the client knows in advance that the server supports it (prior knowledge); upgrading through Upgrade: h2c is deprecated in RFC 9113.

HTTP/3: QUIC over UDP

HTTP/3 carries the same semantics over QUIC — a transport on top of UDP with TLS 1.3 built in, its own streams and flow control for each of them. Each request–response pair occupies its own QUIC stream. The header fields are compressed by QPACK: HPACK relies on in-order delivery, which QUIC does not guarantee between streams. HTTP/3 is used with https addresses: direct connection over HTTP/3 for http is not provided for.

A client usually learns about HTTP/3 support from the Alt-Svc header field in a response over HTTP/1.1 or HTTP/2, for example Alt-Svc: h3=":443". If UDP is blocked and the QUIC connection fails to establish, the client falls back to the versions over TCP.

How to check the version

bashin the terminal
# HTTP/2: for https curl negotiates it on its owncurl -sI --http2 https://example.com# HTTP/3 with fallback to HTTP/2 and HTTP/1.1curl -sI --http3 https://example.com# the version number onlycurl -s -o /dev/null -w '{http_version}\n' \  https://example.com
textexample output
HTTP/2 200content-type: text/html; charset=utf-8...

HTTP/2 frames are used as the transport for its own calls by gRPC — more in the gRPC reference. The TLS handshake is described in the TLS and PKI reference, the “Handshake” section.

Section sources

the section is written from these pages

HTTP security

The main threats at the HTTP level are traffic interception and tampering without TLS, cookie and token theft, script injection (XSS) and embedding a page in someone else’s frame (clickjacking). Protection comes from HTTPS, cookie attributes, response headers and narrowly scoped CORS permissions; TLS settings themselves are covered in the TLS and PKI reference.

HTTPS only and HSTS

Serve everything over https only: without TLS an intermediary sees and alters headers, cookies and the message content (body), and credentials travel as plain text. Answer http requests with a permanent 301 redirect to the https address.

The Strict-Transport-Security header (HSTS) tells the browser to reach the host over https only for max-age seconds. The browser rewrites http:// addresses itself and will not let a certificate error be skipped. Send HSTS only in responses over https — a browser ignores it when it arrives over http.

httpan https response
Strict-Transport-Security: max-age=63072000; includeSubDomains

The preload directive is needed to get the domain onto the HSTS list built into browsers: then even the first visit is protected. For that, max-age must be at least 31,536,000 seconds (a year) and includeSubDomains is required.

Cookies

Issue session cookies with the attributes:

  • Secure — the cookie is sent only over https
  • HttpOnly — the cookie is unavailable to JavaScript, which reduces the damage XSS can do
  • SameSite=Lax or Strict — the cookie is not sent with most cross-site requests

The Domain attribute exposes the cookie to all subdomains; without it, the cookie is sent only to the host that issued it. The __Host- prefix in the name makes the browser accept the cookie only if it has Secure, Path=/ and no Domain: such a cookie is tied to a single host.

httpwhat not to do
Set-Cookie: sid=8f2c1e; Domain=example.com
httpthe right way
Set-Cookie: __Host-sid=8f2c1e; Secure; HttpOnly; SameSite=Lax; Path=/

Cookies are ambient authority: the browser attaches them to a request even when someone else’s site triggered the request with a form or a redirect. A cookie alone is therefore not enough for actions that change data: protection against cross-site request forgery (CSRF) is needed. Keep secrets on the server, and put only a random session identifier in the cookie.

Response protection headers

HeaderValueWhat it is for
X-Content-Type-OptionsnosniffThe browser does not guess the type from the content but follows Content-Type
Content-Security-Policyframe-ancestors 'none' and other directivesRestricts script origins and embedding the page in frames
X-Frame-OptionsDENYFrames banned for browsers without CSP frame-ancestors
Referrer-Policystrict-origin-when-cross-originOther sites receive only the origin, without the path or query parameters
Cache-Controlno-storeSensitive responses are not kept in caches
Server, X-Powered-ByRemove or make genericDo not reveal the software and its versions

Tokens and secrets in URLs

Send tokens in the Authorization header, not in the query string. URIs are shown on screen, stored in bookmarks and in the logs of servers and proxies, and the Referer header carries them to other sites. Send credentials only over a secure connection.

bashwhat not to do
curl "https://api.example.com/orders?access_token=$TOKEN"
bashthe right way
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/orders

The format and verification of Bearer and JWT tokens and the OAuth 2.0 flows are covered in the OAuth and OIDC reference.

CORS: do not reflect any Origin

A dangerous CORS misconfiguration is copying the request’s Origin into Access-Control-Allow-Origin together with Access-Control-Allow-Credentials: true. Any site open in the user’s browser can then read API responses with the user’s cookies attached. Allow only origins from an explicit list.

httpwhat not to do
Access-Control-Allow-Origin: https://evil.exampleAccess-Control-Allow-Credentials: true
pythonthe right way
ALLOWED_ORIGINS = {"https://app.example.com"}  def cors_headers(origin):    # unknown origins get no permission    if origin not in ALLOWED_ORIGINS:        return {"Vary": "Origin"}    return {        "Access-Control-Allow-Origin": origin,        "Access-Control-Allow-Credentials": "true",        "Vary": "Origin",    }

Request data and intermediaries

Request data cannot be trusted: the method, path, headers such as Host and Referer, and the message content (body) all come from the client. SQL injection or a command can hide in any of them, so do not substitute them into database queries or the command line without validation. A shared cache on a proxy is vulnerable to cache poisoning. If the proxy and the server interpret the length and the headers of a message differently, request smuggling becomes possible. Keep proxies and servers up to date and do not accept messages with ambiguous Content-Length and Transfer-Encoding.

Web application risks as a whole are covered in the OWASP Top 10 reference; recommendations on TLS settings are in the TLS and PKI reference, the section “Security”.

Section sources

the section is written from these pages

Common errors and diagnostics

Start diagnostics with curl -v: it shows, in order, name resolution, the connection, the TLS handshake, the request as sent, the status line and the response headers. An error before the status line is the network or TLS; after it, HTTP and the application.

The order of checks

  1. The name resolves: no Could not resolve host error
  2. The connection is established: no Failed to connect error after the Trying line
  3. TLS succeeded: a protocol is agreed (ALPN: server accepted h2), the certificate is verified
  4. The status line: which code, and who answered — the application or the proxy in front of it
  5. Headers: Content-Type, Location, Cache-Control, Age, WWW-Authenticate
  6. The body: the error text, often in the problem details format
bashin the terminal
curl -v https://api.example.com/items/42
textexample output
* Host api.example.com:443 was resolved.* IPv4: 192.0.2.10*   Trying 192.0.2.10:443...* ALPN: curl offers h2,http/1.1...* ALPN: server accepted h2...*  SSL certificate verify ok....> GET /items/42 HTTP/2> Host: api.example.com> Accept: */*>< HTTP/2 200< content-type: application/json< etag: "v7"< cache-control: max-age=60...

Lines with * show the progress of the connection, > the request as sent, < the received status line and headers.

Could not resolve host

Cause: the name does not resolve to an address — a typo, a missing DNS record or a resolver that is not working; curl exits with code 6. Substitute the address by hand: if the request goes through that way, the problem is in DNS — the order of checks is described in the “TCP/IP and DNS” reference.

bashin the terminal
curl -v --resolve api.example.com:443:192.0.2.10 \  https://api.example.com/

Failed to connect to host

Cause: nothing is listening on that address and port, or a firewall cuts the connection off. curl exits with code 7, and if the wait times out — 28 (Operation timeout). Limit the connection time so as not to wait minutes on end, and check that the service is running and the port is open.

bashin the terminal
curl -v --connect-timeout 5 https://api.example.com/

Peer certificate cannot be authenticated with known CA certificates

Cause: the server’s certificate fails verification — it has expired, was issued for a different name, or the server does not send the intermediate certificate; curl exits with code 60. Fix the certificate or the chain on the server (the “TLS and PKI” reference). The -k (--insecure) flag switches verification off and hides the problem — do not leave it in scripts or production.

Too many redirects

Cause: the redirection rules lead in a circle, often across several servers, each of which sees only its own part of the loop. curl -L stops after 50 hops with code 47, and Firefox reports Firefox has detected that the server is redirecting the request for this address in a way that will never terminate. Look through the chain of Location headers and remove the rule that sends the client back to an address it has already visited.

bashin the terminal
curl -sIL --max-redirs 5 https://example.com/old

A related problem: POST turns into GET after a redirect — with 301 and 302 clients behave this way. If the API is meant to keep the method and the body, answer with 308 or 307. In curl, do not combine -X POST with -L: the method from -X goes into every request of the chain regardless of the redirect status code. From curl 8.16 there is --follow instead of -L: it keeps the method only for 307 and 308, as HTTP requires.

401 Unauthorized and 403 Forbidden

The cause of 401: the Authorization header is missing, the token has expired or the scheme is not the one the server expects — WWW-Authenticate shows which one. The cause of 403: the credentials were accepted, but the permissions for the action are not enough, and repeating the request with the same credentials will not help. On a redirect to another host curl -L does not pass the credentials on.

bashin the terminal
curl -i -H "Authorization: Bearer $TOKEN" https://api.example.com/me

415 Unsupported Media Type

Cause: the body arrived with a Content-Type other than the one the server expects. A common case: curl -d sets application/x-www-form-urlencoded by default, while the API takes JSON. If the type is right but the JSON is broken, the server answers 400; if the data fail validation — 422.

bashin the terminal
curl -v -d '{"name":"notebook"}' https://api.example.com/items
textexample output
> POST /items HTTP/2> Content-Type: application/x-www-form-urlencoded...< HTTP/2 415
bashthe right way
curl -i --json '{"name":"notebook"}' https://api.example.com/items

502 Bad Gateway and 504 Gateway Timeout

Cause: the answer came not from the application server but from the proxy or gateway in front of it. 502 means an invalid response arrived from the application, 504 that there was no response in time: the application has crashed, is unreachable, or takes longer than the proxy’s timeout. Compare the response through the proxy with a direct response from the application on the server, then look at the logs of the proxy and the application; proxy timeouts are described in the Nginx reference.

bashon the server, bypassing the proxy
curl -i http://127.0.0.1:8000/items/42

The response does not change after an update

Cause: the response comes from a cache — in the browser, on a CDN or in a reverse proxy. Look at the headers: Age is how many seconds the response has already been sitting in a cache along the way, Cache-Control — how long it will be kept. For API data send Cache-Control: no-cache with an ETag (the “Caching” section).

bashin the terminal
curl -sI https://api.example.com/items/42
textexample output
HTTP/2 200cache-control: max-age=3600age: 1926...

Reason: CORS header 'Access-Control-Allow-Origin' missing

Cause: the response carries no permission for the origin of the page, and the browser does not give the response to the script, although curl opens the same address fine: only the browser checks CORS. Firefox shows the message in the console; with credentials and * in the response it reports Reason: Credential is not supported if the CORS header 'Access-Control-Allow-Origin' is '*'. Repeat the preflight request with curl and check the Access-Control-Allow-* headers.

bashin the terminal
curl -i -X OPTIONS \  -H "Origin: https://app.example.com" \  -H "Access-Control-Request-Method: PUT" \  https://api.example.org/items/42
  • Add the origin of the page to the list of allowed origins on the server
  • Respond to OPTIONS with a 2xx status and Access-Control-Allow-Methods and Access-Control-Allow-Headers
  • For requests with cookies name the origin explicitly and add Access-Control-Allow-Credentials: true

Section sources

the section is written from these pages

Standards and their status

HTTP semantics are defined by RFC 9110, an Internet Standard (STD 97) from June 2022. Together with RFC 9111 and RFC 9112 it replaced RFC 7230–7235, which in 2014 had replaced RFC 2616. The format for describing an API is set by OpenAPI; the latest revision is 3.2.1, dated 10 September 2026.

DocumentWhat it definesStatusReplaced or updated by
RFC 9110Semantics: methods, status codes, header fields, the http and https URIsInternet Standard (STD 97)—
RFC 9111CachingInternet Standard (STD 98)—
RFC 9112HTTP/1.1 message syntax and connectionsInternet Standard (STD 99)Updated by RFC 9931 (March 2026)
RFC 9113HTTP/2Proposed Standard—
RFC 9114HTTP/3Proposed Standard—
RFC 10008The QUERY method and the Accept-Query header fieldProposed Standard—
RFC 5789The PATCH methodProposed Standard—
RFC 9457Problem details: the error format for HTTP APIsProposed Standard—
RFC 6265Cookies: the Set-Cookie and Cookie header fieldsProposed Standard—
RFC 9205 (BCP 56)Building APIs and protocols on top of HTTPBest Current Practice—
RFC 8288Links and the Link header fieldProposed Standard—
Fetch Standard (WHATWG)Requests from the browser and CORSLiving StandardUpdated continuously
OpenAPI 3.2.1The format for describing HTTP APIsCurrent revision—

What changed in recent revisions

  • September 2026, OpenAPI 3.2.1 — fixes to the text of the 3.2 branch; the 3.2 branch itself (September 2025) added QUERY, tag hierarchy and streaming media types.
  • June 2026, RFC 10008 — the QUERY method: a safe and idempotent request with a body.
  • March 2026, RFC 9931 added to RFC 9112 the requirements for CONNECT in HTTP/1.1: a client that opens a tunnel for an untrusted program waits for a 2xx response before forwarding that program’s data, or sends Connection: close, and a proxy that rejects CONNECT closes the connection. This closes one of the request smuggling paths.
  • August 2023, RFC 9457 replaced RFC 7807: a registry of common problem types and rules for several errors in one response.
  • June 2022, RFC 9110–9114: HTTP was split into semantics, caching and one document per version; semantics, caching and HTTP/1.1 became Internet Standards.

Obsolete documents still cited

  • RFC 2616 (1999) — HTTP/1.1 in a single document; replaced by RFC 7230–7235 in 2014.
  • RFC 7230–7235 (2014) — replaced by RFC 9110, 9111 and 9112 in 2022.
  • RFC 7540 (2015) — the first revision of HTTP/2; replaced by RFC 9113 in 2022.
  • RFC 7807 (2016) — the first revision of problem details; replaced by RFC 9457 in 2023.

A link to an old RFC in a framework’s documentation or in an article is a reason to check the wording against the current document: section numbers and some requirements have changed. The current status of any RFC is shown on its page at rfc-editor.org: the “Obsoleted by” and “Updated by” lines.

How to read a standard

Requirements in RFCs are marked with the key words of RFC 2119, and they carry the special meaning only when written in capitals (RFC 8174). MUST and MUST NOT are a firm requirement or prohibition. SHOULD and SHOULD NOT are a recommendation one may depart from only after weighing the consequences. MAY is truly optional. The requirements of RFC 9110 are addressed to roles — sender, recipient, client, server, proxy, cache — so first check whom the sentence applies to.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “HTTP and REST” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61