pub struct Json<T>(pub T);
Expand description
JSON extractor and response.
To extract the specified type of JSON from the body, T
must implement
serde::Deserialize
.
Errors
use poem::{
handler,
http::{Method, StatusCode},
post,
web::Json,
Endpoint, Request, Route,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
}
#[handler]
async fn index(Json(user): Json<User>) -> String {
format!("welcome {}!", user.name)
}
let app = Route::new().at("/", post(index));
let resp = app
.call(
Request::builder()
.method(Method::POST)
.body(r#"{"name": "foo"}"#),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.into_body().into_string().await.unwrap(),
"welcome foo!"
);
Response
To serialize the specified type to JSON, T
must implement
serde::Serialize
.
use poem::{get, handler, http::StatusCode, web::Json, Endpoint, Request, Route};
use serde::Serialize;
#[derive(Serialize)]
struct User {
name: String,
}
#[handler]
async fn index() -> Json<User> {
Json(User {
name: "foo".to_string(),
})
}
let app = Route::new().at("/", get(index));
let resp = app.call(Request::default()).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.into_body().into_string().await.unwrap(),
r#"{"name":"foo"}"#
)
Tuple Fields
0: T
Trait Implementations
fn from_request<'life0, 'async_trait>(
_req: &'a Request,
body: &'life0 mut RequestBody
) -> Pin<Box<dyn Future<Output = Result<Self>> + Send + 'async_trait>> where
'a: 'async_trait,
'life0: 'async_trait,
Self: 'async_trait,
fn from_request<'life0, 'async_trait>(
_req: &'a Request,
body: &'life0 mut RequestBody
) -> Pin<Box<dyn Future<Output = Result<Self>> + Send + 'async_trait>> where
'a: 'async_trait,
'life0: 'async_trait,
Self: 'async_trait,
Extract from request head and body.
Consume itself and return Response
.
fn with_header<K, V>(self, key: K, value: V) -> WithHeader<Self> where
K: TryInto<HeaderName>,
V: TryInto<HeaderValue>,
Self: Sized,
fn with_header<K, V>(self, key: K, value: V) -> WithHeader<Self> where
K: TryInto<HeaderName>,
V: TryInto<HeaderValue>,
Self: Sized,
Wrap an impl IntoResponse
to add a header. Read more
Wrap an impl IntoResponse
to set a status code. Read more
Auto Trait Implementations
impl<T> RefUnwindSafe for Json<T> where
T: RefUnwindSafe,
impl<T> UnwindSafe for Json<T> where
T: UnwindSafe,
Blanket Implementations
impl<T, A, P> Access<T> for P where
A: Access<T>,
P: Deref<Target = A>,
impl<T, A, P> Access<T> for P where
A: Access<T>,
P: Deref<Target = A>,
Mutably borrows from an owned value. Read more
pub fn load(&self) -> DynGuard<T>
pub fn load(&self) -> DynGuard<T>
The equivalent of [Access::load
].
Compare self to key
and return true
if they are equal.
Consumes this value returns a poem::Result<T>
.
pub fn vzip(self) -> V
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more