OpenAPITools / OpenAPITools/openapi-generator

[BUG][Python] The schemaMappings and importMappings do not work in Python clients.

Open
#19,050 3 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Bug Report Checklist
  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

I am generating a Python client. I want to import some classes instead of generating them. The documentation says to use importMappings or schemaMappings. They don't work.

The importMappings are ignored. I found the code that clears them:

// clear import mapping (from default generator) as python does not use it
// at the moment
importMapping.clear();

The schemaMappings can be used to map the schema to something else (e.g. external objects/models outside of the package) according to the customization page. It is unclear how to set them when generating Python clients. They do not add import statements at the top of the generated file. Instead, they camelCase the values. I have used the schemaMappings successfully when generating Java clients for my API, but for Python client codegen they don't work.

I appreciate any advice. Thanks.

openapi-generator version

7.2.0

OpenAPI declaration file content or url
openapi: 3.0.3

info:
  version: 2.7.0
  title: Person API

tags:
  - name: Person
    description: Part of the Person API.
    x-tag-expanded: false

paths:
  /person:
    get:
      tags:
        - Person
      summary: Get a Person
      operationId: getPerson
      responses:
        '200':
          description: A person object.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Person'

components:
  schemas:
    # The Address should be imported, not generated
    Address:
        type: object
        properties:
            full_address:
              type: string
    Person:
      type: object
      properties:
        id:
          type: string
        first_name:
          type: string
        last_name:
          type: string
        age:
          type: integer
        address:
          $ref: '#/components/schemas/Address'
Generation Details
Steps to reproduce

Use the gradle plugin with these settings:

tasks.create("PersonGeneratorTask", GenerateTask) {
    outputDir.set(outputDirectory)
    inputSpec.set(filePath)
    generatorName.set("python")
    generateApiTests.set(false)
    generateApiDocumentation.set(false)
    generateModelTests.set(false)
    generateModelDocumentation.set(false)
    apiNameSuffix.set("Client")
    packageName.set("test_clients.person")
    configOptions.set([
            "hideGenerationTimestamp": "true",
            "generateSourceCodeOnly" : "true"
    ])
    importMappings.set([
            "Address": "from some_file import Address"
           // Also tried "Address": "some_file"
    ])
    schemaMappings.set([
            "Address": "from some_file import Address"
    ])
}

The result is the following code:

from __future__ import annotations
import pprint
import re  # noqa: F401
import json


from typing import Any, ClassVar, Dict, List, Optional
from pydantic import BaseModel, StrictInt, StrictStr
try:
    from typing import Self
except ImportError:
    from typing_extensions import Self

class Person(BaseModel):
    """
    Person
    """ # noqa: E501
    id: Optional[StrictStr] = None
    first_name: Optional[StrictStr] = None
    last_name: Optional[StrictStr] = None
    age: Optional[StrictInt] = None
    address: Optional[FromSomeFileImportAddress] = None
    __properties: ClassVar[List[str]] = ["id", "first_name", "last_name", "age", "address"]
Related issues/PRs
Suggest a fix

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 with PythonClientCodegen.java at the importMapping.clear() code and reproduce the issue using the Gradle GenerateTask settings and Person OpenAPI spec shown here. Trace how importMappings and schemaMappings reach Python model generation; done means an external Address type produces the intended import and type reference instead of a camel-cased value.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, python
Domain
tooling
Issue type
Bug
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.