CodingCode ReviewIntermediate30 minSaves 30 minutes

Generate JSON Schema from Python Dataclasses for OpenAPI

For Python platform engineers, convert existing dataclasses or Pydantic models into valid JSON Schema, streamlining OpenAPI documentation of internal event structures.

This prompt helps Python platform engineers generate accurate JSON Schema definitions directly from their existing `dataclass` or Pydantic models. It simplifies the creation of OpenAPI documentation for internal event payloads, ensuring consistency and reducing manual effort in API specification maintenance.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
Role: Act as a senior Python platform engineer focused on robust data serialization and API specification.

Context: Our internal microservices rely on well-defined data structures, often implemented as Python `dataclasses` or Pydantic models. To facilitate integration and maintain accurate documentation, we need to automatically generate JSON Schema definitions from these models for our OpenAPI specifications. Manual schema creation is proving unsustainable and prone to inconsistencies.

Task: Create a Python utility designed to introspect either a standard `dataclass` or a Pydantic `BaseModel` and accurately translate its definition into a valid JSON Schema. This utility should be flexible enough to handle various Python types and model complexities.

Constraints:
1.  **Modularity**: The solution should be structured as a self-contained Python module, ready for integration into a larger project.
2.  **Type Safety**: All code must include comprehensive type hints, adhering to modern Python best practices.
3.  **Testing**: Include a set of `pytest` unit tests that validate the utility's functionality across different model structures and data types.
4.  **Dependencies**: Provide a `pyproject.toml` file configured for `poetry` or `uv`, listing all required project dependencies (e.g., `pydantic` if Pydantic models are supported, `jsonschema` for validation, etc.).
5.  **Schema Completeness**: The generated JSON Schema must correctly represent:
    *   Primitive Python types (`str`, `int`, `float`, `bool`).
    *   Standard library types (`list`, `dict`, `set`, `tuple`).
    *   `Optional` fields and fields with default values.
    *   Nested `dataclasses` or Pydantic models.
    *   `Enum` types, converting them to JSON Schema `enum` arrays.
    *   Custom types if clearly defined (e.g., `datetime`, `UUID` as `string` with `format`).
6.  **Schema Standard**: The output JSON Schema should conform to Draft 2020-12 or a recent stable version.
7.  **Input Flexibility**: The utility's primary function, `generate_json_schema`, should accept a Python class (either a `dataclass` or a Pydantic `BaseModel`) as its input argument: `generate_json_schema(model_class: type) -> dict`.
8.  **Docstrings**: All public functions and classes should have clear docstrings.

Output:
Present the complete solution in the following format:

1.  **Module Layout**: A clear outline of the proposed file and directory structure.
2.  **`pyproject.toml`**: The full content for managing dependencies.
3.  **`json_schema_generator.py`**: The complete, typed Python code for the utility.
4.  **`test_json_schema_generator.py`**: Comprehensive `pytest` test cases.
5.  **Runtime Notes**: Concise instructions on how to set up the environment, run tests, and use the `generate_json_schema` function with an example like `{{example_model_name}}`, which is a `{{model_type}}`.

Estimated results

DifficultyIntermediate
Setup time30 min
Time saved30 minutes
Best modelsChatGPT, Gemini, Claude
Best audienceSoftware Development, API Management

Editor's note

Why this prompt matters

For Python platform engineers managing internal microservices, keeping API documentation current and consistent with the actual code can be a significant challenge. Data structures, often defined as dataclasses or Pydantic models, evolve. Manually translating these models into JSON Schema for OpenAPI specifications is not only tedious but also a common source of discrepancies. These inconsistencies lead to integration issues, broken contracts, and a loss of trust in the documentation itself.

This workflow directly addresses that pain point by offering a dependable, automated solution. Instead of hand-crafting schema definitions, we generate them directly from the source of truth—your Python models. This approach ensures that your OpenAPI documentation precisely reflects the data contracts enforced by your services. It's about establishing a reliable, type-safe pipeline from code definition to API specification, reducing operational overhead and improving developer experience for teams consuming your services.

The focus here is on production-grade tooling: a modular utility with comprehensive type hints and thorough testing. This isn't just about generating a schema; it's about building a reliable component that integrates into your CI/CD, guaranteeing that your API specifications are always in lockstep with your Python data models, even as they undergo iterative development.

Anatomy

Prompt engineering breakdown

Role

Act as a senior Python platform engineer focused on robust data serialization and API specification.

Context

Our internal microservices rely on well-defined data structures, often implemented as Python `dataclasses` or Pydantic models. We need to automatically generate JSON Schema definitions from these models for OpenAPI specifications, as manual creation is unsustainable and inconsistent.

Goal

Create a Python utility designed to introspect either a standard `dataclass` or a Pydantic `BaseModel` and accurately translate its definition into a valid JSON Schema, handling various Python types and model complexities.

