4

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!

jpjenk
  • 459
  • 2
  • 8
  • 14

2 Answers2

3

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)
Matthew Hegarty
  • 3,791
  • 2
  • 27
  • 42
  • 1
    You should probably use a permalink, which you can get by pressing `y` on a GitHub page: https://help.github.com/articles/getting-permanent-links-to-files/#press-y-to-permalink-to-a-file-in-a-specific-commit – luckydonald Sep 25 '20 at 23:05
1

For example

async def user_login(request: Request) -> JSONResponse:

    try:
        payload = await request.json()
    except JSONDecodeError:
        sprint_f('cannot_parse_request_body', 'red')
        raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="cannot_parse_request_body")
    email = payload['email']
    password = payload['password']