Crate poem_openapi

source ·
Expand description

OpenAPI support for Poem.

Poem-openapi allows you to easily implement APIs that comply with the OpenAPIv3 specification. It uses procedural macros to generate a lots of boilerplate code, so that you only need to focus on the more important business implementations.

Table of contents

Features

  • Type safety If your codes can be compiled, then it is fully compliant with the OpenAPI v3 specification.
  • Rustfmt friendly Do not create any DSL that does not conform to Rust’s syntax specifications.
  • IDE friendly Any code generated by the procedural macro will not be used directly.
  • Minimal overhead All generated code is necessary, and there is almost no overhead.

Quickstart

Cargo.toml

[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"

[dependencies]
poem = "1.2"
poem-openapi = { version = "1.2", features = ["swagger-ui"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

main.rs

use poem::{listener::TcpListener, Route, Server};
use poem_openapi::{payload::PlainText, OpenApi, OpenApiService};

struct Api;

#[OpenApi]
impl Api {
    /// Hello world
    #[oai(path = "/", method = "get")]
    async fn index(&self) -> PlainText<&'static str> {
        PlainText("Hello World")
    }
}

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);

Server::new(TcpListener::bind("127.0.0.1:3000"))
    .run(app)
    .await;

Check it

Open your browser at http://127.0.0.1:3000.

You will see the plaintext response as:

Hello World

Interactive API docs

Now go to http://127.0.0.1:3000/docs.

You will see the automatic interactive API documentation (provided by Swagger UI):

swagger-ui

Crate features

To avoid compiling unused dependencies, Poem gates certain features, some of which are disabled by default:

FeatureDescription
chronoIntegrate with the chrono crate
timeIntegrate with the time crate.
humantimeIntegrate with the humantime crate
swagger-uiAdd swagger UI support
rapidocAdd RapiDoc UI support
redocAdd Redoc UI support
emailSupport for email address string
hostnameSupport for hostname string
uuidIntegrate with the uuid crate
urlIntegrate with the url crate
bsonIntegrate with the bson crate
rust_decimalIntegrate with the rust_decimal crate
static-filesSupport for static file response

Modules

  • Some certificate types for security scheme.
  • Some common error types.
  • Macros to help with building custom payload types.
  • Parameter types for the API operation.
  • Commonly used payload types.
  • Commonly used data types.

Macros

Structs

Enums

Traits

Attribute Macros

Derive Macros