Constraints

The solution must be a self-contained, typed Python module with `pytest` unit tests. It needs `poetry` or `uv` for dependencies. The generated JSON Schema must be complete, representing primitive, standard library, optional, nested, and custom types, conforming to Draft 2020-12. The utility's function should accept a class type, and all public components require docstrings.

Output format

The solution should be presented as a module layout, a `pyproject.toml` file, the complete `json_schema_generator.py` code, `test_json_schema_generator.py` test cases, and clear runtime notes with an example.

Why this structure works

This prompt structure effectively guides the model by first establishing a clear role priming as a senior platform engineer, which sets the appropriate tone and expected technical depth. Explicit constraints precisely define the non-negotiable requirements for type safety, testing, and schema completeness, preventing deviation. Finally, the detailed structured output section ensures the response delivers all necessary components in a ready-to-use format, minimizing follow-up iterations.

Pick your version

Prompt variations

BeginnerWorks with any model

For developers new to JSON Schema generation or needing a basic utility for simple dataclasses, focusing on core functionality over advanced features or strict enterprise standards.

prompt.txt
Role: You are a Python developer. Context: I have a Python `dataclass` and I need to convert it into a JSON Schema for basic documentation. Task: Write a Python script that takes a simple `dataclass` and generates its JSON Schema. Focus on converting common types like strings, integers, and booleans. Constraints: The script should be easy to understand and run, with minimal external dependencies. Include an example `dataclass` and show how to use your function. Output: Provide the Python code and a simple explanation of how to run it with `{{your_dataclass_name}}`.
ProfessionalBest with claude

When a comprehensive, production-grade utility is required, including type hinting, thorough testing, and precise dependency management for complex data models.

prompt.txt
Role: Act as a senior Python platform engineer.

Context: Our team needs a consistent, automated approach to translate Python `dataclass` or Pydantic `BaseModel` definitions into valid JSON Schema. This process is critical for generating accurate OpenAPI documentation and ensuring strict data contract adherence across our microservices. Relying on manual schema creation has led to inconsistencies and increased integration overhead.

Task: Construct a Python utility capable of introspecting a given `{{python_model_class}}` and producing its equivalent JSON Schema. The utility should accurately map primitive types, complex nested structures, `Optional` fields, fields with default values, and `Enum` types.

Constraints:
1.  **Type Safety**: All code must include comprehensive type hints.
2.  **Modularity**: The solution should be a self-contained, importable Python module.
3.  **Testing**: Provide `pytest` unit tests verifying schema generation across various model complexities.
4.  **Dependencies**: Include a `pyproject.toml` file listing all necessary project dependencies.
5.  **Schema Version**: The output JSON Schema must conform to Draft 2020-12.
6.  **Documentation**: Ensure public functions and classes have clear docstrings.
Short VersionWorks with any model

For rapid prototyping or when seeking a concise code snippet to quickly grasp the core logic of JSON Schema generation from Python models without detailed setup instructions.

prompt.txt
Act as a Python platform engineer. Your task is to generate a valid JSON Schema from the given `{{python_model_class}}` (either a `dataclass` or Pydantic `BaseModel`). The output schema must accurately reflect primitive types, nested structures, `Optional` fields, and `Enum` types for OpenAPI documentation. Include essential type hints.
EnterpriseBest with gemini

For large-scale organizational deployments where compliance, security, architectural consistency, and detailed documentation are paramount, requiring a solution integrated with enterprise standards.

prompt.txt
Role: Act as a lead Python platform architect, overseeing enterprise data governance and API compliance.

Context: Our organization manages a vast array of internal microservices, each defining critical data structures with Python `dataclasses` or Pydantic models. Ensuring data integrity, regulatory compliance, and consistent API contracts across these services is paramount. Manual JSON Schema generation for OpenAPI documentation is a significant bottleneck, introducing inconsistencies and audit risks. We require a scalable, auditable framework to automate this process, supporting schema evolution and effective integration into our CI/CD pipelines.

Task: Design and implement a production-ready Python framework to automatically generate valid, versioned JSON Schema definitions from `dataclass` or Pydantic `BaseModel` inputs. This framework must prioritize reliability, maintainability, and extensibility within a regulated enterprise environment.

