Using dry-validation with a pre-existing OpenAPI YAML

We have an OpenAPI spec and we’d like to validate API payloads using dry-validation. The source of truth is the YAML file (OpenAPI) and dry-validation/dry-schema would be our representation within Ruby.

The research I’ve made yield no results for that. There examples where the rules are specified as dry-schema and then exported to openapi.yml [link], or someone is testing the OpenAPI spec itself [link].

The main problem is creating the schema and not duplicating what’s already in the YAML file. I would like to construct the AST based on the YAML content, but I’m afraid there’s no way of doing that with public methods (at least I couldn’t find it).

I’m considering that maybe the way forward would be to define some basic structure and then load data from the file, e.g (pseudo-code, not sure how it’d look like in the end):

class PersonContract < Dry::Validation::Contract
  json do
    require(:data).hash do"openapi.yml", self).rules_for(:person, :data)

I predict that would become cumbersome real quickly. What would be recommended way here?

You can write a rule compiler that takes OpenAPI YAML and turns it into rule AST. This is public API and the AST structure didn’t change since ~2018 so I would consider this to be pretty stable.

The simplest approach would be to write schemas using the DSL to cover all use cases that you have in your OpenAPI specifications, dump these schemas to rule AST and then write a compiler that would match this AST.


I understand that I would have to (1) create a compiler for the OAS YAML format, (2) generate an AST from it and (3) input into dry-schema. The “input into dry-schema” is the uncertain part. For instance, schema.to_ast exists, but is there something like schema.from_ast?

I supposed not, so the remaining option for inputting the OAS AST into dry-schema is, I suppose, for the compiler to call those dry-schema methods such as required and optional and so forth directly.

I’m still studying the complexity of all this vs just going with some OAS gem. dry-validation’s errors would be ideal though.

Thanks a lot for the reply.

p.s. the reason why I’m not writing rules dry-schema first then exporting to OAS is because OAS is a much richer format, with examples, descriptions, URL scope and so forth, so exporting would be lossy. Multiple teams over here are using that OAS file independently.