0
0
FastapiHow-ToBeginner · 3 min read

How to Get Client IP in FastAPI: Simple Guide

In FastAPI, you can get the client IP by accessing the request.client.host property from the Request object. For apps behind proxies, check the X-Forwarded-For header to get the original client IP.
📐

Syntax

Use the Request object from fastapi to access client information. The key parts are:

  • request.client.host: Gives the direct client IP address.
  • request.headers.get('X-Forwarded-For'): Checks for the original IP if behind a proxy.
python
from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/")
async def get_ip(request: Request):
    client_ip = request.client.host
    forwarded_for = request.headers.get('X-Forwarded-For')
    return {"client_ip": client_ip, "forwarded_for": forwarded_for}
💻

Example

This example shows a FastAPI app endpoint that returns the client's IP address. It first tries to get the IP from the X-Forwarded-For header, which proxies set, and falls back to request.client.host if the header is missing.

python
from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/client-ip")
async def client_ip(request: Request):
    x_forwarded_for = request.headers.get('X-Forwarded-For')
    if x_forwarded_for:
        ip = x_forwarded_for.split(",")[0].strip()
    else:
        ip = request.client.host
    return {"client_ip": ip}
Output
{"client_ip": "127.0.0.1"}
⚠️

Common Pitfalls

Many developers forget that when running behind proxies or load balancers, request.client.host shows the proxy IP, not the real client IP. Always check the X-Forwarded-For header first.

Also, the X-Forwarded-For header can contain multiple IPs separated by commas; the first one is usually the original client IP.

python
from fastapi import FastAPI, Request

app = FastAPI()

# Wrong approach: ignoring proxy headers
@app.get("/wrong-ip")
async def wrong_ip(request: Request):
    return {"client_ip": request.client.host}

# Correct approach: checking X-Forwarded-For
@app.get("/correct-ip")
async def correct_ip(request: Request):
    x_forwarded_for = request.headers.get('X-Forwarded-For')
    if x_forwarded_for:
        ip = x_forwarded_for.split(",")[0].strip()
    else:
        ip = request.client.host
    return {"client_ip": ip}
📊

Quick Reference

  • request.client.host: Direct client IP from connection.
  • X-Forwarded-For header: Original client IP when behind proxies.
  • Always parse X-Forwarded-For carefully; it may contain multiple IPs.
  • Use strip() to clean IP strings.

Key Takeaways

Use request.client.host to get the client IP in FastAPI.
Check the X-Forwarded-For header to get the real client IP behind proxies.
The X-Forwarded-For header may contain multiple IPs; use the first one.
Always handle missing headers gracefully by falling back to request.client.host.
Parsing IPs carefully avoids mistakes when proxies are involved.