Constraints:
1.  **Compliance & Auditability**: Generated schemas must include metadata linking to source models and versions. Support schema versioning and diffing.
2.  **Scalability**: Efficiently process a large volume of models (e.g., `{{number_of_models}}` across services) without performance degradation.
3.  **CI/CD Integration**: Provide examples for integrating schema generation, validation, and publication into existing CI/CD workflows.
4.  **Error Handling & Reporting**: Implement comprehensive error handling and generate detailed reports on schema generation status and validation failures.
5.  **Extensibility**: Allow for custom type mappings and schema extensions (e.g., `x-` fields).
6.  **Schema Standard**: Strictly adhere to JSON Schema Draft 2020-12.
7.  **Input Flexibility**: The core function, `generate_json_schema`, must accept a Python class (`dataclass` or Pydantic `BaseModel`) as its input: `generate_json_schema(model_class: type) -> dict`.
8.  **Security**: Address potential security implications, like preventing sensitive default values in public schemas.
9.  **Documentation**: Provide comprehensive developer documentation, including architecture and usage guides.
10. **Dependencies**: Manage all dependencies via `pyproject.toml` with explicit version pinning.

Output:
Present the complete framework, including architectural overview, core code, CI/CD integration examples, a comprehensive test suite, and full documentation.

What you'll get

Expected output

Given a Python dataclass definition, the utility will produce a corresponding JSON Schema dictionary. For instance, consider these two Python data structures, where UserProfile includes a nested Address and various standard and custom types:

```python import dataclasses from enum import Enum from typing import Optional, List import datetime import uuid

class Status(Enum): ACTIVE = "active" INACTIVE = "inactive"

@dataclasses.dataclass class Address: street: str city: str zip_code: str

@dataclasses.dataclass class UserProfile: user_id: uuid.UUID username: str email: Optional[str] = None age: int = 30 is_active: bool = True roles: List[str] status: Status created_at: datetime.datetime billing_address: Address ```

Executing generate_json_schema(UserProfile) would yield the following JSON Schema. This output correctly translates nested models, enumerations, optional fields, and default values into their JSON Schema equivalents. Custom types like uuid.UUID and datetime.datetime are mapped to string with appropriate format attributes, ensuring broad compatibility for API specifications.

``json { "title": "UserProfile", "type": "object", "properties": { "user_id": { "type": "string", "format": "uuid" }, "username": { "type": "string" }, "email": { "type": "string" }, "age": { "type": "integer", "default": 30 }, "is_active": { "type": "boolean", "default": true }, "roles": { "type": "array", "items": { "type": "string" } }, "status": { "type": "string", "enum": ["active", "inactive"] }, "created_at": { "type": "string", "format": "date-time" }, "billing_address": { "$ref": "#/$defs/Address" } }, "required": [ "user_id", "username", "roles", "status", "created_at", "billing_address" ], "$defs": { "Address": { "title": "Address", "type": "object", "properties": { "street": { "type": "string" }, "city": { "type": "string" }, "zip_code": { "type": "string" } }, "required": ["street", "city", "zip_code"] } } } ``

This schema accurately reflects the Python type definitions. Non-optional fields without defaults are marked as required, Enum members are correctly represented as a string enum array, and nested dataclasses are handled with $ref and $defs for proper schema modularity. This structure is suitable for direct inclusion in OpenAPI specifications.

Under the hood

Why this prompt works

This prompt succeeds by establishing a clear, production-minded context and then layering precise, actionable constraints. The initial role-play, "Act as a senior Python platform engineer," immediately sets the expected tone and technical depth, guiding the model to generate idiomatic, high-quality Python code rather than generic scripts. The detailed context grounds the task in a realistic problem: automating schema generation for OpenAPI, which helps the model understand the broader application of its output.

The core strength lies in the comprehensive constraints. Explicitly demanding "Modularity," "Type Safety," "Testing," and "Docstrings" pushes the model beyond basic functionality, ensuring the generated solution adheres to modern engineering best practices. Specifying exact requirements for "Schema Completeness"—listing primitive types, standard library containers, Optional fields, nested models, and Enum types—prevents omissions and guides the model to handle common data structures accurately. Furthermore, the "Input Flexibility" constraint, defining the exact function signature, eliminates ambiguity in API design. These specific, technical directives collectively steer the model towards a complete, testable, and maintainable utility, directly addressing the stated need for robust data serialization and API specification.

Model fit

Best AI models for this prompt

Claude

Claude excels at understanding complex, multi-part instructions and producing well-structured, idiomatic Python code. Its ability to maintain context across a detailed request makes it suitable for generating a complete module with tests and configuration. However, it may sometimes require minor corrections for specific jsonschema draft nuances or edge-case type handling. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT is effective for generating functional Python code, particularly when given explicit instructions for type hinting and test cases. It can produce reasonable pyproject.toml files and structure. Review its output carefully for adherence to the latest jsonschema standards and ensure all edge cases for Python type conversions are covered. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini is capable of generating solid Python utility code and is generally good at following detailed formatting requirements. It handles common dataclass and Pydantic model introspection well. Verify that the generated schema precisely matches the expected jsonschema specification for complex nested types or custom field validations, as these sometimes need refinement. See the full Gemini hub for deeper guidance.

