OpenAPI and JSON Schema

poem-openapi

vld types as poem-openapi request bodies - the OpenAPI schema from vld, validation on parse, 422 with every issue.

vld_openapi::poem_openapi makes a vld::schema! / #[derive(Validate)] type usable in poem-openapi operations: the generated spec documents the vld rules (minLength, minimum, pattern, nested components, …), and the body is validated by vld when it is parsed. No #[derive(Object)] and #[oai(validator(...))] duplicates.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-openapi = { version = "0.8", features = ["poem-openapi"] }
poem = "3"
poem-openapi = "5"
FeatureModuleNotes
poem-openapivld_openapi::poem_openapipoem-openapi 5.x, poem 3.x

Example

use poem::{Route, Server, listener::TcpListener};
use poem_openapi::{OpenApi, OpenApiService, payload::Json};
use vld_openapi::poem_openapi::{VldJson, impl_type};

vld::schema! {
    #[derive(Debug)]
    pub struct Address {
        pub city: String => vld::string().min(1),
    }
}
impl_type!(Address);

vld::schema! {
    #[derive(Debug, serde::Serialize)]
    pub struct NewUser {
        pub name: String => vld::string().min(2).max(50),
        pub email: String => vld::string().email(),
        pub age: i64 => vld::number().int().min(18),
        pub address: Address => vld::nested!(Address),
    }
}
impl_type!(NewUser, "User"); // component name; default: the type name

struct Api;

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

    /// Invalid body: poem-openapi's own 400 with vld's message.
    #[oai(path = "/users/plain", method = "post")]
    async fn create_plain(&self, body: Json<NewUser>) -> Json<String> {
        Json(body.0.name)
    }
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let api = OpenApiService::new(Api, "Users", "1.0").server("http://localhost:3000/api");
    let app = Route::new().nest("/api", api);
    Server::new(TcpListener::bind("0.0.0.0:3000")).run(app).await
}

A rejected VldJson body:

HTTP/1.1 422 Unprocessable Entity

{"error": "Validation failed", "issues": [
  {"path": ".name", "message": "...", "code": "too_small"},
  {"path": ".address.city", "message": "...", "code": "too_small"}
]}

The same body as the vld_web extractors send. Malformed JSON is 422 with a parse_error issue; a non-JSON Content-Type is poem-openapi's 415.

API

ItemDescription
impl_type!(T) / impl_type!(T, "Name")poem-openapi Type + ParseFromJSON for a vld type: a named component from json_schema() (nested vld::nested! types registered too), parsed with vld
VldJson<T>request payload (application/json): 422 with every issue; as a response it serializes T (T: serde::Serialize)
validation_error(&VldError)the 422 poem::Error VldJson rejects with, for your own extractors
json_schema_to_meta(&Value)any vld JSON Schema → MetaSchemaRef (OpenAPI 3.0 dialect)

Gotchas

  • Json<T> with an impl_type! type validates too, but poem-openapi turns any parse failure into one 400 text line (parse request payload error: failed to parse "User": ...). Use VldJson<T> for the structured 422.
  • The spec is OpenAPI 3.0: 2020-12 keywords are rewritten (type: [.., "null"] → nullable, numeric exclusiveMinimum → minimum + exclusiveMinimum: true). Keywords poem-openapi's MetaSchema has no field for (not, contains, propertyNames, x-*, additionalProperties: false) are left out of the document; vld still enforces them.
  • impl_type! does not implement ToJSON: return VldJson<T> (or your own #[derive(Object)] type) from operations.
  • Query / path / header parameters stay poem-openapi's per-argument Query<T> / Path<T> / Header<T>; for a whole vld struct from the query string use vld_web::poem's VldQuery in a plain poem route.