-
Describe the bugKeyError when trying to fetch the swagger docs To ReproduceSteps to reproduce the behavior with a minimum self-contained file. Replace each part with your own scenario:
import base64
from fastapi import APIRouter, File, UploadFile
from starlette.requests import Request
router = APIRouter()
@router.post('/uploadfile')
def get(request: Request, file: UploadFile = File(...)):
filename_parts = file.filename.split('.')
file = file.file.read()
if filename_parts[-1] == 'xlsx':
file = base64.b64encode(file)
return {"file": file}
INFO:uvicorn:('127.0.0.1', 63331) - "GET /openapi.json HTTP/1.1" 500
ERROR:uvicorn:Exception in ASGI application
Traceback (most recent call last):
File "venv/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "venv/lib/python3.7/site-packages/fastapi/applications.py", line 139, in __call__
await super().__call__(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/applications.py", line 134, in __call__
await self.error_middleware(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/middleware/errors.py", line 178, in __call__
raise exc from None
File "venv/lib/python3.7/site-packages/starlette/middleware/errors.py", line 156, in __call__
await self.app(scope, receive, _send)
File "venv/lib/python3.7/site-packages/starlette/middleware/cors.py", line 76, in __call__
await self.app(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/middleware/base.py", line 25, in __call__
response = await self.dispatch_func(request, self.call_next)
File "./components/requests/middleware.py", line 26, in requests_middleware
response = await call_next(request)
File "venv/lib/python3.7/site-packages/starlette/middleware/base.py", line 45, in call_next
task.result()
File "venv/lib/python3.7/site-packages/starlette/middleware/base.py", line 38, in coro
await self.app(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/middleware/base.py", line 25, in __call__
response = await self.dispatch_func(request, self.call_next)
File "./components/metadata_db/middleware.py", line 18, in session_middleware
response = await call_next(request)
File "venv/lib/python3.7/site-packages/starlette/middleware/base.py", line 45, in call_next
task.result()
File "venv/lib/python3.7/site-packages/starlette/middleware/base.py", line 38, in coro
await self.app(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/exceptions.py", line 73, in __call__
raise exc from None
File "venv/lib/python3.7/site-packages/starlette/exceptions.py", line 62, in __call__
await self.app(scope, receive, sender)
File "venv/lib/python3.7/site-packages/starlette/routing.py", line 590, in __call__
await route(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/routing.py", line 208, in __call__
await self.app(scope, receive, send)
File "venv/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "venv/lib/python3.7/site-packages/fastapi/applications.py", line 96, in openapi
return JSONResponse(self.openapi())
File "venv/lib/python3.7/site-packages/fastapi/applications.py", line 88, in openapi
openapi_prefix=self.openapi_prefix,
File "venv/lib/python3.7/site-packages/fastapi/openapi/utils.py", line 268, in get_openapi
flat_models=flat_models, model_name_map=model_name_map
File "venv/lib/python3.7/site-packages/fastapi/utils.py", line 45, in get_model_definitions
model_name = model_name_map[model]
KeyError: <class 'Body_post_uploadfile_post'>Expected behaviorSwagger documentation should load ScreenshotsEnvironment
Additional contextHaving the same issue with a singular Body parameter in a separate endpoint (as explained here). Since that example is more complex I posted this one instead |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments
-
|
@speizerj I'm unable to reproduce this, on either 0.42.0 or latest. I'm happy to troubleshoot further with you if you would like. Here's what I did: Install FastAPI for developmentSee the FastAPI docs on contributing. # GitHub CLI: https://cli.github.com/
~/dev
❯ gh repo fork --clone="true" tiangolo/fastapi
~/dev
❯ cd fastapi
~/dev/fastapi master
❯ git checkout 0.42.0
Note: switching to '0.42.0'.
HEAD is now at 65536cb :bookmark: Release version 0.42.0: Answer to the Ultimate Question of Life, the Universe, and Everything
~/dev/fastapi tags/0.42.0
❯ python -m venv env
# May need to add env to .gitignore for 0.42.0
~/dev/fastapi tags/0.42.0
❯ . env/bin/activate
~/dev/fastapi tags/0.42.0
env ❯ python --version
Python 3.7.7
~/dev/fastapi tags/0.42.0
env ❯ pip install flit
~/dev/fastapi tags/0.42.0
env ❯ flit install --deps all --symlink
~/dev/fastapi tags/0.42.0
env ❯ pip show fastapi uvicorn | grep -e "Name" -e "Version"
Name: fastapi
Version: 0.42.0
Name: uvicorn
Version: 0.11.5Set up directory with test fileCreate a separate directory and put in the test file from the bug report as main.py, adding a FastAPI instance to enable it to run, and adding the example code from the docs for a singular Body parameter in a separate endpoint as described in "Additional context." ~/dev
❯ mkdir fastapi-1523; cd fastapi-1523
# VSCode CLI: https://code.visualstudio.com/docs/editor/command-line
~/dev/fastapi-1523
❯ touch main.py; code main.pyimport base64
from fastapi import APIRouter, Body, FastAPI, File, UploadFile
from pydantic import BaseModel
from starlette.requests import Request
app = FastAPI()
router = APIRouter()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
class User(BaseModel):
username: str
full_name: str = None
@router.put("/items/{item_id}")
async def update_item(
item_id: int, item: Item, user: User, importance: int = Body(...)
):
results = {"item_id": item_id, "item": item, "user": user, "importance": importance}
return results
@router.post("/uploadfile")
def get(request: Request, file: UploadFile = File(...)):
filename_parts = file.filename.split(".")
file = file.file.read()
if filename_parts[-1] == "xlsx":
file = base64.b64encode(file)
return {"file": file}
app.include_router(router)Run the test file using the FastAPI virtual environment~/dev/fastapi-1523
❯ . ~/dev/fastapi/env/bin/activate
~/dev/fastapi-1523
env ❯ uvicorn main:app --reloadCheck the OpenAPI schemaServer output: OpenAPI JSON: # HTTPie: https://httpie.org/
~
❯ http -h :8000/openapi.json
HTTP/1.1 200 OK
content-length: 2497
content-type: application/json
date: Sat, 13 Jun 2020 19:38:10 GMT
server: uvicornI even tried uploading a sample .xlsx file through the Swagger UI. FastAPI returns a |
Beta Was this translation helpful? Give feedback.
-
|
read the traceback so please check your middleware |
Beta Was this translation helpful? Give feedback.
-
|
thank you @ihakh and @br3ndonland for looking into this. I'll look into our middleware and will close this for now. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the help here everyone! 👏 🙇 Thanks for reporting back and closing the issue @speizerj 👍 |
Beta Was this translation helpful? Give feedback.
-
|
@speizerj can you please update how did you solve this issue ? |
Beta Was this translation helpful? Give feedback.
-
|
@ankurRakuten it was a bug within our custom middleware that was causing the issue, not with fastapi |
Beta Was this translation helpful? Give feedback.
-
|
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs. |
Beta Was this translation helpful? Give feedback.


@ankurRakuten it was a bug within our custom middleware that was causing the issue, not with fastapi