When to use

  • When automating the generation of OpenAPI specifications for internal microservices.
  • To ensure consistent data contracts across different Python services that share models.
  • For rapid prototyping of new data models where immediate JSON Schema output is beneficial.
  • When documenting event payloads or API request/response bodies defined by dataclasses or Pydantic models.
  • To programmatically validate data against schemas derived directly from your Python code.

When not to use

  • If your project's data schemas are very simple and manual maintenance is already efficient.
  • When a dedicated API design platform is the primary source of truth for your public API schemas.
  • If your data models are not defined using Python dataclasses or Pydantic BaseModel.
  • For generating schemas that require extensive custom logic beyond type introspection.

Get more from it

Pro tips

  • 1

    Prioritize Pydantic models for advanced schema features like validation rules and examples to enrich the generated schema. This prevents manual schema keyword additions.

  • 2

    Extend the default type mapping dictionary for any custom types (e.g., `Decimal`, `URL`) to ensure accurate, specific schema representation. This avoids generic string or object types.

  • 3

    Integrate schema generation into your CI/CD pipeline to automate documentation updates whenever models change. This prevents documentation from becoming stale.

  • 4

    Validate the generated JSON Schemas against a standard JSON Schema validator to catch subtle structural or type inconsistencies early. This prevents runtime schema validation errors.

  • 5

    Add descriptive docstrings to your model fields; these often translate directly into the `description` attribute in the JSON Schema. This improves API clarity.

  • 6

    Consider supporting Python 3.9+ `Annotated` types to embed additional schema metadata directly within type hints. This provides richer schema details like `min_length` or `pattern`.

Don't ship this

Common mistakes

  • Forgetting to mark nullable fields as `Optional`, leading to schemas that incorrectly enforce required status for those fields.

    Fix — Explicitly use `typing.Optional[Type]` or `Type | None` for any field that can legitimately be null in the data.

  • Not handling `Enum` types correctly, resulting in generic `string` types in the schema instead of specific `enum` arrays.

    Fix — Ensure the utility maps `Enum` types to a JSON Schema `enum` keyword containing all valid member values.

  • Ignoring custom type conversions for types like `UUID` or `datetime`, leading to generic `string` schemas without format.

    Fix — Implement custom handlers to map specific types like `UUID` or `datetime` to `string` with appropriate `format` attributes.

  • Relying on default type mappings for complex nested types without deep introspection, yielding vague `array` or `object` schemas.

    Fix — Recursively inspect nested structures, especially lists of models, to infer and specify their item schemas accurately.

  • Failing to update the schema generator when new Python type hints or Pydantic features are introduced in models.

    Fix — Periodically review and update the schema generation logic to support the latest type hinting constructs and Pydantic model capabilities.

People also ask

Frequently asked questions

Q.Can this utility handle Python models with circular references?

Direct circular references in models can cause infinite recursion during schema generation. The current implementation may not handle these gracefully. Consider refactoring models to break circular dependencies or implementing a mechanism within the generator to track and resolve forward references.

Q.How does this generated JSON Schema integrate with an existing OpenAPI specification?

The generated JSON Schema is typically placed within the components/schemas section of your OpenAPI specification. You can then reference these schemas from your API path definitions using the $ref keyword. This keeps your API documentation consistent with your Python models.

Q.Will this utility work with older Python versions, or is it strictly for modern type hints?

This utility is designed for modern Python (3.8+) leveraging dataclasses and comprehensive type hints. While it might partially function with older versions, full support for Optional, Pydantic models, and advanced type introspection requires a recent Python environment.

Q.What if I need to add specific JSON Schema keywords like `minimum` or `pattern` that aren't inferred?

For Pydantic models, you can often embed these directly using Field arguments (e.g., Field(..., min_length=5)). For standard dataclasses, you would need to extend the utility to parse custom metadata attached to fields or apply a post-processing step to the generated schema dictionary.

Q.Is it possible to generate a single JSON Schema file that includes all my Python models?

Yes, you can iterate through all your relevant dataclass or Pydantic models, call the generate_json_schema function for each, and collect the resulting schemas. Consolidate these into a single dictionary, typically under a components/schemas key, and then write it to a file.

Q.How does this compare to Pydantic's built-in `model_json_schema()` method?

Pydantic's model_json_schema() is highly optimized for Pydantic models and is generally the preferred method when exclusively using Pydantic. This utility provides a more generic solution, aiming to support both Pydantic and standard dataclasses through a unified interface, which is useful in mixed environments.

Q.What if my models use custom base classes or involve complex meta-programming?

The utility relies on standard introspection of dataclasses and Pydantic BaseModel structures. Custom meta-programming that significantly alters how class attributes or type hints are resolved might require modifications to the utility's introspection logic to correctly identify fields and their types.

Version 1.0Last reviewed July 20, 2026
Reviewed by PromptInFlow Editorial Team