OpenAPITools / OpenAPITools/openapi-generator

[BUG][python-fastapi] API route handler does not pass OAuth2 TokenModel to implementation

Open
#20,048 0 comments 0 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

OpenAPI Generator's generated Python-FastAPI code works by your implementation subclassing a base API module, and then the generated router module (ie: apis/pet_api.py) calls one of the subclasses of a base API module (ie: apis/pet_api_base.py).

The generated router method a reference to a TokenModel (token_petstore_auth), but this is attribute is never passed to the subclass add_pet() implementation:

https://github.com/OpenAPITools/openapi-generator/blob/98cd9bd80399c2ce235f4b087e005741fe07bdf3/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py#L50-L59

That code is generated here, where there is no reference to {{#authMethods}} in the method body, only {{#allParams}}:

https://github.com/OpenAPITools/openapi-generator/blob/98cd9bd80399c2ce235f4b087e005741fe07bdf3/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache#L62-L71

And the TokenModel doesn't appear in the base API module (ie: apis/pet_api_base.py):

https://github.com/OpenAPITools/openapi-generator/blob/98cd9bd80399c2ce235f4b087e005741fe07bdf3/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api_base.py#L15-L23

That code is generated here, where there is no reference to {{#authMethods}} at all:

https://github.com/OpenAPITools/openapi-generator/blob/98cd9bd80399c2ce235f4b087e005741fe07bdf3/modules/openapi-generator/src/main/resources/python-fastapi/base_api.mustache#L17-L23

As a result, it is impossible to use the validated information from the OAuth token in your implementation.

Expected behaviour

The base API should include the TokenModel:

class BasePetApi:
    # ...
    async def add_pet(
        self,
        pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")],
        token_petstore_auth: TokenModel = Security(
            get_token_petstore_auth, scopes=["write:pets", "read:pets"]
        ),
    ) -> Pet:
        """"""
        ...

The generated router method should pass on the TokenModel:

# ...
async def add_pet(
    pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")] = Body(None, description="Pet object that needs to be added to the store"),
    token_petstore_auth: TokenModel = Security(
        get_token_petstore_auth, scopes=["write:pets", "read:pets"]
    ),
) -> Pet:
    """"""
    if not BasePetApi.subclasses:
        raise HTTPException(status_code=500, detail="Not implemented")
    return await BasePetApi.subclasses[0]().add_pet(pet, token_petstore_auth)

That way, your implementation can use the token with something like:

class PetApiImpl(BasePetApi):
    # ...
    async def add_pet(self, pet: Pet, token_petstore_auth: TokenModel):
        database.Pet.objects.create(creator=token_petstore_auth.sub, pet=pet)
openapi-generator version

7.9.0

OpenAPI declaration file content or url

https://github.com/OpenAPITools/openapi-generator/blob/98cd9bd80399c2ce235f4b087e005741fe07bdf3/samples/server/petstore/python-fastapi/openapi.yaml#L23-L47

Generation Details

Sample is included with OpenAPI Generator:

./bin/generate-samples.sh ./bin/configs/*.yaml
Steps to reproduce
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 modules/openapi-generator/src/main/resources/python-fastapi/api.mustache and base_api.mustache, then compare their output with the Petstore sample files under samples/server/petstore/python-fastapi. Run ./bin/generate-samples.sh ./bin/configs/*.yaml and verify that authenticated generated methods expose the TokenModel and pass it to the implementation.

Written by the indexing model from the issue text.

Assessment

Tech stack
fastapi, openapi, python
Domain
api, authentication, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.