Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the same response model on two different endpoints on FastAPI

Tags:

python

fastapi

I am using FastAPI and I cannot view the documentation on the /docs endpoint when I have the same response model for two endpoints.

This is the code I use

import dataclasses

import fastapi
import uvicorn

app = fastapi.FastAPI()



@dataclasses.dataclass
class Response:
    yo: str


@app.post('/one', response_model=Response)
def get_responses():
    pass


@app.post('/two', response_model=Response)  # When I remove this "Response", or I create a second class it works.
def send_responses():
    pass


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1')

This is the error it shows in the browser enter image description here

This is the error it shows in the code

...
response = await func(request)
  File "E:\Code\venvs\lib\site-packages\fastapi\applications.py", line 224, in openapi
    return JSONResponse(self.openapi())
  File "E:\Code\venvs\lib\site-packages\fastapi\applications.py", line 199, in openapi
    self.openapi_schema = get_openapi(
  File "E:\Code\venvs\lib\site-packages\fastapi\openapi\utils.py", line 418, in get_openapi
    definitions = get_model_definitions(
  File "E:\Code\venvs\lib\site-packages\fastapi\utils.py", line 32, in get_model_definitions
    model_name = model_name_map[model]
KeyError: <class 'pydantic.dataclasses.Response'>

What am I doing wrong?

like image 774
Nayaro Avatar asked Jun 06 '26 20:06

Nayaro


1 Answers

To summarize the comments: currently FastAPI seems to have problems when re-using the same dataclass. The solution would be to use the BaseModel of pydantic instead.

Below is the full working code, the only change is how the class "Response" is declared.

import dataclasses

import fastapi
import uvicorn
import pydantic


app = fastapi.FastAPI()


class Response(pydantic.BaseModel):
    yo: str


@app.post('/one', response_model=Response)
def get_responses():
    pass


@app.post('/two', response_model=Response)
def send_responses():
    pass


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1')
like image 72
Nayaro Avatar answered Jun 10 '26 19:06

Nayaro