question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error while opening swagger docs while uploading file in APIRouter

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

router = APIRouter(
    prefix='/predict',
    tags=["Prediction"],
    responses={404: {"description": "Not Found"}}
)


@router.post("/")
async def predict(file: UploadFile = File(...)):
    extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png")
    if not extension:
        raise HTTPException(status_code=400, detail="File Format Error : Uploaded file must be a JPG, JPEG or PNG file")
    image = read_image_file(await file.read())
    result = predict_pneumonia(image)
    if result > 0.6:
        return JSONResponse(content={"prediction": "pneumonia"})
    return JSONResponse(content={"prediction": "no pneumonia"})

Description

I am just trying to create a ML prediction application using FastAPI. While uploading images, swagger docs doesn’t load and its showing the below mentioned error. But the endpoint works perfectly when tried with Postman.

image

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 404, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 78, in __call__
    return await self.app(scope, receive, send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\applications.py", line 270, in __call__
    await super().__call__(scope, receive, send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\applications.py", line 124, in __call__
    await self.middleware_stack(scope, receive, send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
    raise exc
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\middleware\exceptions.py", line 75, in __call__
    raise exc
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\middleware\exceptions.py", line 64, in __call__
    await self.app(scope, receive, sender)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
    raise e
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\routing.py", line 680, in __call__
    await route.handle(scope, receive, send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\routing.py", line 275, in handle
    await self.app(scope, receive, send)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\starlette\routing.py", line 65, in app
    response = await func(request)
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\applications.py", line 225, in openapi
    return JSONResponse(self.openapi())
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\applications.py", line 200, in openapi
    self.openapi_schema = get_openapi(
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\openapi\utils.py", line 423, in get_openapi
    definitions = get_model_definitions(
  File "D:\Programming_Languages\Anaconda\envs\Medaignostic-Playground\lib\site-packages\fastapi\utils.py", line 39, in get_model_definitions
    model_name = model_name_map[model]
KeyError: <class 'pydantic.main.Body_predict_predict__post'>

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.85.0

Python Version

3.9

Additional Context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Shrijeethcommented, Sep 24, 2022

Thank you, I am able to resolve my issue by changing code inside routing.py file in fastapi (Line 593). I updated the code in routing.py line 593, as given below. Now it works perfectly.

if route not in self.routes:
            self.routes.append(route)
0reactions
tiangolocommented, Nov 14, 2022

Thanks for the help here @JarroVGIT ! 👏 🙇

If that solves the original problem, then you can close this issue @Shrijeeth ✔️

Read more comments on GitHub >

github_iconTop Results From Across the Web

[BUG] Error generating swagger docs when using uploadfile ...
Open the browser and call the endpoint /docs . KeyError raised. INFO:uvicorn:('127.0.0.1', 63331) - ...
Read more >
Error while uploading the swagger file
Hello Team, I have installed Swagger UI Field Formatter module using composer. I am getting an error as soon as i open the...
Read more >
File Upload - Swagger
Swagger UI displays file parameters using a file input control, allowing the users to browse for a local file to upload. Upload a...
Read more >
How to Upload File using FastAPI? - python - Stack Overflow
I just use f = open(file) method once, and when I send the request several times, the f will be closed after the...
Read more >
Release Notes - FastAPI
Close FormData (uploaded files) after the request is done. ... pip in the venv to avoid errors when installing dependencies docs/en/docs/contributing.md .
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found