Skip to main content

FromRequest

Trait FromRequest 

Source
pub trait FromRequest<St>: Sized {
    type Error;

    // Required method
    async fn from_request(
        st: &St,
        req: &HttpRequest,
        payload: &mut Payload,
    ) -> Result<Self, Self::Error>;
}
Expand description

Turns request data into a value that a handler can use.

Each argument accepted by a handler registered with Route::to() is an extractor. Before calling the handler, ntex asks each argument type to create its value from the incoming request.

An extractor can look at the application state, request headers, path, and other request information. It can also read the request body through the payload. Extractors run in the same order as the handler arguments and share that payload, so an extractor that reads the body may leave nothing for the next one. For that reason, a handler should normally have only one body-reading extractor.

When an extractor returns an error, ntex turns it into an HTTP response and skips the handler. The error must implement WebResponseError for the application. If the handler should still run, use Option<T> to receive None, or Result<T, T::Error> to receive the original error.

§Example

A custom extractor can turn a request header into a handler argument:

use ntex::http::Payload;
use ntex::web::{self, FromRequest, HttpRequest, InternalError};

struct ClientName(String);

impl<St: web::State> FromRequest<St> for ClientName {
    type Error = InternalError<&'static str>;

    async fn from_request(_: &St, req: &HttpRequest, _: &mut Payload) -> Result<Self, Self::Error> {
        req.headers()
            .get("x-client-name")
            .and_then(|value| value.to_str().ok())
            .map(|value| ClientName(value.to_owned()))
            .ok_or_else(|| web::error::ErrorBadRequest("Missing client name"))
    }
}

async fn hello(client: ClientName) -> String {
    format!("Hello, {}!", client.0)
}

let app = web::App::default().route("/", web::get().to(hello));

Required Associated Types§

Source

type Error

The error returned when extraction fails.

For a route handler, ntex must be able to turn this error into an HTTP response through WebResponseError.

Required Methods§

Source

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<Self, Self::Error>

Creates the extractor value for this request.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<St, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> FromRequest<St> for (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, T6: FromRequest<St> + 'static, T7: FromRequest<St> + 'static, T8: FromRequest<St> + 'static, T9: FromRequest<St> + 'static, T10: FromRequest<St> + 'static, T11: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T6 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T7 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T8 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T9 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T10 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T11 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

impl<St, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> FromRequest<St> for (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, T6: FromRequest<St> + 'static, T7: FromRequest<St> + 'static, T8: FromRequest<St> + 'static, T9: FromRequest<St> + 'static, T10: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T6 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T7 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T8 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T9 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T10 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

impl<St, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> FromRequest<St> for (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, T6: FromRequest<St> + 'static, T7: FromRequest<St> + 'static, T8: FromRequest<St> + 'static, T9: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T6 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T7 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T8 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T9 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

impl<St, T0, T1, T2, T3, T4, T5, T6, T7, T8> FromRequest<St> for (T0, T1, T2, T3, T4, T5, T6, T7, T8)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, T6: FromRequest<St> + 'static, T7: FromRequest<St> + 'static, T8: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T6 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T7 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T8 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

impl<St, T0, T1, T2, T3, T4, T5, T6, T7> FromRequest<St> for (T0, T1, T2, T3, T4, T5, T6, T7)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, T6: FromRequest<St> + 'static, T7: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T6 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T7 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

impl<St, T0, T1, T2, T3, T4, T5, T6> FromRequest<St> for (T0, T1, T2, T3, T4, T5, T6)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, T6: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T6 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T0, T1, T2, T3, T4, T5, T6), Self::Error>

Source§

impl<St, T0, T1, T2, T3, T4, T5> FromRequest<St> for (T0, T1, T2, T3, T4, T5)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, T5: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T5 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T0, T1, T2, T3, T4, T5), Self::Error>

Source§

impl<St, T0, T1, T2, T3, T4> FromRequest<St> for (T0, T1, T2, T3, T4)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, T4: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T4 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T0, T1, T2, T3, T4), Self::Error>

