Using FastAPI in a sync, not async mode, I would like to be able to receive the RAW, unchanged body of a post request.
All examples I can find show async code, when I try it in a normal sync way, the request.body() shows uo as a coroutine object.
And when I test it by posting some XML to this endpoint, I get a 500 "Internal Server Error"
from fastapi import FastAPI, Response, Request, Body
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/input")
def input_request(request: Request):
# how can I access the RAW request body here?
body = request.body()
# do stuff with the body here
return Response(content=body, media_type="application/xml")
Is this not possible with FastAPI?
Note: a simplified input request would look like
POST http://127.0.0.1:1083/input
Content-Type: application/xml
<XML>
<BODY>TEST</BODY>
</XML>
and I have no control over how input requests are sent, because I need to replace an existing SOAP API
If an object is co-routine, it needs to be awaited. FastAPI is based on Starlette, and Starlette methods for returning the body of the request are async methods; thus, you need to "await" them.
Alternatively, if you are confident that the incoming data is a valid JSON, you can use the Body field, as below:
@app.post("/input")
def input_request(payload: dict = Body(...)):
return payload
If, however, the incoming data is in XML format, as in the example you provided, it might be best to pass them via files instead (as below), using a tempfile module in your client.
@app.post("/input")
def input_request(file: bytes = File(...)):
return file