2.10. HTTP Methods
Table of Contents
Overview of HTTP Methods
When a client talks to a server using HTTP, it always sends a request method that says what kind of action it wants to perform on a resource.
Common methods include:
| Method | Typical purpose |
|---|---|
| GET | Read / fetch a resource |
| POST | Create a new resource or trigger an action |
| PUT | Replace a resource |
| PATCH | Partially update a resource |
| DELETE | Delete a resource |
| HEAD | Get headers only, no body |
| OPTIONS | Ask which methods / features are allowed |
Every HTTP request line looks like:
METHOD /path HTTP/1.1For example:
GET /users HTTP/1.1
Host: example.comThe method is part of the HTTP specification, so servers and clients can agree on what each method is supposed to mean.
Important rule
The HTTP method defines the intent of the request. Backend routes and APIs must be designed so that:
- URLs identify what you are working with (the resource).
- Methods describe what you want to do with that resource.
You will use methods constantly when building backend APIs, especially REST APIs later in the course.
Safe, Idempotent, and Cacheable Methods
HTTP methods are not only names. They also have semantics that help with caching, retries, and proxies.
Safe methods
A method is safe if it is meant only to read data, not to change anything on the server.
Standard safe methods:
- GET
- HEAD
- OPTIONS
Safe does not mean there is no effect at all. The server can still log the request or update a counter. It means the method should not create, update, or delete resources in a way that matters to the user.
Example of correct use:
GET /products/123This should not create a new product, change its price, or delete it.
Example of incorrect use:
GET /delete-accountIf this endpoint actually deletes the account, it breaks the idea of safety. Tools like browsers and crawlers might follow a link and trigger deletion by accident.
Idempotent methods
A method is idempotent if making the same call multiple times in a row has the same effect as making it once.
Formally, if $f$ is the effect of a request, then:
$$
f(x) = f(f(x))
$$
Examples:
- GET is idempotent
RepeatingGET /users/1does not change the user. - PUT is idempotent
RepeatingPUT /users/1 { "name": "Alice" }sets the name to "Alice" every time. After the first request, the state stays the same. - DELETE is considered idempotent
Deleting the same resource multiple times results in "the resource does not exist". After the first delete, further deletes do not change anything more.
Methods that are idempotent by design:
| Method | Idempotent? | Safe? |
|---|---|---|
| GET | Yes | Yes |
| HEAD | Yes | Yes |
| OPTIONS | Yes | Yes |
| PUT | Yes | No |
| DELETE | Yes | No |
| POST | No | No |
| PATCH | Not guaranteed | No |
Example of idempotent behavior:
DELETE /posts/10- First time: deletes the post.
- Second time: nothing more to delete, but still "post 10 is gone".
From the point of view of system state, one call or ten calls give the same end result: "no post 10".
Cacheable methods
Some methods are considered cacheable. Intermediaries like browsers and proxies can store responses and reuse them, based on headers.
Common cacheable methods:
- GET
- HEAD
POST responses can also be cached if certain headers are present, but this is not common for typical API design.
Example of cacheable usage:
GET /productsIf the server includes headers like:
Cache-Control: max-age=60then a browser can reuse the cached response for 60 seconds without asking the server again.
As a backend developer, it is important to:
- Use GET only for reading, so it is safe to cache.
- Use POST, PUT, PATCH, DELETE for changing data, and usually not cache them.
GET
Purpose
GET is used to retrieve information. It does not change data on the server.
Properties:
- Safe: should not modify resources.
- Idempotent: repeating a GET does not change state.
- Cacheable: often cached by browsers and proxies.
Examples
Fetch a list of users:
GET /users HTTP/1.1
Host: api.example.comFetch a single user:
GET /users/42 HTTP/1.1
Host: api.example.comWith query parameters (filtering, searching):
GET /users?role=admin&page=2 HTTP/1.1
Host: api.example.comIn a browser, when you type a URL like:
https://example.com/productsthe browser sends:
GET /products HTTP/1.1
Host: example.comGET and request body
By the HTTP standard, GET requests should not have a body. Some clients allow it, but many servers and tools ignore it. For APIs, always put GET parameters in the URL or query string, not in the body.
Bad pattern:
GET /search
Body: { "q": "phone" }Better:
GET /search?q=phonePOST
Purpose
POST is used to:
- Create a new resource.
- Submit data to a server.
- Trigger a server-side action that may not directly map to "create one resource".
Properties:
- Not safe: it changes state.
- Not idempotent: repeating a POST can create multiple items.
- Usually not cached.
Examples: creating resources
Create a new user:
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"name": "Alice",
"email": "alice@example.com"
}The server might reply:
HTTP/1.1 201 Created
Location: /users/123
Content-Type: application/json
{
"id": 123,
"name": "Alice",
"email": "alice@example.com"
}The important part is that POST /users does not say what the ID will be. The server creates it.
Examples: actions
Sometimes an operation does not fit "create exactly one resource". Then POST is still used.
Examples:
POST /loginto log in a user.POST /password-resetto start password reset.POST /orders/123/payto pay for order 123.POST /reports/generateto generate a report.
In these cases, POST means "perform this action using the submitted data".
Non-idempotent behavior
Consider:
POST /orders
Body: { "product_id": 10, "quantity": 1 }If you send it twice by mistake, you may get:
- Order 101 created
- Order 102 created
So sending the same POST more than once usually changes the state more than once.
PUT
Purpose
PUT is used to replace an entire resource at a specific URL.
Properties:
- Not safe: it modifies data.
- Idempotent: doing the same PUT many times yields the same final state.
- Usually not cached.
The key idea is that the client sends the full representation of the resource and says: "make the resource at this URL exactly like this".
Examples
Replace a user:
PUT /users/123 HTTP/1.1
Content-Type: application/json
{
"id": 123,
"name": "Alice Smith",
"email": "alice@example.com",
"role": "admin"
}If the server already has a user 123, it will update it to match this JSON exactly. If some field is missing from the body, the server may set it to a default or null, depending on implementation.
Calling the same PUT again with the same data does nothing new, because the user is already in that state.
Creating or not creating on PUT
Different APIs handle this differently:
- Some treat
PUT /users/123as "update existing user 123, fail if it does not exist". - Others treat it as "create user 123 if it does not exist, or update it if it does".
The HTTP specification allows both, but you should be consistent in your own API.
PUT vs POST
A simple way to remember the difference:
- POST /users
"Create a new user, the server chooses the ID." - PUT /users/123
"Create or replace the user that must be at/users/123."
Another mental model:
| Question | POST | PUT |
|---|---|---|
| Who chooses the resource URL | Server | Client |
| Typical use | Create, actions | Replace a specific resource |
| Idempotent | No | Yes |
PATCH
Purpose
PATCH is used to partially update a resource, not replace it completely.
Properties:
- Not safe: it modifies data.
- Not guaranteed idempotent, but often implemented in an idempotent way.
- Usually not cached.
PATCH is useful when you only want to send the fields that change.
Examples: partial update
Suppose a user has this full data:
{
"id": 123,
"name": "Alice Smith",
"email": "alice@example.com",
"role": "user",
"active": true
}You want to change only the role:
PATCH /users/123 HTTP/1.1
Content-Type: application/json
{
"role": "admin"
}A reasonable server behavior:
- Update only
role. - Leave
name,email,activeunchanged.
Repeat the same PATCH:
PATCH /users/123
{ "role": "admin" }The second time, the user is already admin, so state does not change. In this case, it behaves idempotently, even though the spec does not require it.
JSON Patch and other formats
There is a specific format called JSON Patch defined in RFC 6902. It uses an array of operations like "replace this path" or "add to that path".
Example JSON Patch body:
[
{ "op": "replace", "path": "/role", "value": "admin" },
{ "op": "add", "path": "/tags/-", "value": "vip" }
]Then:
PATCH /users/123 HTTP/1.1
Content-Type: application/json-patch+json
[ ... ]Not all APIs use JSON Patch. Many use a simpler "partial object" style, where you send only the fields to update.
DELETE
Purpose
DELETE is used to remove a resource.
Properties:
- Not safe: it modifies data.
- Idempotent: repeating DELETE has the same final effect, the resource is gone.
- Usually not cached.
Examples
Delete a specific user:
DELETE /users/123 HTTP/1.1
Host: api.example.comServer responses can vary:
204 No Contentif deleted successfully with no body.200 OKwith some body describing what was deleted.404 Not Foundif the resource does not exist.
Some APIs always return 204 even if it was already deleted, to keep DELETE idempotent.
Soft delete vs hard delete
Internally, servers often do not physically remove data. They can:
- Mark it as deleted (soft delete), for example set
deleted_attimestamp. - Actually remove it from the database (hard delete).
From the HTTP perspective, both are "delete". The difference is an internal implementation detail.
HEAD
Purpose
HEAD is like GET, but the server returns only headers, no body.
Properties:
- Safe.
- Idempotent.
- Cacheable like GET.
This is useful to check:
- If a resource exists.
- Metadata, such as
Content-Length,Content-Type, or caching headers. - Whether a resource has changed, using ETag or Last-Modified.
Examples
Check if a file exists:
HEAD /files/report.pdf HTTP/1.1
Host: example.comServer response:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 582131
ETag: "abc123"No body is sent, so the response is smaller and faster.
Use cases:
- A download manager can use HEAD to check file size before downloading.
- A client can check if a page changed by comparing ETag values.
OPTIONS
Purpose
OPTIONS asks the server: "What can I do with this resource or URL?"
Properties:
- Safe.
- Idempotent.
- Can be used by browsers and clients to discover supported methods and features.
Examples
General options for the server:
OPTIONS * HTTP/1.1
Host: example.comOptions for a specific resource:
OPTIONS /users/123 HTTP/1.1
Host: api.example.comThe server might respond:
HTTP/1.1 204 No Content
Allow: GET, PUT, PATCH, DELETE, OPTIONS
The Allow header lists the supported methods.
OPTIONS and CORS
In browsers, OPTIONS is heavily used with CORS (Cross Origin Resource Sharing). When a web page sends certain types of cross origin requests, the browser may send a preflight request:
OPTIONS /api/data HTTP/1.1
Origin: https://myapp.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-TypeThe server then replies with headers that tell the browser whether the real request is allowed.
You will see and configure this often in backend work for APIs used by browsers.
Method Semantics and Good API Design
In backend development, you often need to choose which method to use for an endpoint. Here are some guiding principles.
Use the correct method for what you do
Typical REST style mapping:
| Action | Path example | Method |
|---|---|---|
| List all items | /users | GET |
| Get one item | /users/123 | GET |
| Create a new item | /users | POST |
| Replace an item completely | /users/123 | PUT |
| Partially update an item | /users/123 | PATCH |
| Delete an item | /users/123 | DELETE |
Avoid patterns like:
GET /create-user
GET /delete-user?id=123They break the semantics of GET and can cause security and caching issues.
Think about idempotency and retries
Network requests can fail. Clients, proxies, or load balancers may retry requests.
- Idempotent methods (GET, PUT, DELETE) are safer to retry automatically.
- Non idempotent methods (POST) must be handled more carefully.
Example problem:
- Client sends
POST /ordersto create an order. - It times out and retries.
- The server had already created the order, and now creates a second one.
Solutions (later in the course) include idempotency keys, but for now remember:
Key idea
Non idempotent methods like POST can create side effects multiple times if retried. Idempotent methods like PUT and DELETE are designed so that multiple retries lead to the same final state.
Document supported methods
Your API should:
- Clearly document which methods are supported for each path.
- Use proper HTTP status codes for unsupported methods, such as
405 Method Not Allowed. - Ideally return an
Allowheader listing the supported methods.
Example:
HTTP/1.1 405 Method Not Allowed
Allow: GET, POSTSummary
- HTTP methods describe what action the client wants to perform.
- Safe methods (GET, HEAD, OPTIONS) do not change data and are safe to call repeatedly for reading.
- Idempotent methods (GET, PUT, DELETE, HEAD, OPTIONS) can be called many times with the same effect on server state.
- GET is for reading, POST for creating or actions, PUT for full replacement, PATCH for partial updates, DELETE for removal.
- HEAD returns headers only, OPTIONS describes capabilities.
- Using correct methods and respecting their semantics helps with:
- Caching
- Retries
- Security
- Clean API design
You will apply these concepts directly when you start building APIs and backend routes in later chapters.
Views: 8
KAHIBARO