0

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?

juhat
  • 342
  • 2
  • 10
  • How are you running your application? Works as expected with FastAPI and uvicorn directly. – MatsLindh Nov 08 '22 at 13:36
  • @MatsLindh I''ve followed this tutorial to setup the application to run inside Azure function app: https://learn.microsoft.com/en-us/samples/azure-samples/fastapi-on-azure-functions/azure-functions-python-create-fastapi-app/ – juhat Nov 08 '22 at 13:47
  • 2
    Then it kind of sounds like an issue with how Azure functions integrate with the ASGI protocol, and not a FastAPI/Starlette issue directly. Have you seen https://demiliani.com/2022/07/11/azure-functions-getting-the-client-ip-address/ ? It might only be available through the `X–Forwarded-For` header. I'd inspect the whole `request` object to see what the Azure functions host includes. – MatsLindh Nov 08 '22 at 13:49
  • Thank you! `X-Forwarded-For` header did the trick after the app was deployed to Azure. – juhat Nov 08 '22 at 14:05

0 Answers0