astahmer / openapi-zod-client

Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)
openapi-zod-client.vercel.app
717 stars 80 forks source link

Appropriately handle OpenAPI ReadOnly and WriteOnly properties #296

Open jjdonov opened 1 month ago

jjdonov commented 1 month ago

Describe the bug

OpenAPI has support for read and write only properties. Their documentation can be found here

You can use the readOnly and writeOnly keywords to mark specific properties as read-only or write-only. This is useful, for example, when GET returns more properties than used in POST – you can use the same schema in both GET and POST and mark the extra properties as readOnly. readOnly properties are included in responses but not in requests, and writeOnly properties may be sent in requests but not in responses.

It doesnt seem that openapi-zod-client respects these modifiers. As a result it can be really hard to work with the schemas when they are shared between GET and POST.

A naive way of working around this is to supply some dummy data to appease the compiler / zod, but that you know the API will not respect. For example, providing the id for a resource in a POST request body.

As a more comprehensive workaround, we are preprocessing the OpenAPI spec to split the schemas before passing them to openapi-zod-client.

Minimal reproduction

Reproduction

Use the generated client to create a message. It will require the id property, despite it being readonly.

Expected behavior

readOnly properties are not required in PATCH/PUT/POST bodies writeOnly properties are not expected in GET response bodies