Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access request object in router function using FastAPI?

Tags:

python

fastapi

I am new to FastAPI framework, I want to print out the response. For example, in Django:

@api_view(['POST'])
def install_grandservice(req):
    print(req.body)

And in FastAPI:

@app.post('/install/grandservice')
async def login():
   //print out req

I tried to to like this

@app.post('/install/grandservice')
async def login(req):
    print(req.body)

But I received this error: 127.0.0.1:52192 - "POST /install/login HTTP/1.1" 422 Unprocessable Entity

Please help me :(

like image 371
Minh Nguyen Avatar asked Jul 18 '26 07:07

Minh Nguyen


2 Answers

You can define a parameter with a Request type in the router function, as

from fastapi import FastAPI, Request

app = FastAPI()


@app.post('/install/grandservice')
async def login(request: Request):
    print(request)
    return {"foo": "bar"}

This is also covered in the doc, under Use the Request object directly section

like image 148
JPG Avatar answered Jul 22 '26 19:07

JPG


Here is an example that will print the content of the Request for fastAPI. It will print the body of the request as a json (if it is json parsable) otherwise print the raw byte array.

async def print_request(request):
    print(f'request header       : {dict(request.headers.items())}' )
    print(f'request query params : {dict(request.query_params.items())}')  
    try : 
        print(f'request json         : {await request.json()}')
    except Exception as err:
        # could not parse json
        print(f'request body         : {await request.body()}')


@app.post("/printREQUEST")
async def create_file(request: Request):
    try:
        await print_request(request)
        return {"status": "OK"}
    except Exception as err:
        logging.error(f'could not print REQUEST: {err}')
        return {"status": "ERR"}
like image 27
Etienne Salimbeni Avatar answered Jul 22 '26 19:07

Etienne Salimbeni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!