# Requests and responses

# URL anatomy

https://example.com:8443/articles/42?format=full#comments
\____/   \_________/ \__/ \_________/ \________/ \_______/
 scheme      host     port    path       query    fragment

The scheme selects a protocol, the host identifies a server, and the optional port selects a service. The path identifies a resource; the query carries parameters to the server. A fragment is handled by the browser and is normally not sent in the HTTP request.

# HTTP request

GET /articles/42 HTTP/1.1
Host: example.com
Accept: application/json

A request contains a method, target, protocol version, headers, and optionally a body. A form using method="post" sends its named controls in the request body (or in the URL for GET).

# HTTP response

HTTP/1.1 200 OK
Content-Type: application/json

{"id":42,"title":"HTTP basics"}

A response contains a status code, headers, and optionally a body. Content-Type tells the client how to interpret the body; Accept tells the server which response formats the client prefers.

# Methods and status codes

Method Typical meaning Common response
GET Read a resource 200 OK, 404 Not Found
POST Create a resource or trigger an action 201 Created, 400 Bad Request
PUT Replace a resource 200 OK, 204 No Content
PATCH Partially update a resource 200 OK, 400 Bad Request
DELETE Remove a resource 204 No Content, 404 Not Found
HEAD Get response metadata without a body 200 OK
OPTIONS Ask which operations are supported 204 No Content

GET, HEAD, and OPTIONS are safe: they should not change the resource. PUT, DELETE, and usually PATCH are idempotent when repeated requests have the same intended result; POST commonly creates a new result each time.

Status-code groups communicate the result:

  • 2xx means success: 200, 201, 204.
  • 3xx means redirection or cache reuse: 301, 302, 304.
  • 4xx means the request cannot be fulfilled as sent: 400, 401, 403, 404, 409, 429.
  • 5xx means a server or upstream service failed: 500, 503.

# Headers and bodies

JSON is a common body format, but it is not required by HTTP:

POST /articles HTTP/1.1
Content-Type: application/json
Accept: application/json

{"title":"A new article"}

Authorization communicates credentials or a token conceptually; it does not make an API secure by itself. Cache headers such as Cache-Control, ETag, and If-None-Match help avoid transferring unchanged data.

MDN: HTTP request methods (opens new window) MDN: HTTP response status codes (opens new window)