Search code examples
python-3.xrestpayloadstarlette

How to handle JSON request body with the Starlette framework


I am moving my API framework from an older version of ApiStar to Starlette and am having trouble correctly accessing the HTTP body which, in this case, is a JSON payload, in the functions that I am routing to.

This is what was working for me with ApiStar:

from apistar import http
import json

def my_controller(body: http.Body):

    spec = json.loads(body)

    print(spec['my_key_1'])
    print(spec['my_key_2'])

Any help basically converting the above to the syntax used by Starlett would be very helpful as I was not able to figure it out from the documentation.

Thanks!


Solution

  • The Starlette tests have an example of reading JSON from a request.

        async def app(scope, receive, send):
            request = Request(scope)
            try:
                data = await request.json()
                print(data['my_key_1'])
            except RuntimeError:
                data = "Receive channel not available"
            response = JSONResponse({"json": data})
            await response(scope, receive, send)