Video lecture
Watch on YouTube(opens in a new tab)Sub topic 2
Methods: GET, POST, and Friends
Assume you can use a browser, recognize basic HTML, and run terminal commands. This chapter focuses on how a server interprets an HTTP request and builds a response.
HTTP methods
An HTTP method tells the server what the client wants to do.
GETretrieves a resource. AGETrequest should not change server data.POSTsends data to create a resource or trigger an action.PUTreplaces a resource.PATCHchanges part of a resource.DELETEremoves a resource.
A method does not guarantee behavior. The server must implement the behavior correctly.
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 28
username=ana&password=secretThe path identifies the operation, and the body carries input. Query parameters are commonly used with GET, while submitted data usually belongs in a POST body.
Reading status codes
A response status code summarizes the result.
| Range | Meaning | Example |
|---|---|---|
| 2xx | The request succeeded | `200 OK` |
| 3xx | The client should use another response or location | `304 Not Modified` |
| 4xx | The request is invalid or unauthorized | `404 Not Found` |
| 5xx | The server failed while handling it | `500 Internal Server Error` |
A 201 Created response often follows a successful POST. A 401 Unauthorized usually means authentication is required. A 403 Forbidden means the server understood the request but refuses it.
Headers and content types
Headers are name-value fields that describe a request or response. Content-Type identifies the body format, such as text/html, application/json, or image/png. Accept tells the server which response formats the client prefers. Content-Length gives the body size in bytes.
A header is metadata, not automatically trusted input. Servers still validate values such as authorization tokens and content types.
HTTPS and TLS
HTTPS is HTTP carried through TLS, a protocol that encrypts traffic and authenticates the server. TLS helps prevent network observers from reading or modifying requests. It does not make an unsafe server or malicious application safe.
What a server does with a request
A server typically:
- Parses the method, URL, headers, and body.
- Matches the method and path to a handler.
- Validates input and checks authentication.
- Performs application work.
- Returns a status code, headers, and body.
Exercise
Which status code should a server commonly return after creating a resource with POST?
Show answer
201 Created.