For request-specific IP geolocation in FastAPI, use a typed dependency declared only on the routes that need a location. Middleware runs for every request, so a lookup placed there adds work to health checks, documentation pages, metrics endpoints, CORS preflight requests, and any route that never reads the result. The dependency approach keeps the lookup opt-in, and it is easier to test and reason about.
Why middleware is the wrong place for a lookup
FastAPI’s middleware documentation describes middleware as code that runs for each request before the path operation handles it, and again around the response on the way out (FastAPI middleware tutorial). That broad scope is the point of middleware: it suits cross-cutting work such as timing headers or request IDs. It is a poor fit for an IP lookup, because the lookup then becomes global unless you write your own rules to skip paths.
As an Amazon Associate I earn from qualifying purchases.
Those rules are easy to get wrong. A geolocation call that runs for /health, /docs, and a Prometheus scrape endpoint spends a network round trip or a database read on requests whose answer nobody uses. It also runs before routing has decided which handler will respond, so the middleware cannot see which endpoint declared a need for location.
The practitioner argument behind this article, from Abdullah Afzal’s post Why FastAPI geolocation middleware is the wrong tool, makes the same point in one line: a dependency runs after routing, and only where you declare it. The post is a single author’s argument rather than a benchmark, so treat its claims as reasoning to evaluate, not measured results.
#1 Best Overall
- Real-Time Location Tracking with No Monthly Fees: Keep track of what matters most without any hidden costs. This GPS locator uses the SeekTag app to show your item's real-time location on your phone. There are no subscriptions and no SIM card required, making it a cost-effective tracking solution for your auto, motorcycle, truck, or trailer. You can track over a long distance with peace of mind.
- Universal Compatibility for Both iOS and Android: Whether you use an iPhone or an Android phone, this smart tracker works seamlessly for everyone. Simply download the free SeekTag application, pair the device via wireless Bluetooth connection, and you're ready to start tracking. It's the perfect personal equipment for families with mixed phone types.
- Compact, Durable Design with Multiple Attachments: Despite its powerful tracking capabilities, this device is remarkably small, tiny, and portable. The included magnetic mount securely attaches to metal surfaces, while the keychain allows for easy attachment to dog collars, kid backpacks, or luggage. With an IP65 rating, it's protected against dust and water splashes, ready for any adventure.
- Versatile Tracking for Your Valuables, Pets, and People: This isn't just for cars. Use it as a pet tracker to monitor your dogs & cats` location, a child locator for your children's safety, or an item finder for your bags and valuables. Its long range and tiny size make it an incredibly versatile tool for protecting your people and possessions from being lost.
- Reliable and Discreet for Long-Term Use: Engineered for reliability, this locator is designed for long-term use. Its efficient power management ensures a long battery life up to 360 days, providing extended tracking without frequent replacement battery. The small and undetectable design allows for discreet placement on your auto or other personal items, offering a reliable security solution.
What a route dependency gives you
A FastAPI dependency is a function that FastAPI calls for each request to a route that declares it with Depends(). Because the dependency sits in the route signature, three things follow:
- Opt-in scope. Only routes that list the dependency pay for the lookup. Health checks and documentation stay untouched.
- A typed return value. The dependency returns a model your handler can type-check, instead of a value tucked into
request.statethat every handler must know to read. - Overrides in tests. You can replace the dependency in tests so that route logic runs against a fixed location without contacting a provider.
The author also notes request-level caching, meaning a dependency used several times within one request is resolved once. That is a claim from the post and is worth confirming against the FastAPI dependency documentation for the version you run.
Rank #2
- FIND YOUR ITEMS ON FIND MY — AirTag (2nd generation) helps you keep track of what matters. Attach one to an item you want to keep track of using the Find My app.*
- EXPANDED PRECISION FINDING ON IPHONE AND APPLE WATCH — Get step-by-step directions to your lost item on iPhone and, now, Apple Watch.*
- ENHANCED SPEAKER — With a 50% louder speaker and a new, distinctive chime, it’s easier than ever to hear and find AirTag.*
- PING FROM FAR AND WIDE — Upgraded Ultra Wideband and Bluetooth chips allow you to find your items from even farther away than ever before.*
- SHARE ITEM LOCATION — Share AirTag location access temporarily and securely with trusted contacts, third parties, or over 50 airline partners if you lose something important.
A minimal sketch
The example below shows only the wiring. The function body reads the client address and returns a model; you would call your chosen lookup source where the comment indicates.
from fastapi import Depends, FastAPI, Request
from pydantic import BaseModel
class Location(BaseModel):
ip: str | None
country_code: str | None = None
def get_location(request: Request) -> Location:
ip = request.client.host if request.client else None
# Call your lookup source here, after the client IP is trusted.
return Location(ip=ip)
app = FastAPI()
@app.get("/pricing")
def pricing(location: Location = Depends(get_location)):
return {"country": location.country_code}
@app.get("/health")
def health():
return {"status": "ok"}
Notice that /health does not declare the dependency, so it never triggers a lookup.
Rank #3
- Premium GPS Tracker — The LandAirSea 54 GPS tracker provides accurate global location, real-time alerts, and geofencing. Easily attaches to vehicles, ATVs, golf carts, or other critical assets.
- Track Movements in Real-Time — Track and map (with Google Maps) in real-time on web-based software or our SilverCloud App. Location updates as fast as every 3 seconds with historical playback for up to 1 year.
- Powerful & Discreet — The motion-activated GPS tracker will sleep when not in motion for extended periods, preserving the battery life. The ultra-compact design and internal magnet create the ultimate discreet tracker.
- Lifetime Warranty — This GPS tracker is built to last. LandAirSea, a USA-based company and pioneer in GPS tracking offers a unconditional lifetime warranty that covers any manufacturing defects in the device encountered during normal use.
- Subscription Required — Affordable subscription plans are required for each device. Fees start as low as $9.95 a month for annual plans and $19.95 for monthly plans. No contracts, cancel anytime for a hassle-free experience.
Resolve the client IP before you look it up
Most production FastAPI apps sit behind a load balancer, reverse proxy, or CDN. In that setup, request.client.host often holds the proxy’s address, not the visitor’s. Forwarded headers such as X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Host carry the original values, and FastAPI’s proxy documentation explains that these headers are not trusted by default (FastAPI behind a proxy).
The reason is security. The FastAPI documentation puts it this way: “But for security, as the server doesn’t know it is behind a trusted proxy, it won’t interpret those headers.” If the server accepted any caller-supplied forwarding value, a client could claim any address it liked and receive a location that does not match its real network origin.
Rank #4
- LONG-BATTERY VEHICLE TRACKING – Built for cars, trailers, fleets, equipment, boats, and motorcycles, Tracki’s trailer GPS tracker uses a 10,000mAh battery for 2 to 7 months active at 1–5 minute updates or up to 12 months in sleep mode.
- SUBSCRIPTION-POWERED SERVICE – The Tracki GPS tracker connects through 4G LTE Cat1 with built-in global SIM, giving app access, real-time location updates, alerts, and support after activation; Subscription Required, Cancel Anytime.
- FLEET-WIDE CONTROL – A practical fleet GPS tracker for work vehicles, with subscription-powered 15-second to 1-minute updates plus speed, geofence, movement, idle time, impact, and battery alerts through SMS, email, and app notifications.
- TRAILER & ASSET COVERAGE – A GPS tracker for trailer, car, truck, RV, boat, or equipment use, with 185+ country coverage, GPS accuracy of 5 to 10 meters outdoors, and Wi-Fi fallback indoors when GPS signals are harder to reach.
- SECURE TWO-WHEEL MONITORING – Use this motorcycle tracker for authorized bikes and powersport assets, with a built-in strong magnet, included screw mount, and weatherproof design for flexible vehicle placement.
Steps to establish a trustworthy client address
- List the network peers that really forward traffic to your application: your load balancer, reverse proxy, or CDN addresses.
- Configure the ASGI server’s trust list to match those peers only. For Uvicorn, the FastAPI documentation covers the
--forwarded-allow-ipsoption; check your server’s default and set it explicitly rather than relying on it. - Read the client address from the server’s processed request metadata, which is
request.client.hostonce forwarded headers are accepted from trusted peers, not from a raw header you parse yourself. - Avoid a permissive setting such as trusting all addresses unless the application can only receive traffic from the trusted proxy. If the port is reachable directly from the internet, a wildcard trust list lets any client forge its address.
- Confirm the result by sending a request through the real proxy chain and logging what the handler sees. Do this in staging with the same proxy configuration you run in production.
Where TLS terminates also matters for the forwarded protocol value. FastAPI’s HTTPS deployment guide covers the HTTPS side of that setup (FastAPI HTTPS deployment).
Recommended Free Tools
Choose a lookup source after the IP is trusted
Once you have a trustworthy address, you need a way to map it to a location. Two broad options exist. MaxMind documents hosted GeoIP web-service endpoints for country, city, and insights lookups, and these require authorization credentials (MaxMind GeoIP web service requests). A local database, which your application queries without a network call to a provider, is the other architecture.
Best Value
- 【Dual-System Compatibility】Our car tracker tags work seamlessly with both iOS and Android systems, covering mainstream devices. This Bluetooth tracking device pairs effortlessly with Apple's “Find My” or Google's “Find Hub” app without subscription fees. (Note: Cannot pair with iOS and Android devices simultaneously.)
- 【Real-time Undetectable GPS tracker】Our small vehicle tracker GPS allows global tracking and location. When there are a large number of iOS & Android devices nearby, location updates are very accurate and happen in real time, recording the location of your item at any time.
- 【Car Tracker No Subscription】The GPS trackers no subscription required or monthly fees. You can use it for a long time with just a one - time purchase. Our smart item finders locator also suitable for tracking pets, vehicles, keys, the elderly and children.
- 【High-Volume Alert】Close-Range Search—The app displays the distance to lost items to narrow your search area. Trigger an 80-100 decibel alert from the built-in speaker via Google Find Hub or Apple's Find My app—ideal for locating items in cluttered spaces like sofa crevices or drawers. Even if the item is out of sight, a single button press activates the item finders' alert.
- 【Simple Setup】This location tracker for Android or iOS pairs effortlessly with Android or iOS devices in seconds, automatically adapting to your chosen platform (connects to only one platform at a time). An instruction manual is included. If you're concerned about understanding it, you can watch the video tutorial on our page.
| Factor | Hosted lookup API | Local geolocation database |
|---|---|---|
| Request latency | Adds a network call per lookup; not measured in the cited sources | In-process or local read; not measured in the cited sources |
| Availability | Depends on the provider and your network path | Depends on your own file or service being present |
| Credentials and cost | Requires authorization credentials; pricing not stated in the cited sources | Packaging and licensing not stated in the cited sources |
| Updates | Handled by the provider | You must refresh the data; update cadence not stated in the cited sources |
| Data handling | Client IP addresses are sent to a third party | IP addresses stay inside your infrastructure |
The cited sources confirm the endpoint types and the credential requirement, but they do not provide benchmarks, pricing, or update schedules. Check each provider’s current terms and documentation before you choose.
How precise is IP location?
IP geolocation estimates where an address is registered or routed. It does not identify a person, a household, or a street address. VPNs, mobile carriers, and other address assignments can place a visitor far from where they are. MaxMind’s support pages state these limits and publish accuracy figures for its GeoIP products (MaxMind geolocation accuracy; MaxMind IP geolocation data). These are the vendor’s own estimates, not independent evaluations:
- About 99.8% country-level accuracy.
- About 80% accuracy for U.S. state or region.
- About 66% accuracy for U.S. city within a 50 km radius.
The support page does not show a publication year for these figures, so treat them as current vendor estimates without a dated baseline.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →In practice, that means country-level personalization such as currency or language defaults is a reasonable use. City-level decisions deserve a fallback, and no decision that grants or denies access should rest on IP location alone.
Handle missing and low-confidence results
- A missing client address, an unknown range, or a lookup timeout should return a null or unknown location, not an error that breaks the route, unless the route truly cannot function without it.
- Store the precision you received, not just the city name, so downstream code can choose a country-level default instead of a city-level guess.
- Log lookups without storing raw addresses longer than your privacy policy allows, especially when a third-party provider receives them.
Decision checklist
- Does the route need location to produce its response? If not, do not declare the dependency.
- Is the proxy chain configured so the client address is read from trusted peers only?
- Would a country-level answer be enough for this decision?
- Can the handler continue when the lookup returns nothing?
- Have you decided whether a hosted provider or a local database is acceptable for your data-handling obligations?
Where middleware still belongs
This is not an argument against middleware in general. Middleware remains the right place for work that every request must receive, such as adding security headers, measuring timing, or assigning request IDs. The mistake is using it for a value that only some handlers consume and that depends on a trust decision made by the infrastructure.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




