Poem is a full-featured and easy-to-use web framework with the Rust programming language.
Features
- Both Ease of use and performance.
- Minimizing the use of generics.
- Blazing fast and flexible routing.
-
tower::Service
andtower::Layer
compatibility. - Use
Poem-openapi
to write APIs that comply with OAS3 specifications and automatically generate documents.
Basic example
use poem::{handler, listener::TcpListener, route, route::get, web::Path, Server};
#[handler]
fn hello(Path(name): Path<String>) -> String {
format!("hello: {}", name)
}
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let app = route().at("/hello/:name", get(hello));
let listener = TcpListener::bind("127.0.0.1:3000");
let server = Server::new(listener).await?;
server.run(app).await
}
OpenAPI example
use poem::{listener::TcpListener, route};
use poem_openapi::{payload::PlainText, OpenApi, OpenApiService};
struct Api;
#[OpenApi]
impl Api {
#[oai(path = "/hello", method = "get")]
async fn index(
&self,
#[oai(name = "name", in = "query")] name: Option<String>,
) -> PlainText<String> {
match name {
Some(name) => PlainText(format!("hello, {}!", name)),
None => PlainText("hello!".to_string()),
}
}
}
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let listener = TcpListener::bind("127.0.0.1:3000");
let api_service = OpenApiService::new(Api)
.title("Hello World")
.server("http://localhost:3000/api");
let ui = api_service.swagger_ui("http://localhost:3000");
poem::Server::new(listener)
.await?
.run(route().nest("/api", api_service).nest("/", ui))
.await
}