2

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?

Chris
  • 18,724
  • 6
  • 46
  • 80
DP9
  • 61
  • 1
  • 8
  • 1
    Does this answer your question? [FastAPI: how to read body as any valid json?](https://stackoverflow.com/questions/64379089/fastapi-how-to-read-body-as-any-valid-json) – Yagiz Degirmenci Feb 10 '21 at 07:28
  • Please have a look at the answers [here](https://stackoverflow.com/a/70636163/17865804) and [here](https://stackoverflow.com/a/73761724/17865804). – Chris Feb 14 '23 at 06:54

1 Answers1

9

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}
JPG
  • 82,442
  • 19
  • 127
  • 206