Skip to content
Advertisement

Export Pydantic Model, with all ENUM values expanded

I have a pydantic model ModelX, with member Enums defined. The script should run as is.

JavaScript

I want to export this model as a JSON with the list of all Enum values. Something like

JavaScript

I am looking to return this Json as a response of my api call, all Enum values, it can be under “allOf” key or some other better way. This way the response has all the possible enum values and the consumer of this response can use it to pre-validate requests, or even show them on a UI screen.

Let me know in case more details or explanation is required.

Advertisement

Answer

Pydantic is configured to export json schema compliant with the following specifications: JSON Schema Core, JSON Schema Validation, OpenAPI.

These specs follow the design principle of reducing repeated elements. Child models are referenced with ref to avoid unnecessarily repeating model definitions.

You can override some elements of this by modifying a “sub-model” in the Field class by adding a custom title or default value. Only the overloaded values however will be included.

In your case, you will need to employ a workaround to manipulate the final state:

JavaScript
Advertisement