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?
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}