HTTP Methods (GET, POST, PUT, DELETE)
Mapping verbs to Actix Web macros.
Learning Objectives
- Use #[get], #[post], #[put], #[delete]
##Choosing the right verb
HTTP methods tell the server what the client wants to do with a resource. Picking the right one makes your API predictable, cacheable and easy for others to use.
#The core methods
- GET: read a resource. It must not change anything.
- POST: create a resource or trigger an action.
- PUT: replace a resource completely.
- PATCH: change part of a resource.
- DELETE: remove a resource.
#Safe and idempotent
Two properties explain a lot of design choices:
- Safe methods do not change server state (GET, HEAD, OPTIONS).
- Idempotent methods give the same result if repeated (GET, PUT, DELETE). Sending the same PUT twice leaves the resource in the same state. POST is not idempotent: two POSTs may create two records.
Idempotency matters because networks fail and clients retry.
#Methods in Actix Web
Use the attribute macros for the common verbs:
use actix_web::{delete, get, patch, post, put, web, HttpResponse, Responder};
#[get("/notes/{id}")]
async fn read(id: web::Path<u32>) -> impl Responder {
format!("read {}", id.into_inner())
}
#[post("/notes")]
async fn create() -> impl Responder {
HttpResponse::Created().body("created")
}
#[put("/notes/{id}")]
async fn replace(id: web::Path<u32>) -> impl Responder {
format!("replaced {}", id.into_inner())
}
#[patch("/notes/{id}")]
async fn update(id: web::Path<u32>) -> impl Responder {
format!("updated {}", id.into_inner())
}
#[delete("/notes/{id}")]
async fn remove(id: web::Path<u32>) -> impl Responder {
HttpResponse::NoContent().finish()
}#Several methods on one path
With the builder style you can attach different handlers to the same URL:
use actix_web::{web, App};
App::new().service(
web::resource("/notes")
.route(web::get().to(list_notes))
.route(web::post().to(create_note)),
);#Matching status codes
- GET success:
200. - POST creating something:
201with the new resource or aLocationheader. - DELETE success:
204. - Wrong method on a known path: Actix returns
405 Method Not Allowedwhen a resource exists but not for that method.
#REST naming
Use nouns in URLs (/notes) and let the method be the verb. Avoid paths like /getNotes or /deleteNote.
"What If?" Experiment
Learning by doing. Modify the code to see what happens.
See a 405 response.
Send a PUT to a path that only has GET and POST.
The server answers 405 Method Not Allowed.
Explanation: The path exists but not for that verb, which is exactly what 405 means.
Common Mistakes
Anticipate and avoid these frequent pitfalls when working with this concept.
Changing data in a GET handler
It seems convenient, but browsers and crawlers can call GET URLs freely.
Explanation: Use DELETE (or POST) for changes. GET must stay safe so prefetching and crawlers cannot destroy data.
Returning 200 for POST creation
200 is the default so it is easy to forget the more precise code.
Explanation: 201 tells clients a new resource was created, which many client libraries use.
Practical Exercise
Complete a notes resource
TaskRegister GET and POST on /notes using web::resource and two handlers.
Requirements
- GET /notes returns "list"
- POST /notes returns 201 with "created"
Need a hint?
Try solving the exercise in your local environment first. Once you have a solution, or if you get completely stuck, reveal the answer.
Real-World Application
Public APIs from payment providers to cloud platforms follow these conventions, so developers can guess how an endpoint behaves before reading the docs.
Key Takeaways
- GET reads, POST creates, PUT replaces, PATCH modifies, DELETE removes.
- GET is safe; GET, PUT and DELETE are idempotent; POST is not.
- Use #[get], #[post] and friends, or web::resource().route() for multi-method paths.
- Use nouns in paths and the method as the verb.
Finished reading?
Mark this lesson as done to track your progress and earn XP.