[BUG] Body is always parsed as JSON regardless of media_type
See original GitHub issueDescribe the bug
This is to continue the discussion at https://github.com/tiangolo/fastapi/issues/579#issuecomment-589263249. Body
accepts an argument media_type
, but regardless of the media_type Body is parsed as JSON. This is a problem for other media_types such as plain/text
, application/sql
, etc. And this is not compliant to OpenAPI content. Body should be able to represent plain text as str
too.
Basically I wish I could do this:
request: str = Body(..., media_type='text/plain')
However, this produces 400 parsing error because Body is parsed as JSON anyway.
To Reproduce
- Create a file with:
from fastapi import FastAPI, Body
app = FastAPI()
@app.post("/")
def read_root(body: str = Body(..., media_type='text/plain')):
return {"I received:": body}
-
Run the server.
-
Then execute:
curl -d 'I want to print this' -H 'Content-Type: plain/text' http://localhost:8000
-
It returns {“detail”:“There was an error parsing the body”}
-
But I expected it to return
{"I received": "I want to print this"}
.
Expected behavior
My expectation is that the Body should be parsed based on the Content-Type header always.
Screenshots
I think the information is quite comprehensive without screenshots.
Environment
- OS: Ubuntu 18.04
- FastAPI Version: 0.49.0
- Python 3.7.4
Additional context
The associated part is: https://github.com/tiangolo/fastapi/blob/9c3c9b6e78768374868d690bc05918d58481e880/fastapi/routing.py#L114
This does not check Content-Type. My proposal is to fix it as
if body_bytes and request.headers['Content-Type'] == 'application/json':
# if body_bytes and request.headers.get('Content-Type', 'application/json'): # if the content type should be assumed.
body = await request.json()
else:
body = body_bytes
I can make a PR for this, but I would like to learn the maintainers’ opinion on this. @tiangolo @dmontagu @phy25, thanks for the great project!
Issue Analytics
- State:
- Created 4 years ago
- Reactions:22
- Comments:21 (2 by maintainers)
Top GitHub Comments
Any update on the fix for this? I’d love to be able to get my API docs to include the request body documentation for
text/plain
POST
endpoints. 😃Is there any other way to document the request body in OpenAPI documentation, besides
Body(...)
?I have a legacy service that I am porting to FastAPI, and one of the operations accepts a YAML body. I am happy to parse it myself using the raw request, but I do not see any way to express that a) this operation accepts a body, or b) that the body should be
application/yaml
.Most of the users of my service use the Swagger UI directly, so not being able to enter the body for the request there would be a huge problem for them.