Sling Academy
Home/FastAPI/3 Ways to Get User’s IP Address in FastAPI

3 Ways to Get User’s IP Address in FastAPI

Last updated: April 24, 2023

When building backend applications with FastAPI, you may need to get the IP addresses of your users for several purposes, such as:

  • Geolocation: With an IP address, you can determine the user’s location, which can be useful for providing location-specific content or services.
  • Security: By logging IP addresses, you can detect and prevent unauthorized access to your application or website. You can also use IP addresses to identify potential security threats or suspicious activity.
  • Analytics: Knowing the IP address of your users can help you track and analyze traffic to your application or website, including user behavior and preferences.

This quick article shows you a couple of different ways to get the IP address of a user with FastAPI.

Using Request Client Host

Example:

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/")
async def read_root(request: Request):
    client_host = request.client.host
    return {"client_host": client_host}

If your FastAPI project is running in localhost, the IP will be 127.0.0.1:

request.client will work well in the vast majority of cases unless you’re running behind a proxy. In that situation, you use uvicorn’s –proxy-headers flag to accept these incoming headers and make sure the proxy forwards them.

Using headers

You can use Header dependencies to access the X-Forwarded-For and X-Real-IP headers like so:

from fastapi import FastAPI, Depends, Header
app = FastAPI()


@app.get('/')
def home_route(
    x_forwarded_for: str = Header(None, alias='X-Forwarded-For'),
    x_real_ip: str = Header(None, alias='X-Real-IP')
):
    return {"X-Forwarded-For": x_forwarded_for, "X-Real-Ip": x_real_ip}

The disadvantage of this approach is that these headers are not always reliable and can be spoofed by malicious clients. The result can also be null if the client is not sending the headers in the request.

Using information provided by Cloudflare

If your FastAPI application uses Cloudflare then you can easily get information about a user’s IP address, city, and country using the following headers: CF-Connecting-IP, CF-IPCity, and CF-IPCountry, respectively.

Example:

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/")
async def read_root(request: Request):
   # Get user ip, city and country provided by Cloudflare
   user_ip = request.headers.get('CF-Connecting-IP')
   city = request.headers.get('CF-IPCity')
   country = request.headers.get('CF-IPCountry')

This data is provided by Cloudflare for all plans, including the free one. Note that In some rare cases, information about a user’s city or country may be missing.

Next Article: FastAPI: How to Change the Response Status Code

Previous Article: FastAPI: How to extract request headers (2 approaches)

Series: FastAPI Request & Response Tutorials

FastAPI

You May Also Like

  • Popular useful built-in Jinja filters you should know
  • How to remove consecutive whitespace in rendered Jinja pages
  • How to format large numbers with thousand separators in Jinja template
  • How to format date time in Jinja templates
  • FastAPI + Jinja: How to create custom filters
  • How to pass variables from Python (FastAPI) to Jinja
  • How to decode Jinja response to string
  • How to create and use macros in Jinja
  • How to use namespace in Jinja
  • How to use if/ else in Jinja
  • How to use loops in Jinja
  • FastAPI + SQLAlchemy: Using cursor-based pagination
  • FastAPI: How to use macros in Jinja templates
  • Fixing Common Swagger UI Errors in FastAPI
  • FastAPI Error: 307 Temporary Redirect – Causes and Solutions
  • FastAPI Error: Expected UploadFile, received ‘str’
  • Resolving FastAPI ImportError: No Known Parent Package
  • FastAPI Error: No module named ‘pydantic_core._pydantic_core’
  • Resolving FastAPI 422 Error: Value is not a valid dict