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
[dependencies]
vld = "0.8"
vld-openapi = { version = "0.8", features = ["poem-openapi"] }
poem = "3"
poem-openapi = "5"
| Feature | Module | Notes |
|---|---|---|
poem-openapi | vld_openapi::poem_openapi | poem-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
| Item | Description |
|---|---|
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 animpl_type!type validates too, but poem-openapi turns any parse failure into one 400 text line (parse request payload error: failed to parse "User": ...). UseVldJson<T>for the structured 422.- The spec is OpenAPI 3.0: 2020-12 keywords are rewritten (
type: [.., "null"]→nullable, numericexclusiveMinimum→minimum+exclusiveMinimum: true). Keywords poem-openapi'sMetaSchemahas no field for (not,contains,propertyNames,x-*,additionalProperties: false) are left out of the document; vld still enforces them. impl_type!does not implementToJSON: returnVldJson<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 usevld_web::poem'sVldQueryin a plain poem route.
schemars and aide
Two-way bridge between vld and schemars - vld types as schemars::JsonSchema, and schemars types validated through vld.
TypeScript, Zod, Valibot
Generate TypeScript Zod (3 or 4) or Valibot schemas, or plain TypeScript types, from vld schemas, so the frontend validates exactly what the server does.