How can we convert pydantic models to json schema?
April 01, 2025
95.0% Confidence
# Converting Pydantic Models to JSON Schema
Pydantic is a powerful data validation and settings management library for Python. One of its key features is the ability to generate JSON schemas from Pydantic models automatically. This capability is beneficial for applications that require a stable and formal representation of data structures, such as APIs and data validation systems.
## Generating JSON Schema from Pydantic Models
To convert a Pydantic model to JSON Schema, you can utilize the `schema_json()` method available on Pydantic's `BaseModel`. This method returns a JSON schema as a string, which is compliant with the JSON Schema Draft 2020-12 specification, as well as OpenAPI extensions.
### Example of Generating JSON Schema
Here’s a simple example to illustrate how to generate a JSON schema:
```python
from pydantic import BaseModel
class MyModel(BaseModel):
id: int
name: str
# Generate JSON schema
json_schema = MyModel.schema_json()
print(json_schema)
```
In this example, the `MyModel` class defines a model with two fields: `id` of type integer and `name` of type string. Calling `MyModel.schema_json()` will generate a JSON schema that accurately represents this model.
### Other Methods for JSON Schema Generation
Pydantic also provides other methods for handling JSON representations and schemas:
- `BaseModel.model_json_schema()` returns a dictionary representation of the schema.
- `BaseModel.model_dump_json()` gives a JSON string representation of the schema dictionary.
- `TypeAdapter.json_schema()` can be used to generate a JSON schema for adapted types, allowing for more complex scenarios where models are adapted for various use cases[^2].
## Configuring JSON Schema Generation
To control the behavior of the generated JSON schemas, you can use model configuration. For instance, if you want to ensure that no extra fields are included in the output, you can configure the model as follows:
```python
from pydantic import BaseModel, Extra
class Query(BaseModel):
id: str
name: str = None
class Config:
extra = Extra.forbid
```
In this configuration, the `extra` property is set to `Extra.forbid`, which means that any additional fields not explicitly defined in the model will raise a validation error when the model is instantiated[^4].
## Suppressing Title Autogeneration
By default, Pydantic generates a title for fields in the JSON schema based on the attribute names. If you want to suppress this automatic title generation, you can subclass the `GenerateJsonSchema` class and override the `field_title_should_be_set` method, allowing for more control over the schema output[^1].
## Summary
In summary, converting Pydantic models to JSON Schema is straightforward with the built-in methods provided by the library. Whether you are generating a simple schema or utilizing more advanced features through configuration, Pydantic's design allows for flexibility and power in managing data definitions. Here are the key points to remember:
- Use `BaseModel.schema_json()` to generate JSON Schema.
- Utilize configuration options to control schema properties like extra fields.
- Consider subclassing for advanced customization of schema generation.
For more detailed information, you can refer to the official Pydantic documentation on [JSON Schema usage](https://docs.pydantic.dev/2.1/usage/json_schema)[^2].
### References:
[^1]: [Pydantic v2 to JSON Schema translation: How to suppress ...](https://stackoverflow.com/questions/78679812/pydantic-v2-to-json-schema-translation-how-to-suppress-autogeneration-of-title)
[^2]: [JSON Schema - Pydantic](https://docs.pydantic.dev/2.1/usage/json_schema)
[^4]: [How to generate a strict json schema with pydantic?](https://stackoverflow.com/questions/65738013/how-to-generate-a-strict-json-schema-with-pydantic)
Sources
Pydantic v2 to JSON Schema translation: How to suppress ...
"Discusses preventing title autogeneration in Pydan"
Visit Source
Dynamically Generating Pydantic Model from a Schema ...
"Explains how to get JSON schema from models."
Visit Source
How to generate a strict json schema with pydantic?
"Configuration for strict JSON schema generation"
Visit Source
How to Convert a Pydantic Model to JSON - HatchJS.com
"Explains how to convert Pydantic models to JSON."
Visit Source