poem_openapi Derive Macro ApiResponse Copy item path Source #[derive(ApiResponse)]
{
#[oai]
}
Expand description Define an OpenAPI response.
§ Macro parametersAttribute Description Type Optional
bad_request_handler Sets a custom bad request handler, it can convert error to the value of the this response type. string Y
header Add an extra header ExtraHeader
Y
display When converting a response to an error, the error message comes from the Display trait
. bool Y
§ Item parametersAttribute description Type Optional
status HTTP status code. If omitted, it is a default response type. u16 Y
content_type Specify the content type. string Y
actual_type Specifies the actual response type string Y
header Add an extra header ExtraHeader
Y
Attribute description Type Optional
deprecated Header deprecated String Y
Attribute description Type Optional
name Header name String N
ty Header type String N
description Header description String Y
deprecated Header deprecated bool Y
use poem_openapi::{payload::PlainText, ApiResponse};
#[derive(ApiResponse)]
enum CreateUserResponse {
#[oai(status = 200 )]
Ok (#[oai(header = "X-Id" )] String),
#[oai(status = 201 )]
OkWithBody(PlainText<String>, #[oai(header = "X-Id" )] String),
}
use poem_openapi::ApiResponse;
#[derive(ApiResponse)]
#[oai(
header(name = "X-ExtraHeader-1" , ty = "String" ),
header(name = "X-ExtraHeader-2" , ty = "i32" ),
)]
enum CreateUserResponse {
#[oai(status = 200 , header(name = "X-ExtraHeader-3" , ty = "f32" ))]
Ok ,
}
§ Example with bad request handler
use poem::Error;
use poem_openapi::{payload::PlainText, ApiResponse};
#[derive(ApiResponse)]
#[oai(bad_request_handler = "bad_request_handler" )]
enum CreateUserResponse {
#[oai(status = 200 )]
Ok ,
#[oai(status = 409 )]
UserAlreadyExists,
#[oai(status = 400 )]
BadRequest(PlainText<String>),
}
fn bad_request_handler(err: Error) -> CreateUserResponse {
CreateUserResponse::BadRequest(PlainText(format! ("error: {}" , err.to_string())))
}
§ Example as an error type
use poem::Error;
use poem_openapi::{payload::{PlainText, Json}, ApiResponse, Object, OpenApi};
#[derive(Object)]
struct CreateUserRequest {
username: String,
nickname: String,
email: String,
}
#[derive(ApiResponse)]
enum CreateUserResponse {
#[oai(status = 200 )]
Ok ,
}
#[derive(ApiResponse)]
enum CreateUserResponseError {
#[oai(status = 409 )]
UserAlreadyExists,
#[oai(status = 400 )]
BadRequest(PlainText<String>),
}
struct UserApi;
#[OpenApi]
impl UserApi {
#[oai(path = "/user" , method = "post" )]
async fn create(
& self ,
user: Json<CreateUserRequest>,
) -> Result <CreateUserResponse, CreateUserResponseError> {
todo! ()
}
}