I am trying to access the client IP inside FastAPI path operation function like in the documentation here: https://fastapi.tiangolo.com/advanced/using-request-directly/
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/items/{item_id}")
def read_root(item_id: str, request: Request):
client_host = request.client.host
return {"client_host": client_host, "item_id": item_id}
However, this results in the following error:
Exception: AttributeError: 'NoneType' object has no attribute 'host'
It seems that the request.client
returns None
. Starlette documentation says request.client
should be a named two-tuple. https://www.starlette.io/requests/
Any suggestions how to get access to the IP?