pub trait FromRequest<S, B, M = ViaRequest>: Sized {
type Rejection: IntoResponse;
// Required method
fn from_request<'life0, 'async_trait>(
req: Request<B>,
state: &'life0 S,
) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>>
where 'life0: 'async_trait,
Self: 'async_trait;
}
Expand description
Types that can be created from requests.
Extractors that implement FromRequest
can consume the request body and can thus only be run
once for handlers.
If your extractor doesnโt need to consume the request body then you should implement
FromRequestParts
and not FromRequest
.
See axum::extract
for more general docs about extractors.
ยงWhat is the B
type parameter?
FromRequest
is generic over the request body (the B
in
http::Request<B>
). This is to allow FromRequest
to be usable with any
type of request body. This is necessary because some middleware change the
request body, for example to add timeouts.
If youโre writing your own FromRequest
that wont be used outside your
application, and not using any middleware that changes the request body, you
can most likely use axum::body::Body
.
If youโre writing a library thatโs intended for others to use, itโs recommended to keep the generic type parameter:
use axum::{
async_trait,
extract::FromRequest,
http::{self, Request},
};
struct MyExtractor;
#[async_trait]
impl<S, B> FromRequest<S, B> for MyExtractor
where
// these bounds are required by `async_trait`
B: Send + 'static,
S: Send + Sync,
{
type Rejection = http::StatusCode;
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
// ...
}
}
This ensures your extractor is as flexible as possible.
Required Associated Typesยง
Sourcetype Rejection: IntoResponse
type Rejection: IntoResponse
If the extractor fails itโll use this โrejectionโ type. A rejection is a kind of error that can be converted into a response.
Required Methodsยง
Dyn Compatibilityยง
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.