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

Question:

In Flask, requests from client can be handled as follows.

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?

Asked By: DP9

||

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}
Answered By: JPG
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.