Crate poem

source ·
Expand description

Poem is a full-featured and easy-to-use web framework with the Rust programming language.

Table of contents


use poem::{get, handler, listener::TcpListener, web::Path, IntoResponse, Route, Server};

fn hello(Path(name): Path<String>) -> String {
    format!("hello: {}", name)

async fn main() -> Result<(), std::io::Error> {
    let app = Route::new().at("/hello/:name", get(hello));


The Endpoint trait represents a type that can handle HTTP requests, and it returns the Result<T: IntoResponse, Error> type.

The handler macro is used to convert a function into an endpoint.

use poem::{
    error::NotFoundError, handler, http::StatusCode, test::TestClient, Endpoint, Request,

fn return_str() -> &'static str {

fn return_err() -> Result<&'static str, NotFoundError> {

let resp = TestClient::new(return_str).get("/").send().await;

let resp = TestClient::new(return_err).get("/").send().await;


The extractor is used to extract something from the HTTP request.

Poem provides some commonly used extractors for extracting something from HTTP requests.

In the following example, the index function uses 3 extractors to extract the remote address, HTTP method and URI.

use poem::{
    http::{Method, Uri},

fn index(remote_addr: &RemoteAddr, method: Method, uri: &Uri) {}

By default, the extractor will return a 400 Bad Request when an error occurs, but sometimes you may want to change this behavior, so you can handle the error yourself.

In the following example, when the Query extractor fails, it will return a 500 Internal Server response and the reason for the error.

use poem::{
    error::ParseQueryError, handler, http::StatusCode, web::Query, IntoResponse, Response,
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Params {
    name: String,

fn index(res: Result<Query<Params>>) -> Result<impl IntoResponse> {
    match res {
        Ok(Query(params)) => Ok(,
        Err(err) if<ParseQueryError>() => Ok(Response::builder()
        Err(err) => Err(err),


There are three available routes.

use poem::{get, handler, post, web::Path, Route};

async fn get_user(id: Path<String>) {}

async fn delete_user(id: Path<String>) {}

async fn create_user() {}

let app = Route::new()
    .at("/user/:id", get(get_user).delete(delete_user))
    .at("/user", post(create_user));

You can create custom extractors, see also FromRequest.


All types that can be converted to HTTP response Response should implement IntoResponse.

In the following example, the string_response and status_response functions return the String and StatusCode types, because Poem has implemented the IntoResponse trait for them.

The no_response function does not return a value. We can think that its return type is (), and Poem also implements IntoResponse for (), which is always converted to 200 OK.

The result_response function returns a Result type, which means that an error may occur.

use poem::{handler, http::StatusCode, Result};

fn string_response() -> String {

fn status_response() -> StatusCode {

fn no_response() {}

fn result_response() -> Result<String> {

Handling errors

The following example returns customized content when NotFoundError occurs.

use poem::{
    error::NotFoundError, handler, http::StatusCode, EndpointExt, IntoResponse, Response, Route,

fn foo() {}

fn bar() {}

let app =
        .at("/foo", foo)
        .at("/bar", bar)
        .catch_error(|err: NotFoundError| async move {
                .body("custom not found")


You can call the with method on the Endpoint to apply a middleware to an endpoint. It actually converts the original endpoint to a new endpoint.

use poem::{handler, middleware::Tracing, EndpointExt, Route};

fn index() {}

let app = Route::new().at("/", index).with(Tracing);

You can create your own middleware, see also Middleware.

Crate features

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

serverServer and listener APIs(enable by default)
compressionSupport decompress request body and compress response body
cookieSupport for Cookie
csrfSupport for Cross-Site Request Forgery (CSRF) protection
multipartSupport for Multipart
native-tlsSupport for HTTP server over TLS with native-tls
openssl-tlsSupport for HTTP server over TLS with openssl-tls
opentelemetrySupport for opentelemetry
prometheusSupport for Prometheus
redis-sessionSupport for RedisSession
rustlsSupport for HTTP server over TLS with rustls
sessionSupport for session
sseSupport Server-Sent Events (SSE)
tempfileSupport for tempfile
testTest utilities to test your endpoints.
tower-compatAdapters for tower::Layer and tower::Service.
websocketSupport for WebSocket
anyhowIntegrate with the anyhow crate.
eyre06Integrate with version 0.6.x of the eyre crate.
i18nSupport for internationalization
acme-native-rootsSupport for ACME(Automatic Certificate Management Environment)
acme-webpki-rootsSupport for ACME using webpki TLS roots rather than native TLS roots
tokio-metricsIntegrate with the tokio-metrics crate.
embedIntegrate with rust-embed crate.
xmlIntegrate with quick-xml crate.
yamlIntegrate with serde-yaml crate.



  • Endpoint related types.
  • Some common error types.
  • A general purpose library of common HTTP types
  • i18ni18n
    Internationalization related types.
  • listenerserver
    Commonly used listeners.
  • Commonly used middleware.
  • sessionsession
    Session management.
  • testtest
    Test utilities to test your endpoints.
  • Commonly used as the type of extractor or response.



  • An network address.


  • A helper function, similar to RouteMethod::new().connect(ep).
  • A helper function, similar to RouteMethod::new().delete(ep).
  • A helper function, similar to RouteMethod::new().get(ep).
  • A helper function, similar to RouteMethod::new().head(ep).
  • A helper function, similar to RouteMethod::new().options(ep).
  • A helper function, similar to RouteMethod::new().patch(ep).
  • A helper function, similar to RouteMethod::new().post(ep).
  • A helper function, similar to RouteMethod::new().put(ep).
  • A helper function, similar to RouteMethod::new().trace(ep).

Attribute Macros