programmingconcepts

§ 8.4 · Tools

HTTP and APIs

HTTP is the request-and-response protocol of the web; an API is a set of requests a program agrees to answer.

HTTP is the protocol browsers and programs use to talk to web servers. A client sends a request with a method like GET or POST, a path, headers and an optional body; the server replies with a status code, headers and a body. An API is the set of requests a server promises to answer, usually exchanging JSON over HTTP.

Model
Request and response
Common methods
GET, POST, PUT, PATCH, DELETE
Status families
2xx ok, 3xx redirect, 4xx client error, 5xx server error
Stateless
Each request stands alone

A request, line by line

When you open a page, your browser sends text like this to the server:

GET /concepts/quicksort HTTP/1.1
Host: www.programming-concepts.com
Accept: text/html
  • The request line has three parts: the method (GET), the path (/concepts/quicksort) and the protocol version.
  • Each header is a Name: value pair with extra information: which site, which formats the client accepts, cookies, credentials.
  • A blank line ends the headers. A body, such as JSON for a POST, can follow it.

The server answers in the same shape:

HTTP/1.1 200 OK
Content-Type: text/html
Cache-Control: public, max-age=0, must-revalidate

<!doctype html>...

Parsing a request

The code below does what every web server does first: split the raw text into method, path, headers and body. It splits on the blank line, then on line breaks, then on the first : of each header. Header names are lowercased, because HTTP says they ignore case.

def parse_request(raw):
    """Split a raw HTTP/1.1 request into its parts."""
    head, _, body = raw.partition("\r\n\r\n")  # a blank line ends the headers
    request_line, *header_lines = head.split("\r\n")
    parts = request_line.split(" ")
    if len(parts) != 3:
        raise ValueError(f"bad request line: {request_line!r}")
    method, path, version = parts
    headers = {}
    for line in header_lines:
        name, _, value = line.partition(":")
        headers[name.strip().lower()] = value.strip()  # names ignore case
    return {"method": method, "path": path, "version": version, "headers": headers, "body": body}

Real servers also handle bodies that arrive in pieces, limits on header size, and malformed input from attackers, which is why you use a library in production. But underneath, it’s this.

Methods and status codes

Method Meaning Safe to repeat?
GET Read a resource Yes, and it shouldn’t change anything
POST Create something, or run an action No
PUT Replace a resource Yes
PATCH Change part of a resource Not guaranteed
DELETE Remove a resource Yes
Code Meaning
200 OK It worked.
201 Created A new resource exists; often returned by POST.
301 / 302 It moved; look at the Location header.
400 Bad Request The request itself is malformed.
401 / 403 Not signed in / signed in but not allowed.
404 Not Found No such resource.
500 / 503 The server failed / is overloaded or down.

What makes an API

An API (application programming interface) is a contract: “send this request, get this response”. A web API is usually a set of URLs and methods that exchange JSON:

Request Does
GET /users/42 Returns user 42 as JSON.
POST /users with a JSON body Creates a user, returns 201 and the new user.
DELETE /users/42 Deletes user 42, returns 204 No Content.

This style, nouns in the URL and verbs in the method, is called REST. Alternatives include GraphQL, where the client sends a query describing exactly the data it wants, and gRPC, which uses a binary format and generated client code.

HTTP is stateless: each request carries everything the server needs, such as a session cookie or an Authorization header. That’s what lets a site run on many servers at once.

Common mistakes

  1. Changing data with GET. Browsers, caches and crawlers send GET freely. A “delete” link that uses GET will eventually be clicked by a bot.
  2. Returning 200 for errors. Put the failure in the status code, so clients, caches and monitoring can see it.
  3. Trusting the client. Anything in a request, headers included, can be forged. Validate on the server.

Check yourself

Check yourself

A request returns 401. What should the client do?

Check yourself

Which method should an API use to create a new order?

Sources

  • RFC 9110, HTTP Semantics (2022), and RFC 9112, HTTP/1.1 (2022), rfc-editor.org.
  • Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, PhD dissertation, UC Irvine (2000), chapter 5, “REST.”
  • MDN Web Docs, “HTTP,” developer.mozilla.org.

Newsletter

One new concept each week, by email.

Signup opens soon.