Uniform response for poem-openapi.
The poem-openapi-response is a poem-openapi extension crate, in order to unify the poem-openapi
response types.
In this crate:
- [
ErrorResponse] includes all the types defined in the Poem framework that implementResponseError, facilitating the generation of Responses from errors already defined by Poem. - [
UniResponse<T>] is shaped like [Result<T, ErrorResponse>], in general T means a response with status code 200, but it can also be any type that implementsApiResponse. Please note that, If the status codes defined inTandErrorResponseare the same, the definition inTwill override the definition inErrorResponse. This is useful when you want to define a custom error response.
Quickstart
Cargo.toml
[]
= "helloworld"
= "0.1.0"
= "2021"
[]
= "1"
= { = "2", = ["swagger-ui"] }
= "0.2.0"
= { = "1", = ["macros", "rt-multi-thread"] }
main.rs
use poem::{listener::TcpListener, EndpointExt, Route, Server};
use poem_openapi::{payload::PlainText, OpenApi, OpenApiService};
use poem_openapi_response::{ErrorResponse, UniResponse};
struct Api;
#[OpenApi]
impl Api {
/// Hello world
#[oai(path = "/hello", method = "get")]
async fn hello(&self) -> UniResponse<PlainText<&'static str>> {
UniResponse::new(PlainText("Hello World"))
}
/// Not found
#[oai(path = "/not_found", method = "get")]
async fn not_found(&self) -> UniResponse {
UniResponse::not_found(None)
}
}
let api_service =
OpenApiService::new(Api, "Hello World", "1.0").server("http://localhost:3000");
let ui = api_service.swagger_ui();
let app = Route::new()
.nest("/", api_service)
.nest("/docs", ui)
.catch_all_error(|e| async move {
ErrorResponse::from_poem_error(e)
.unwrap_or_else(|| ErrorResponse::InternalServerError(PlainText(e.to_string())))
});
# tokio::runtime::Runtime::new().unwrap().block_on(async {
Server::new(TcpListener::bind("127.0.0.1:3000"))
.run(app)
.await;
# });