Source§

impl<St, T0, T1, T2, T3> FromRequest<St> for (T0, T1, T2, T3)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, T3: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T3 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T0, T1, T2, T3), Self::Error>

Source§

impl<St, T0, T1, T2> FromRequest<St> for (T0, T1, T2)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, T2: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T2 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T0, T1, T2), Self::Error>

Source§

impl<St, T0, T1> FromRequest<St> for (T0, T1)
where St: State, T0: FromRequest<St> + 'static, T1: FromRequest<St> + 'static, <T0 as FromRequest<St>>::Error: WebResponseError<St, St::Error>, <T1 as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T0, T1), Self::Error>

Source§

impl<St, T> FromRequest<St> for (T,)
where St: State, T: FromRequest<St> + 'static, <T as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Source§

type Error = InternalError<&'static str>

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<(T,), Self::Error>

Source§

impl<St, T> FromRequest<St> for Option<T>
where St: State, T: FromRequest<St>, <T as FromRequest<St>>::Error: WebResponseError<St, St::Error>,

Optionally extract a field from the request

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

§Example
use ntex::http;
use ntex::web::{self, error, App, HttpRequest, FromRequest, InternalError};
use rand;

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

impl<St> FromRequest<St> for Thing {
    type Error = InternalError<&'static str>;

