Search code examples
pythonfastapix-forwarded-forstarlette

FastAPI (starlette) get client real IP


I have an API on FastAPI and i need to get the client real IP address when he request my page.

I'm ty to use starlette Request. But it returns my server IP, not client remote IP.

My code:

@app.post('/my-endpoint')
async def my_endpoint(stats: Stats, request: Request):
    ip = request.client.host
    print(ip)
    return {'status': 1, 'message': 'ok'}

What i'm doing wrong? How to get real IP (like in Flask request.remote_addr)?


Solution

  • request.client should work, unless you're running behind a proxy (e.g. nginx) in that case use uvicorn's --proxy-headers flag to accept these incoming headers and make sure the proxy forwards them.