logo
pub trait FromRequest: Sized {
    type Error: Into<Error>;
    type Future: Future<Output = Result<Self, Self::Error>>;
    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future;

    fn extract(req: &HttpRequest) -> Self::Future { ... }
}
Expand description

A type that implements FromRequest is called an extractor and can extract data from the request. Some types that implement this trait are: Json, Header, and Path.

Configuration

An extractor can be customized by injecting the corresponding configuration with one of:

Here are some built-in extractors and their corresponding configuration. Please refer to the respective documentation for details.

Implementing An Extractor

To reduce duplicate code in handlers where extracting certain parts of a request has a common structure, you can implement FromRequest for your own types.

Note that the request payload can only be consumed by one extractor.

Associated Types

The associated error which can be returned.

Future that resolves to a Self.

Required methods

Create a Self from request parts asynchronously.

Provided methods

Create a Self from request head asynchronously.

This method is short for T::from_request(req, &mut Payload::None).

Implementations on Foreign Types

Optionally extract a field from the request

If the FromRequest for T fails, return None rather than returning an error response

Examples

use actix_web::{web, dev, App, Error, HttpRequest, FromRequest};
use actix_web::error::ErrorBadRequest;
use futures_util::future::{ok, err, Ready};
use serde::Deserialize;
use rand;

#[derive(Debug, Deserialize)]
struct Thing {
    name: String
}

impl FromRequest for Thing {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
        if rand::random() {
            ok(Thing { name: "thingy".into() })
        } else {
            err(ErrorBadRequest("no luck"))
        }

    }
}

/// extract `Thing` from request
async fn index(supplied_thing: Option<Thing>) -> String {
    match supplied_thing {
        // Puns not intended
        Some(thing) => format!("Got something: {:?}", thing),
        None => format!("No thing!")
    }
}

let app = App::new().service(
    web::resource("/users/:first").route(
        web::post().to(index))
);

Optionally extract a field from the request or extract the Error if unsuccessful

If the FromRequest for T fails, inject Err into handler rather than returning an error response

Examples

use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest};
use actix_web::error::ErrorBadRequest;
use futures_util::future::{ok, err, Ready};
use serde::Deserialize;
use rand;

#[derive(Debug, Deserialize)]
struct Thing {
    name: String
}

impl FromRequest for Thing {
    type Error = Error;
    type Future = Ready<Result<Thing, Error>>;

    fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
        if rand::random() {
            ok(Thing { name: "thingy".into() })
        } else {
            err(ErrorBadRequest("no luck"))
        }
    }
}

/// extract `Thing` from request
async fn index(supplied_thing: Result<Thing>) -> String {
    match supplied_thing {
        Ok(thing) => format!("Got thing: {:?}", thing),
        Err(e) => format!("Error extracting thing: {}", e)
    }
}

let app = App::new().service(
    web::resource("/users/:first").route(web::post().to(index))
);

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

Extract text information from a request’s body.

Text extractor automatically decode body according to the request’s charset.

Use PayloadConfig to configure extraction process.

Examples

use actix_web::{post, web, FromRequest};

// extract text data from request
#[post("/")]
async fn index(text: String) -> String {
    format!("Body {}!", text)
}

Implementors

Extract the request’s method.

Examples

use actix_web::{http::Method, web, App, Responder};

async fn handler(method: Method) -> impl Responder {
    format!("Request method: {}", method)
}

let app = App::new().default_service(web::to(handler));

Extract the request’s URI.

Examples

use actix_web::{http::Uri, web, App, Responder};

async fn handler(uri: Uri) -> impl Responder {
    format!("Requested path: {}", uri.path())
}

let app = App::new().default_service(web::to(handler));

It is possible to get HttpRequest as an extractor handler parameter

Examples

use actix_web::{web, App, HttpRequest};
use serde::Deserialize;

/// extract `Thing` from request
async fn index(req: HttpRequest) -> String {
   format!("Got thing: {:?}", req)
}

let app = App::new().service(
    web::resource("/users/{first}").route(
        web::get().to(index))
);

Extract binary data from a request’s payload.

Collects request payload stream into a Bytes instance.

Use PayloadConfig to configure extraction process.

Examples

use actix_web::{post, web};

/// extract binary data from request
#[post("/")]
async fn index(body: web::Bytes) -> String {
    format!("Body {:?}!", body)
}

See here for example of usage as an extractor.

See here for example of usage as an extractor.

See here for example of usage as an extractor.

See here for example of usage as an extractor.

See here for example of usage as an extractor.

See here for example of usage as an extractor.