[Python] Using FastAPI in a sync way, how can I get the raw body of a POST request?

Discussão em 'Python' iniciado por Stack, Março 30, 2025.

  1. Stack

    Stack Membro Participativo

    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 up as a coroutine object.

    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.

    Continue reading...

Compartilhe esta Página