Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump http "Content-type: application/json;" in FastAPI [duplicate]

I will write a python script that listen to a webhook for a custom tool that will send json(They might support other format also) on a port I can specify.

How to write something similar to linux command: "nc -l 9000" to dump the out put I get on that port (header and body)?

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    print()  <- how to get the data here?
    return {"message": "ok"}

I want to print the content in the terminal, then I can easy see what I will get and take action on it. Not sure what I should replay to them if that is even needed (need to check this, they are not done with their part yet).

like image 484
olle.holm Avatar asked Sep 09 '25 14:09

olle.holm


1 Answers

So i think you are looking for Request.

This contains a lot of information (including, Body, Form, Headers etc.) about the request.

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/")
def read_root(request: Request):
    print(request.headers)
    return {}

So now if i send a request to this endpoint this 'll return me

{
    "host":"127.0.0.1:8000",
    "connection":"keep-alive",
    "accept":"application/json",
    "sec-fetch-site":"same-origin",
    "sec-fetch-mode":"cors",
    "sec-fetch-dest":"empty",
    "referer":"http://127.0.0.1:8000/docs",
    "accept-encoding":"gzip, deflate, br",
    "accept-language":"en-US,en;q=0.9,tr;q=0.8",
    "cookie":"csrftoken=sdf6ty78uewfıfehq7y8fuq; _ga=GA.1.11242141,1234423"
}

Then you can extract the accept from request.headers

If you only need that, you can also do

@app.get("/")
def read_root(request: Request):
    print(request.headers['accept'])
    return {}

This will return only

Out: application/json
like image 137
Yagiz Degirmenci Avatar answered Sep 12 '25 03:09

Yagiz Degirmenci