What is the equivalent FastApi way to do request.json() as in Flask

Viewed 1280

In Flask,requests from client can be handled like this For JSON Data

payload = request.get_json()

For token arguments

token = request.headers.get('Authorization')

For arguments

id = request.args.get('url', None)

What is the FastApi way of doing the same?

1 Answers

You can call the .json() method of Request class as,

from json import JSONDecodeError
from fastapi import FastAPI, Request

app = FastAPI()


@app.post("/")
async def root(request: Request):
    try:
        payload_as_json = await request.json()
        message = "Success"
    except JSONDecodeError:
        payload_as_json = None
        message = "Received data is not a valid JSON"
    return {"message": message, "received_data_as_json": payload_as_json}
Related