OpenAPITools / OpenAPITools/openapi-generator

[REQ] Generate Pydantic examples accordingly

Open
#20,264 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Enhancement: Feature
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

When using the python-fastapi generator, examples specified in the OpenAPI specification are not applied to the generated Pydantic fields.

For example, given the following OpenAPI 3.0 specification (.yaml):

openapi: 3.0.3
info:
  title: Sample API
  description: An example OpenAPI specification with various field types.
  version: 1.0.0
paths:
  /data:
    post:
      summary: Submit data
      description: Endpoint to submit data with various types.
      operationId: submitData
      requestBody:
        description: Data object containing various types
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                id:
                  type: integer
                  description: A unique identifier for the data object.
                  example: 123
                name:
                  type: string
                  description: A name for the data object.
                  example: Name of the object
                value:
                  type: number
                  format: double
                  description: A floating-point number representing the value.
                  example: 99.99
                isActive:
                  type: boolean
                  description: Indicates whether the data is active or not.
                  example: true
                tags:
                  type: array
                  description: A list of tags associated with the data.
                  items:
                    type: string
                  example:
                    - "tag"

              required:
                - id
                - value
                - isActive
      responses:
        '201':
          description: Data submitted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: integer
                    description: The unique identifier of the created data object.
                    example: 123
                  message:
                    type: string
                    description: Success message.
                    example: "Data submitted successfully."
        '400':
          description: Bad Request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    description: Error message indicating why the request failed.
                    example: "Invalid input data."

The resulting Pydantic model should look like this:

id: int = Field(examples=[123], description="A unique identifier for the data object.")
name: str = Field(examples=["Name of the Object"], description="A name for the data object.")
value: float = Field(examples=[99.99], description="A floating-point number representing the value.")
isActive: bool = Field(examples=[True], description="Indicates whether the data is active or not.")
tags: list[str] = Field(examples=[["tag"]], description="A list of tags associated with the data.")

However, currently, the examples field is not being set. This behavior is confirmed by the following lines of code:

https://github.com/OpenAPITools/openapi-generator/blob/326f100f0e4e50f569f43fbceaa5448b407fa8f9/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java#L2178-L2183

https://github.com/OpenAPITools/openapi-generator/blob/326f100f0e4e50f569f43fbceaa5448b407fa8f9/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java#L2255-L2258

I attempted to modify the code to include the examples parameter in the Pydantic Field (using cp.getExample()), but running the script ./bin/generate-samples.sh ./bin/configs/*.yaml || exit resulted in numerous unexpected changes. These changes seem to be introduced by a default example value, as defined here:

https://github.com/OpenAPITools/openapi-generator/blob/326f100f0e4e50f569f43fbceaa5448b407fa8f9/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java#L371-L376

For instance, the generated example for an integer becomes 56 due to the following logic:

https://github.com/OpenAPITools/openapi-generator/blob/326f100f0e4e50f569f43fbceaa5448b407fa8f9/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java#L486-L490

I suspect the toExampleValue function in AbstractPythonCodegen.java needs to be completely reworked. It should:
1. Use only explicitly defined examples from the .yaml file.
2. Properly escape values or this kind of transformation where necessary.

I am willing to work on this, but I’d like to confirm if this is the correct approach before proceeding. As mentioned above, the generated examples are not currently used when generating the Pydantic model, so I believe this change would not introduce any breaking changes.

Could you provide your thoughts on this? Am I missing anything here?

Tagging relevant contributors for feedback: @cbornet @tomplus @krjakbrjak @fa0311 @multani

cc: @evelynegroen

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the referenced sections of modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java, especially the Pydantic field handling and toExampleValue logic. Run ./bin/generate-samples.sh ./bin/configs/*.yaml to inspect the reported changes, then verify that explicitly defined OpenAPI examples appear in generated Pydantic Field declarations without unintended defaults.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, java, openapi, python
Domain
api, backend-api-design, tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.