    async fn from_request(st: &St, req: &HttpRequest, payload: &mut http::Payload) -> Result<Self, Self::Error> {
        if rand::random() {
            Ok(Thing { name: "thingy".into() })
        } else {
            Err(error::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!")
    }
}

fn main() {
    let app = App::default().service(
        web::resource("/users/{first}").route(
            web::post().to(index))
    );
}
Source§

type Error = Infallible

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<Option<T>, Self::Error>

Source§

impl<St, T> FromRequest<St> for Result<T, T::Error>
where St: State, T: FromRequest<St>,

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

§Example
use ntex::http;
use ntex::web::{self, error, App, State, HttpRequest, FromRequest, InternalError};
use rand;

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

impl<St: State> FromRequest<St> for Thing {
    type Error = InternalError<&'static str>;

    async fn from_request(st: &St, req: &HttpRequest, payload: &mut http::Payload) -> Result<Thing, Self::Error> {
        if rand::random() {
            Ok(Thing { name: "thingy".into() })
        } else {
            Err(error::ErrorBadRequest("no luck"))
        }
    }
}

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

fn main() {
    let app = App::default().service(
        web::resource("/users/{first}").route(web::post().to(index))
    );
}
Source§

type Error = <T as FromRequest<St>>::Error

Source§

async fn from_request( st: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<Self, Self::Error>

Source§

impl<St: State> FromRequest<St> for String

Extract text information from a request’s body.

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

PayloadConfig allows to configure extraction process.

§Example
use ntex::web::{self, App, FromRequest, WebAppConfig};

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

fn main() {
    let cfg = WebAppConfig::new()
        .set_state(web::types::PayloadConfig::new(4096)); // <- limit size of the payload

    let app = App::default()
        .with_config(cfg)
        .service(
            web::resource("/index.html")
                .route(web::get().to(index))  // <- register handler with extractor params
    );
}
Source§

type Error = PayloadError

Source§

async fn from_request( _: &St, req: &HttpRequest, payload: &mut Payload, ) -> Result<String, Self::Error>

Implementors§

Source§

impl<St, T> FromRequest<St> for Form<T>
where St: State, T: DeserializeOwned + 'static,

Source§

impl<St, T> FromRequest<St> for Json<T>
where St: State, T: DeserializeOwned + 'static,

Json extractor. Allow to extract typed information from request’s payload.

To extract typed information from request’s body, the type T must implement the Deserialize trait from serde.

JsonConfig allows to configure extraction process.

§Example
use ntex::web;

#[derive(serde::Deserialize)]
struct Info {
    username: String,
}

/// deserialize `Info` from request's body
async fn index(info: web::types::Json<Info>) -> String {
    format!("Welcome {}!", info.username)
}

fn main() {
    let app = web::App::default().service(
        web::resource("/index.html").route(
           web::post().to(index))
    );
}
Source§

impl<St, T> FromRequest<St> for Query<T>
where St: State, T: DeserializeOwned,

Extract typed information from the request’s query.

§Example
use ntex::web;

#[derive(Debug, serde::Deserialize)]
pub enum ResponseType {
   Token,
   Code
}

#[derive(serde::Deserialize)]
pub struct AuthRequest {
   id: u64,
   response_type: ResponseType,
}

// Use `Query` extractor for query information.
// If `id` or `response_type` is missing or invalid, extraction fails and the
// handler is not called.
// The correct request for this handler would be `/index.html?id=64&response_type=Code`
async fn index(info: web::types::Query<AuthRequest>) -> String {
    format!("Authorization request for client with id={} and type={:?}!", info.id, info.response_type)
}

fn main() {
    let app = web::App::default().service(
       web::resource("/index.html")
           .route(web::get().to(index))); // <- use `Query` extractor
}
Source§

impl<St: State> FromRequest<St> for Bytes

Request binary data from a request’s payload.

Loads request’s payload and construct Bytes instance.

PayloadConfig allows to configure extraction process.

§Example
use ntex::{web, util::Bytes};

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

fn main() {
    let app = web::App::default().service(
        web::resource("/index.html").route(
            web::get().to(index))
    );
}
Source§

impl<St: State> FromRequest<St> for HttpRequest

It is possible to get HttpRequest as an extractor handler parameter

§Example
use ntex::web::{self, App, HttpRequest};

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

fn main() {
    let app = App::default().service(
        web::resource("/users/{first}").route(
            web::get().to(index))
    );
}
Source§

impl<St: State> FromRequest<St> for Payload

Get request’s payload stream

§Example
use std::future::Future;
use ntex::util::{BytesMut, Stream};
use ntex::web::{self, error, App, HttpResponse};

/// extract binary data from request
async fn index(mut body: web::types::Payload) -> Result<HttpResponse, error::PayloadError>
{
    let mut bytes = BytesMut::new();
    while let Some(item) = ntex::util::stream_recv(&mut body).await {
        bytes.extend_from_slice(&item?);
    }

    format!("Body {:?}!", bytes);
    Ok(HttpResponse::Ok().build())
}

fn main() {
    let app = App::default().service(
        web::resource("/index.html").route(
            web::get().to(index))
    );
}
Source§

impl<T, St: State> FromRequest<St> for Path<T>

Extract typed information from the request’s path.

§Example
use ntex::web;

/// extract path info from "/{username}/{count}/index.html" url
/// {username} - deserializes to a String
/// {count} - deserializes to a u32
async fn index(info: web::types::Path<(String, u32)>) -> String {
    format!("Welcome {}! {}", info.0, info.1)
}

fn main() {
    let app = web::App::default().service(
        web::resource("/{username}/{count}/index.html") // <- define path parameters
             .route(web::get().to(index)) // <- register handler with `Path` extractor
    );
}

It is possible to extract path information to a specific type that implements Deserialize trait from serde.

use std::convert::Infallible;
use ntex::web;

#[derive(serde::Deserialize)]
struct Info {
    username: String,
}

/// extract `Info` from a path using serde
async fn index(info: web::types::Path<Info>) -> Result<String, Infallible> {
    Ok(format!("Welcome {}!", info.username))
}

fn main() {
    let app = web::App::default().service(
        web::resource("/{username}/index.html") // <- define path parameters
             .route(web::get().to(index)) // <- use handler with `Path` extractor
    );
}