# Request and Response
In an HTTP server, the core operation is receiving a Request and returning a Response. Actix Web simplifies this by letting you define handler functions that take various parameters (Extractors) and return types that implement the Responder trait.
##HTTP Requests
The raw HttpRequest object gives you access to the entire incoming request: headers, URI, method, and more. However, you rarely need to interact with it directly because Actix Web's Extractors handle most common needs (like parsing JSON or extracting path parameters).
If you do need it:
use actix_web::{HttpRequest, Responder};
async fn inspect_req(req: HttpRequest) -> impl Responder {
let method = req.method();
let uri = req.uri();
format!("You made a {} request to {}", method, uri)
}##HTTP Responses
A handler must return something that implements Responder. The Responder trait is implemented for many standard types, including String, &str, HttpResponse, and actix_web::Result.
When you return a string, Actix Web automatically creates a 200 OK HTTP response with the string as the body, and sets the Content-Type header to text/plain.
To have more control, you construct an HttpResponse:
use actix_web::{HttpResponse, Responder};
async fn custom_response() -> impl Responder {
HttpResponse::Created() // 201 Created
.insert_header(("X-Custom-Header", "MyValue"))
.body("Resource created successfully")
}##JSON Responses
Actix Web integrates seamlessly with serde_json. To return JSON, you wrap a serializeable struct in web::Json.
use actix_web::{web, Responder};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
async fn get_user() -> impl Responder {
let user = User { id: 1, name: "Alice".into() };
web::Json(user)
}Actix Web will automatically set the status code to 200 and the Content-Type header to application/json.