Skip to main content

Multiple Methods

Handling GET, POST, PUT, DELETE

Actix 4.9+ 4 min read

# Multiple Methods

A single route path can respond differently depending on the HTTP method used (GET, POST, PUT, DELETE, etc.). This is fundamental for building RESTful APIs.

#Using Macros

You can use multiple macros or the #[routes] macro (from some community extensions) but typically, you define separate handlers for different methods and bind them to the same path.

code_blocksrust
use actix_web::{get, post, web, HttpResponse};

#[get("/users")]
async fn list_users() -> HttpResponse {
    HttpResponse::Ok().body("List users")
}

#[post("/users")]
async fn create_user() -> HttpResponse {
    HttpResponse::Created().body("User created")
}

#Using Manual Configuration

When configuring routes manually, you chain method guards using web::route().

code_blocksrust
use actix_web::{web, HttpResponse};

async fn handle_get() -> HttpResponse { HttpResponse::Ok().body("GET") }
async fn handle_post() -> HttpResponse { HttpResponse::Ok().body("POST") }

// In App configuration:
// .route("/resource", web::get().to(handle_get))
// .route("/resource", web::post().to(handle_post))

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{web, App, HttpServer, Responder, HttpResponse};
2
3async fn get_data() -> impl Responder {
4 HttpResponse::Ok().body("Got data")
5}
6
7async fn post_data() -> impl Responder {
8 HttpResponse::Created().body("Posted data")
9}
10
11#[actix_web::main]
12async fn main() -> std::io::Result<()> {
13 HttpServer::new(|| {
14 App::new()
15 .route("/data", web::get().to(get_data))
16 .route("/data", web::post().to(post_data))
17 })
18 .bind(("127.0.0.1", 8080))?
19 .run()
20 .await
21}
Was this page helpful?