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: valuepair 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}// Split a raw HTTP/1.1 request into its parts.
function parseRequest(raw) {
const split = raw.indexOf('\r\n\r\n'); // a blank line ends the headers
const head = split === -1 ? raw : raw.slice(0, split);
const body = split === -1 ? '' : raw.slice(split + 4);
const [requestLine, ...headerLines] = head.split('\r\n');
const parts = requestLine.split(' ');
if (parts.length !== 3) throw new Error(`bad request line: ${JSON.stringify(requestLine)}`);
const [method, path, version] = parts;
const headers = {};
for (const line of headerLines) {
const colon = line.indexOf(':');
const name = colon === -1 ? line : line.slice(0, colon);
const value = colon === -1 ? '' : line.slice(colon + 1);
headers[name.trim().toLowerCase()] = value.trim(); // names ignore case
}
return { method, path, version, headers, body };
}import (
"fmt"
"strings"
)
type Request struct {
Method, Path, Version string
Headers map[string]string
Body string
}
// parseRequest splits a raw HTTP/1.1 request into its parts.
func parseRequest(raw string) (Request, error) {
head, body, _ := strings.Cut(raw, "\r\n\r\n") // a blank line ends the headers
lines := strings.Split(head, "\r\n")
parts := strings.Split(lines[0], " ")
if len(parts) != 3 {
return Request{}, fmt.Errorf("bad request line: %q", lines[0])
}
req := Request{Method: parts[0], Path: parts[1], Version: parts[2], Headers: map[string]string{}, Body: body}
for _, line := range lines[1:] {
name, value, _ := strings.Cut(line, ":")
req.Headers[strings.ToLower(strings.TrimSpace(name))] = strings.TrimSpace(value) // names ignore case
}
return req, nil
}use std::collections::HashMap;
struct Request {
method: String,
path: String,
version: String,
headers: HashMap<String, String>,
body: String,
}
// Split a raw HTTP/1.1 request into its parts.
fn parse_request(raw: &str) -> Result<Request, String> {
let (head, body) = raw.split_once("\r\n\r\n").unwrap_or((raw, "")); // a blank line ends the headers
let mut lines = head.split("\r\n");
let request_line = lines.next().unwrap_or("");
let parts: Vec<&str> = request_line.split(' ').collect();
if parts.len() != 3 {
return Err(format!("bad request line: {:?}", request_line));
}
let mut headers = HashMap::new();
for line in lines {
let (name, value) = line.split_once(':').unwrap_or((line, ""));
headers.insert(name.trim().to_lowercase(), value.trim().to_string()); // names ignore case
}
Ok(Request {
method: parts[0].to_string(),
path: parts[1].to_string(),
version: parts[2].to_string(),
headers,
body: body.to_string(),
})
}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
- Changing data with
GET. Browsers, caches and crawlers sendGETfreely. A “delete” link that usesGETwill eventually be clicked by a bot. - Returning
200for errors. Put the failure in the status code, so clients, caches and monitoring can see it. - 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?
401 Unauthorized means the request lacked valid credentials. A 5xx code would point at the server instead.
Check yourself
Which method should an API use to create a new order?
POST creates resources or triggers actions. GET must not change anything, because it can be repeated or prefetched freely.
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.
Finished this page?
Your list