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?

2

1 Answer 1

10

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.