### Setup Development Environment with Tox and Uv Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/development-contributing.md Steps to clone the repository, install uv, tox, and create a developer environment using tox. ```bash git clone git@github.com:/datamodel-code-generator.git cd datamodel-code-generator curl -LsSf https://astral.sh/uv/install.sh | sh uv tool install --python-preference only-managed --python 3.13 tox --with tox-uv tox run -e dev ``` -------------------------------- ### Quick Start CLI Command Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/asyncapi.md Use this command to quickly generate Python models from an AsyncAPI file. Ensure you have datamodel-code-generator installed. ```bash datamodel-codegen \ --input asyncapi.yaml \ --input-file-type asyncapi \ --output-model-type pydantic_v2.BaseModel \ --output model.py ``` -------------------------------- ### Example Output of Version Command Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/manual/version.md This is an example of the output you can expect when running the `--version` command. ```text datamodel-codegen version: 0.x.x ``` -------------------------------- ### Add field examples to docstrings Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/field-customization.md Use the `--use-field-description-example` flag to include `example` or `examples` properties from schema fields directly into the generated docstrings for IDE intellisense. ```bash datamodel-codegen --input schema.json --use-field-description-example ``` -------------------------------- ### Install datamodel-code-generator with uv Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md Recommended installation for standalone CLI use. This command installs the tool globally for your user. ```bash uv tool install datamodel-code-generator ``` -------------------------------- ### Install datamodel-code-generator with pip Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md Standard installation method using pip. ```bash pip install datamodel-code-generator ``` -------------------------------- ### Show Help Message Output Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/utility-options.md An example of the output when the --help option is used, showing the usage and available options. ```text usage: datamodel-codegen [-h] [--input INPUT] [--url URL] ... Generate Python data models from schema files. options: -h, --help show this help message and exit --input INPUT Input file path (default: stdin) ... ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/development-contributing.md Install and configure pre-commit hooks for maintaining code quality. ```bash uv tool install prek prek install ``` -------------------------------- ### Example AsyncAPI YAML Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/asyncapi.md An example AsyncAPI 3.0.0 document defining user signup events. This YAML is used as input for model generation. ```yaml asyncapi: 3.0.0 info: title: User events version: 1.0.0 channels: userSignedUp: messages: userSignedUp: payload: $ref: '#/components/schemas/UserSignedUp' components: schemas: UserSignedUp: type: object required: - id - email properties: id: type: string email: type: string format: email ``` -------------------------------- ### JSON Schema with Multi-line Description and Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/field-customization.md An example JSON schema illustrating a field with a multi-line description and an example value. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "MultilineDescriptionWithExample", "type": "object", "properties": { "name": { "type": "string", "description": "User name.\nThis is a multi-line description.", "example": "John Doe" } } } ``` -------------------------------- ### Install datamodel-code-generator with Protocol Buffers support Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md Install with optional Protocol Buffers support for generating models from .proto files. ```bash pip install 'datamodel-code-generator[protobuf]' ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/ci-cd.md Install pre-commit and its hooks in your project. This is a prerequisite for using the pre-commit configurations. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Generate Pydantic model with field examples Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/field-customization.md This example demonstrates how the `--use-field-description-example` flag transforms a JSON schema with 'example' and 'examples' properties into a Pydantic model with corresponding docstrings and field configurations. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Extras", "type": "object", "properties": { "name": { "type": "string", "description": "normal key", "key1": 123, "key2": 456, "$exclude": 123, "invalid-key-1": "abc", "-invalid+key_2": "efg", "$comment": "comment", "$id": "#name", "register": "hij", "schema": "klm", "x-repr": true, "x-abc": true, "example": "example", "readOnly": true }, "age": { "type": "integer", "example": 12, "writeOnly": true, "examples": [ 13, 20 ] }, "status": { "type": "string", "examples": [ "active" ] } } } ``` ```python # generated by datamodel-codegen: # filename: extras.json # timestamp: 2022-11-11T00:00:00+00:00 from __future__ import annotations from pydantic import BaseModel, Field class Extras(BaseModel): name: str | None = Field(None, description='normal key', examples=['example']) """ Example: 'example' """ age: int | None = Field(None, examples=[13, 20], json_schema_extra={'example': 12}) """ Examples: - 13 - 20 """ status: str | None = Field(None, examples=['active']) """ Example: 'active' """ ``` -------------------------------- ### Install Package in Editable Mode Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/development-contributing.md Clone the repository and install the package in editable mode for development. ```sh git clone git@github.com:koxudaxi/datamodel-code-generator.git pip install -e datamodel-code-generator ``` -------------------------------- ### Install Watch Dependency Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/general-options.md The watch feature requires the `watch` extra dependency to be installed. ```bash pip install 'datamodel-code-generator[watch]' ``` -------------------------------- ### Merge Rules Example for Profiles Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/pyproject_toml.md Illustrates how profile settings replace base settings, using 'strict-types' as an example where the profile's value completely overwrites the base configuration. ```toml [tool.datamodel-codegen] strict-types = ["str", "int"] http-headers = ["Authorization: Bearer token"] [tool.datamodel-codegen.profiles.api] strict-types = ["bytes"] ``` -------------------------------- ### Example Alias File Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/aliases.md This example demonstrates scoped aliases for specific fields within different classes, along with a fallback for fields not explicitly scoped. ```json { "Root.name": "root_name", "User.name": "user_name", "Address.name": "address_name" } ``` -------------------------------- ### TypedDict Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/output-model-types.md Example of TypedDict output, providing static type hints for dictionary structures. ```python from typing import TypedDict, NotRequired class Pet(TypedDict): id: int name: str tag: NotRequired[str] ``` -------------------------------- ### Install datamodel-code-generator with GraphQL support Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md Install with optional GraphQL support for generating models from GraphQL schemas. ```bash pip install 'datamodel-code-generator[graphql]' ``` -------------------------------- ### Install datamodel-code-generator with HTTP support Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md Install with optional HTTP support for resolving remote $ref values in schemas. ```bash pip install 'datamodel-code-generator[http]' ``` -------------------------------- ### Inline Field Description Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/field-customization.md Demonstrates how to use inline descriptions for fields, including multi-line text and examples. This is useful for providing detailed context directly within the data model definition. ```python description='User name.\nThis is a multi-line description.', examples=['John Doe'], ) """ User name. This is a multi-line description. Example: 'John Doe' """ ``` -------------------------------- ### OpenAPI Schema Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/field-customization.md An example OpenAPI 3.0.0 schema demonstrating various fields and their descriptions, including query parameters, response headers, and component schemas. ```yaml openapi: "3.0.0" info: version: 1.0.0 title: Swagger Petstore license: name: MIT servers: - url: http://petstore.swagger.io/v1 paths: /pets: get: summary: List all pets operationId: listPets tags: - pets parameters: - name: limit in: query description: How many items to return at one time (max 100) required: false schema: type: integer format: int32 responses: '200': description: A paged array of pets headers: x-next: description: A link to the next page of responses schema: type: string content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy post: summary: Create a pet operationId: createPets tags: - pets responses: '201': description: Null response default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById tags: - pets parameters: - name: petId in: path required: true description: The id of the pet to retrieve schema: type: string responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy components: schemas: Pet: required: - id - name properties: id: type: integer format: int64 default: 1 name: type: string tag: type: string Pets: type: array ``` -------------------------------- ### Example Protocol Buffers Schema Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/protobuf.md An example Protocol Buffers schema file (order.proto) defining messages for an order, including timestamps, oneofs, and a gRPC service definition. ```proto syntax = "proto3"; package example.shop.v1; import "google/protobuf/timestamp.proto"; message Order { // Unique order identifier. string id = 1; repeated string tags = 2; google.protobuf.Timestamp created_at = 3; oneof contact { string email = 4; string phone = 5; } } message GetOrderRequest { string id = 1; } message GetOrderResponse { Order order = 1; } service OrderService { rpc GetOrder(GetOrderRequest) returns (GetOrderResponse); } ``` -------------------------------- ### Problem: Duplicate Annotated Fields Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/model-reuse.md Without using `$ref`, each class gets its own inline field definition, leading to duplication. This example shows two classes with identical `place_name` fields. ```python class ClassA(BaseModel): place_name: Annotated[str, Field(alias='placeName')] # Duplicate! class ClassB(BaseModel): place_name: Annotated[str, Field(alias='placeName')] # Duplicate! ``` -------------------------------- ### Running datamodel-codegen with uv in GitHub Actions Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/ci-cd.md Leverage `uv` for managing Python dependencies and running commands within GitHub Actions. This example installs `datamodel-code-generator` ephemerally and executes a profile check. ```yaml - name: Install uv uses: astral-sh/setup-uv@v4 - name: Verify generated models are up-to-date run: uv run --with datamodel-code-generator datamodel-codegen --profile api --check ``` -------------------------------- ### Python __init__.py Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/general-options.md This snippet shows the generated __init__.py file for a modular structure, exporting key components. It's generated by datamodel-codegen. ```python # __init__.py # generated by datamodel-codegen: # filename: modular.yaml from ._internal import DifferentTea, Error, Id, Optional, Result, Source __all__ = ["DifferentTea", "Error", "Id", "Optional", "Result", "Source"] ``` -------------------------------- ### Quick Model Generation Workflow (Linux) Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/oneliner.md A practical example demonstrating the workflow for generating Pydantic v2 models from the clipboard on Linux using xclip. ```bash xclip -selection clipboard -o | uvx datamodel-codegen --input-file-type jsonschema --output-model-type pydantic_v2.BaseModel ``` -------------------------------- ### Quick Start: Generate from Python Model Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/python-model.md Use the `--input-model` argument to specify the Python file and object name, and `--output` for the generated file. ```bash datamodel-codegen --input-model ./mymodule.py:User --output model.py ``` -------------------------------- ### Quick Model Generation Workflow (macOS) Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/oneliner.md A practical example demonstrating the workflow for generating Pydantic v2 models from the clipboard on macOS. ```bash pbpaste | uvx datamodel-codegen --input-file-type jsonschema --output-model-type pydantic_v2.BaseModel ``` -------------------------------- ### Install Debug Extra Dependency Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/manual/debug.md The debug functionality requires the 'debug' extra to be installed with pip. Install it using the provided command. ```bash pip install 'datamodel-code-generator[debug]' ``` -------------------------------- ### Install email-validator for EmailStr Support Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/type-mappings.md Install the necessary dependency for Pydantic's EmailStr type, which is used for validating email formats. Alternatively, Pydantic can be installed with the 'email' extra. ```bash pip install email-validator # Or pip install pydantic[email] ``` -------------------------------- ### Example of custom template usage Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/template-customization.md Demonstrates how to use a custom template file for code generation. This is useful for advanced customization of the output structure and naming conventions. ```bash datamodel-codegen --input schema.json --output models.py --custom-template-dir ./templates/ ``` -------------------------------- ### Install datamodel-code-generator with pipx Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/index.md Install datamodel-code-generator using pipx for isolated environments. ```bash pipx install datamodel-code-generator ``` -------------------------------- ### Using Named Profiles via CLI Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/pyproject_toml.md Demonstrates how to activate a specific named profile ('api' or 'database') using the --profile option in the command line. ```bash datamodel-codegen --profile api datamodel-codegen --profile database ``` -------------------------------- ### Install datamodel-code-generator with conda Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md Install the package using conda from the conda-forge channel. ```bash conda install -c conda-forge datamodel-code-generator ``` -------------------------------- ### Example XML Schema Definition Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/xmlschema.md This is an example of a purchase order XML Schema definition. ```xml ``` -------------------------------- ### Quick Model Generation Workflow (Windows PowerShell) Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/oneliner.md A practical example demonstrating the workflow for generating Pydantic v2 models from the clipboard on Windows using PowerShell. ```powershell Get-Clipboard | uvx datamodel-codegen --input-file-type jsonschema --output-model-type pydantic_v2.BaseModel ``` -------------------------------- ### Recommended options for single-file projects Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/model-reuse.md This combination of options is recommended for single-file projects to deduplicate models and inline simple root models, resulting in cleaner output. ```bash datamodel-codegen \ --input schema.json \ --output model.py \ --reuse-model \ --collapse-root-models ``` -------------------------------- ### Show Help Message Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/manual/help.md Use the `--help` option to display the help message and exit. This command shows all available command-line options with their descriptions and default values. ```bash datamodel-codegen --help ``` -------------------------------- ### Install datamodel-code-generator with msgspec support Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/output-model-types.md Install the necessary package to enable msgspec support in datamodel-code-generator. ```bash pip install 'datamodel-code-generator[msgspec]' ``` -------------------------------- ### Example pyproject.toml Configuration Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/formatting.md Configures datamodel-codegen, black, isort, and ruff formatters with specific line lengths and quote styles. ```toml [tool.datamodel-codegen] formatters = ["builtin"] builtin-format-line-length = 100 [tool.black] line-length = 100 skip-string-normalization = true [tool.isort] profile = "black" line_length = 100 [tool.ruff] line-length = 100 [tool.ruff.format] quote-style = "single" ``` -------------------------------- ### Watch Mode Output Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/general-options.md This example shows the output when watch mode is successfully enabled. ```bash Watching ``` -------------------------------- ### Python dataclass Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/output-model-types.md Example of Python's built-in dataclass output for simple data structures. ```python from dataclasses import dataclass from typing import Optional @dataclass class Pet: id: int name: str tag: Optional[str] = None ``` -------------------------------- ### Example JSON Schema Input Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/README.md This is an example of a JSON schema used as input for generating a data model. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Pet", "type": "object", "required": ["name", "species"], "properties": { "name": { "type": "string", "description": "The pet's name" }, "species": { "type": "string", "enum": ["dog", "cat", "bird", "fish"] }, "age": { "type": "integer", "minimum": 0, "description": "Age in years" }, "vaccinated": { "type": "boolean", "default": false } } } ``` -------------------------------- ### Example pyproject.toml configuration with profiles Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/utility-options.md Shows how to define default settings and multiple named profiles (e.g., 'strict', 'dataclass') within the pyproject.toml file for datamodel-code-generator. ```toml [tool.datamodel-codegen] # Default configuration output-model-type = "pydantic_v2.BaseModel" [tool.datamodel-codegen.profiles.strict] # Strict profile with additional options strict-types = ["str", "int", "float", "bool"] strict-nullable = true [tool.datamodel-codegen.profiles.dataclass] # Dataclass profile output-model-type = "dataclasses.dataclass" ``` -------------------------------- ### Example OpenAPI 3.0.0 Schema Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/template-customization.md This is an example OpenAPI 3.0.0 schema used to demonstrate data model generation. ```yaml openapi: "3.0.0" info: version: 1.0.0 title: Swagger Petstore license: name: MIT servers: - url: http://petstore.swagger.io/v1 paths: /pets: get: summary: List all pets operationId: listPets tags: - pets parameters: - name: limit in: query description: How many items to return at one time (max 100) required: false schema: type: integer format: int32 responses: '200': description: A paged array of pets headers: x-next: description: A link to the next page of responses schema: type: string content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy post: summary: Create a pet operationId: createPets tags: - pets responses: '201': description: Null response default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById tags: - pets parameters: - name: petId in: path required: true description: The id of the pet to retrieve schema: type: string responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy components: schemas: Pet: required: - id - name properties: id: type: integer format: int64 default: 1 name: type: string tag: type: string Pets: type: array items: $ref: "#/components/schemas/Pet" Users: type: array items: required: - id - name properties: id: type: integer format: int64 name: type: string tag: type: string Id: type: string Rules: type: array items: type: string ``` -------------------------------- ### Generic Container Type Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/python-version-compatibility.md Example of generated Python code using `typing.Sequence` and `typing.Mapping` for type hints. ```python from typing import Mapping, Sequence class Data(BaseModel): items: Sequence[str] mapping: Mapping[str, int] ``` -------------------------------- ### Split Models into Separate Files Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/general-options.md Demonstrates how to use `--module-split-mode single` to generate each model class in its own file. This example also includes `--all-exports-scope recursive` and `--use-exact-imports` for comprehensive export management. ```bash datamodel-codegen --input schema.json --module-split-mode single --all-exports-scope recursive --use-exact-imports ``` -------------------------------- ### Recommended options for large multi-file projects Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/model-reuse.md This combination of options is recommended for large multi-file projects to achieve deduplicated models, shared types in a custom module, inlined root models, and minimal output. ```bash datamodel-codegen \ --input schemas/ \ --output models/ \ --reuse-model \ --reuse-scope tree \ --shared-module-name common \ --collapse-root-models ``` -------------------------------- ### Input Schema for TypedDict Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/typing-customization.md This is an example input JSON schema used to demonstrate the effect of the `--no-use-closed-typed-dict` option. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "title": "ClosedModel", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} }, "required": ["name"], "additionalProperties": false } ``` -------------------------------- ### Monorepo with Multiple Schemas Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/ci-cd.md This example demonstrates how to handle multiple schemas in a monorepo structure by using a matrix strategy. Each item in the matrix defines specific configurations for a different schema. ```yaml jobs: validate: runs-on: ubuntu-latest strategy: matrix: include: - working-directory: packages/api input: schemas/openapi.yaml output: src/models.py input-file-type: openapi - working-directory: packages/admin input: schemas/schema.json output: src/models.py input-file-type: jsonschema steps: - uses: actions/checkout@v4 - uses: koxudaxi/datamodel-code-generator@0.44.0 with: input: ${{ matrix.input }} output: ${{ matrix.output }} input-file-type: ${{ matrix.input-file-type }} output-model-type: pydantic_v2.BaseModel working-directory: ${{ matrix.working-directory }} ``` -------------------------------- ### Pydantic Field Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/general-options.md Demonstrates a Pydantic RootModel with a field that includes an example value, useful for API documentation or testing. ```python # bar.py # generated by datamodel-codegen: # filename: modular.yaml from __future__ import annotations from pydantic import Field, RootModel class FieldModel(RootModel[str]): root: str = Field(..., examples=['green']) ``` -------------------------------- ### Module Splitting Example Output Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/general-options.md Shows the generated Python code when using `--module-split-mode single`, resulting in separate files for `__init__.py`, `model.py`, `order.py`, and `user.py`. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { "User": { "type": "object", "properties": { "id": {"type": "integer"}, "name": {"type": "string"} } }, "Order": { "type": "object", "properties": { "id": {"type": "integer"}, "user": {"$ref": "#/definitions/User"} } } } } ``` ```python # __init__.py # generated by datamodel-codegen: # filename: input.json from __future__ import annotations from .model import Model from .order import Order from .user import User __all__ = [ "Model", "Order", "User", ] # model.py # generated by datamodel-codegen: # filename: input.json from __future__ import annotations from typing import Any from pydantic import RootModel class Model(RootModel[Any]): root: Any # order.py # generated by datamodel-codegen: # filename: input.json from __future__ import annotations from pydantic import BaseModel from .user import User class Order(BaseModel): id: int | None = None user: User | None = None # user.py # generated by datamodel-codegen: # filename: input.json from __future__ import annotations from pydantic import BaseModel class User(BaseModel): id: int | None = None name: str | None = None ``` -------------------------------- ### Pydantic v2 dataclass Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/output-model-types.md Example of Pydantic v2 dataclass output, combining dataclass syntax with Pydantic validation. ```python from pydantic.dataclasses import dataclass from typing import Optional @dataclass class Pet: id: int name: str tag: Optional[str] = None ``` -------------------------------- ### Pydantic v2 BaseModel Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/output-model-types.md Example of Pydantic v2 BaseModel output, including field validation and optional fields. ```python from pydantic import BaseModel, Field, RootModel class Pet(BaseModel): id: int = Field(..., ge=0) name: str = Field(..., max_length=256) tag: str | None = None class Pets(RootModel[list[Pet]]): root: list[Pet] ``` -------------------------------- ### Help Message Output Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/manual/help.md The output of the `--help` command provides usage information, a brief description of the tool, and a list of available options with their short descriptions and default values. ```text usage: datamodel-codegen [-h] [--input INPUT] [--url URL] ... Generate Python data models from schema files. options: -h, --help show this help message and exit --input INPUT Input file path (default: stdin) ... ``` -------------------------------- ### Generate Model from Clipboard (macOS) Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/oneliner.md Use pbpaste to pipe clipboard content to uvx for schema generation. This allows quick model creation from copied schemas. ```bash pbpaste | uvx datamodel-codegen --input-file-type jsonschema ``` ```bash pbpaste | uvx datamodel-codegen --input-file-type jsonschema --output model.py ``` ```bash pbpaste | uvx datamodel-codegen --input-file-type jsonschema | pbcopy ``` -------------------------------- ### OpenAPI Schema Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/field-customization.md This is an example of an OpenAPI 3.0.0 schema used as input for code generation. It defines pets, users, and associated operations. ```yaml openapi: "3.0.0" info: version: 1.0.0 title: Swagger Petstore license: name: MIT servers: - url: http://petstore.swagger.io/v1 paths: /pets: get: summary: List all pets operationId: listPets tags: - pets parameters: - name: limit in: query description: How many items to return at one time (max 100) required: false schema: type: integer format: int32 responses: '200': description: A paged array of pets headers: x-next: description: A link to the next page of responses schema: type: string content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy post: summary: Create a pet operationId: createPets tags: - pets responses: '201': description: Null response default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById tags: - pets parameters: - name: petId in: path required: true description: The id of the pet to retrieve schema: type: string responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy components: schemas: Pet: required: - id - name properties: id: type: integer format: int64 default: 1 name: type: string tag: type: string Pets: type: array items: $ref: "#/components/schemas/Pet" Users: type: array items: required: - id - name ``` -------------------------------- ### Generate Model from Clipboard (Linux xclip) Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/oneliner.md Utilize xclip to read from the clipboard and pipe it to uvx for schema generation. This enables clipboard integration on Linux systems. ```bash xclip -selection clipboard -o | uvx datamodel-codegen --input-file-type jsonschema ``` ```bash xclip -selection clipboard -o | uvx datamodel-codegen --input-file-type jsonschema | xclip -selection clipboard ``` -------------------------------- ### Example JSON Input Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/jsondata.md This is a sample JSON file used as input for generating Pydantic models. ```json { "pets": [ { "name": "dog", "age": 2 }, { "name": "cat", "age": 1 }, { "name": "snake", "age": 3, "nickname": "python" } ], "status": 200 } ``` -------------------------------- ### OpenAPI Schema Example Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/openapi-only-options.md This is an example of an OpenAPI 3.0.0 schema used as input. It includes info, servers, paths, and components with various definitions. ```yaml openapi: "3.0.0" info: version: 1.0.0 title: Swagger Petstore license: name: MIT servers: - url: http://petstore.swagger.io/v1 paths: /pets: get: summary: List all pets operationId: listPets tags: - pets parameters: - name: limit in: query description: How many items to return at one time (max 100) required: false schema: type: integer format: int32 responses: '200': description: A paged array of pets headers: x-next: description: A link to the next page of responses schema: type: string content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy post: summary: Create a pet operationId: createPets tags: - pets responses: '201': description: Null response default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById tags: - pets parameters: - name: petId in: path required: true description: The id of the pet to retrieve schema: type: string responses: '200': description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" x-amazon-apigateway-integration: uri: Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PythonVersionFunction.Arn}/invocations passthroughBehavior: when_no_templates httpMethod: POST type: aws_proxy components: schemas: Pet: required: - id - name properties: id: type: integer format: int64 default: 1 name: type: string tag: type: string Pets: type: array items: $ref: "#/components/schemas/Pet" Users: type: array items: required: - id - name properties: id: type: integer format: int64 name: type: string tag: type: string Id: type: string Rules: type: array items: type: string Error: description: error result required: - code - message properties: code: type: integer format: int32 ``` -------------------------------- ### Use a Named Profile Source: https://github.com/koxudaxi/datamodel-code-generator/blob/main/docs/cli-reference/manual/profile.md Specify a profile to apply its configuration settings. This example uses the 'strict' profile. ```bash datamodel-codegen --input schema.json --profile strict # (1)! ```