Skip to main content

Module poem_openapi

Module poem_openapi 

Source
Available on crate feature poem-openapi only.
Expand description

poem-openapi 5: vld types as poem-openapi request bodies and schemas.

  • impl_type! implements poem-openapi’s Type and ParseFromJSON for a vld::schema! / #[derive(Validate)] type: its OpenAPI schema is the vld json_schema() (a named component, nested vld::nested! types included), and parsing validates with vld. Json<User> then works in #[oai] operations; a failure is poem-openapi’s own 400 with vld’s message.
  • VldJson<T> is a request payload for such a type that answers 422 with every issue ({"error": "Validation failed", "issues": [{"path", "message", "code"}]}, the body vld_web sends) instead of one 400 text line. A wrong Content-Type stays poem-openapi’s 415. As a response, VldJson<T> serializes T (T: serde::Serialize).
  • json_schema_to_meta converts any vld JSON Schema to a MetaSchemaRef.

The schema is converted to the OpenAPI 3.0 dialect (crate::validator::to_openapi3) first. Keywords poem-openapi’s MetaSchema has no field for (not, contains, propertyNames, x-*, additionalProperties: false) are dropped from the document; validation still applies them.

use poem_openapi::{OpenApi, payload::Json};
use vld_openapi::poem_openapi::{VldJson, impl_type};

vld::schema! {
    #[derive(Debug, serde::Serialize)]
    pub struct NewUser {
        pub name: String => vld::string().min(2),
        pub age: i64 => vld::number().int().min(18),
    }
}
impl_type!(NewUser);

struct Api;

#[OpenApi]
impl Api {
    /// 422 with every issue on invalid input.
    #[oai(path = "/users", method = "post")]
    async fn create(&self, body: VldJson<NewUser>) -> Json<String> {
        Json(body.0.name)
    }

    /// poem-openapi's 400 on invalid input.
    #[oai(path = "/users/plain", method = "post")]
    async fn create_plain(&self, body: Json<NewUser>) -> Json<i64> {
        Json(body.0.age)
    }
}

let service = poem_openapi::OpenApiService::new(Api, "Users", "1.0");
assert!(service.spec().contains("\"minLength\": 2"));

Guide: https://s00d.github.io/vld/integrations/openapi/poem-openapi

Re-exports§

pub use ::poem_openapi;

Modules§

prelude
impl_type!, VldJson, json_schema_to_meta and vld::prelude.

Macros§

impl_type
Implement poem-openapi Type + ParseFromJSON for a vld type: impl_type!(T) or impl_type!(T, "ComponentName"). See the module docs.

Structs§

VldJson
A JSON request body validated with vld: 422 with every issue on failure. See the module docs.

Functions§

json_schema_to_meta
Convert a vld JSON Schema to a poem-openapi schema (OpenAPI 3.0).
validation_error
The 422 response VldJson rejects with: {"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}.