internetdata-fastapi 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python: ['3.11', '3.12', '3.13', '3.14']
14
+ steps:
15
+ - uses: actions/checkout@v7
16
+ - uses: actions/setup-python@v7
17
+ with:
18
+ python-version: ${{ matrix.python }}
19
+ cache: pip
20
+ cache-dependency-path: pyproject.toml
21
+ - run: pip install -e ".[dev]"
22
+ - run: ruff check .
23
+ - run: ruff format --check .
24
+ - run: mypy src
25
+ - run: pytest
@@ -0,0 +1,63 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags: ['v*']
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ contents: read
12
+ # PyPI trusted publishing exchanges this OIDC token for a short-lived upload
13
+ # token. No API token in a repository secret.
14
+ id-token: write
15
+ steps:
16
+ - uses: actions/checkout@v7
17
+ - uses: actions/setup-python@v7
18
+ with:
19
+ python-version: '3.13'
20
+ cache: pip
21
+ cache-dependency-path: pyproject.toml
22
+ # The tag only TRIGGERS this; PyPI publishes whatever the built artifact says.
23
+ # Without this check, tagging v1.0.1 against a 1.0.0 package silently
24
+ # republishes 1.0.0, or fails as "already exists" with a confusing message.
25
+ - name: Tag must match the package version
26
+ run: |
27
+ tag="${GITHUB_REF_NAME#v}"
28
+ pkg="$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' src/internetdata_fastapi/__init__.py)"
29
+ if [ "$tag" != "$pkg" ] ; then
30
+ echo "tag $tag does not match __version__ $pkg" >&2
31
+ exit 1
32
+ fi
33
+ - run: pip install -e ".[dev]" build
34
+ - run: pytest
35
+ - run: python -m build
36
+ - uses: pypa/gh-action-pypi-publish@release/v1
37
+
38
+ # This version's section of CHANGELOG.md, as the tag's GitHub Release. It
39
+ # waits for the publish, so no release page names a version the registry
40
+ # cannot serve, and a re-run edits the release rather than failing on it.
41
+ github-release:
42
+ needs: publish
43
+ runs-on: ubuntu-latest
44
+ permissions:
45
+ contents: write
46
+ steps:
47
+ - uses: actions/checkout@v7
48
+ - name: GitHub Release from CHANGELOG.md
49
+ env:
50
+ GH_TOKEN: ${{ github.token }}
51
+ GH_REPO: ${{ github.repository }}
52
+ run: |
53
+ version="${GITHUB_REF_NAME#v}"
54
+ awk -v v="$version" '/^## /{ if (found) exit; found = ($2 == v); next } found' CHANGELOG.md > notes.md
55
+ if ! grep -q '^### ' notes.md ; then
56
+ echo "CHANGELOG.md has no section for ${version}" >&2
57
+ exit 1
58
+ fi
59
+ if gh release view "$GITHUB_REF_NAME" > /dev/null 2>&1 ; then
60
+ gh release edit "$GITHUB_REF_NAME" --notes-file notes.md
61
+ else
62
+ gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes-file notes.md --verify-tag
63
+ fi
@@ -0,0 +1,17 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+
4
+ # Build output.
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+
9
+ # Virtualenvs, including any made to run codegen. Keep them out of the tree entirely.
10
+ .venv/
11
+ venv/
12
+ .venv-*/
13
+
14
+ # Tool caches.
15
+ .pytest_cache/
16
+ .mypy_cache/
17
+ .ruff_cache/
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ What each release changed for you, newest first. Each line is a commit's summary, linked to its full description and diff.
4
+
5
+ ## 1.0.0 - 2026-11-14
6
+
7
+ ### Features
8
+
9
+ - Attach the visitor's InternetData record to every request, read with `lookup(request)`, as pure ASGI middleware for FastAPI, Starlette and Litestar: the location, the network and the company behind the address, and the anonymity and hosting flags your plan serves ([`68f2916`](https://github.com/internetdata/sdk-python-fastapi/commit/68f2916e9dc33f397747eec3375d08b2f4911f33))
10
+ - Refuse a request with a `block_condition` written in the shape of a result, by country, network type, anonymity or any other member, with 403 or an `on_blocked` of your own ([`68f2916`](https://github.com/internetdata/sdk-python-fastapi/commit/68f2916e9dc33f397747eec3375d08b2f4911f33))
11
+ - Refuse one FastAPI endpoint, router or app with the `block_if` dependency, judging the answer the middleware already attached ([`68f2916`](https://github.com/internetdata/sdk-python-fastapi/commit/68f2916e9dc33f397747eec3375d08b2f4911f33))
12
+ - Choose where the client address comes from: `request.client.host` by default, `xff_ip_selector`, `header_ip_selector` for a header your edge writes, or a callable of your own ([`68f2916`](https://github.com/internetdata/sdk-python-fastapi/commit/68f2916e9dc33f397747eec3375d08b2f4911f33))
13
+ - Fail open on any lookup failure unless `fail_closed` is set, with a 2.5 s bound, no retry and a cache by default ([`68f2916`](https://github.com/internetdata/sdk-python-fastapi/commit/68f2916e9dc33f397747eec3375d08b2f4911f33))
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mslm Dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.5
2
+ Name: internetdata-fastapi
3
+ Version: 1.0.0
4
+ Summary: Official FastAPI and Starlette middleware for the InternetData API. Look up the visitor behind every request: location, network, VPN, proxy, Tor and hosting.
5
+ Project-URL: Homepage, https://internetdata.io
6
+ Project-URL: Source, https://github.com/internetdata/sdk-python-fastapi
7
+ Author-email: Mslm Dev <support@internetdata.io>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: asn,fastapi,geoblocking,hosting,internetdata,ip-geolocation,ip-intelligence,ip-lookup,middleware,proxy-detection,tor,vpn-detection
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Internet
19
+ Classifier: Topic :: Security
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: internetdata<3,>=2.12.0
23
+ Requires-Dist: starlette>=0.37
24
+ Provides-Extra: dev
25
+ Requires-Dist: fastapi>=0.115; extra == 'dev'
26
+ Requires-Dist: mypy>=1.11; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Requires-Dist: ruff>=0.6; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # [<img src="https://s3.internetdata.io/internetdata-public/brand/mark.svg" alt="InternetData" height="28"/>](https://internetdata.io/) InternetData FastAPI Middleware
32
+
33
+ [![PyPI](https://img.shields.io/pypi/v/internetdata-fastapi.svg)](https://pypi.org/project/internetdata-fastapi/)
34
+ [![license](https://img.shields.io/pypi/l/internetdata-fastapi.svg)](LICENSE)
35
+
36
+ The official [FastAPI](https://fastapi.tiangolo.com) and [Starlette](https://www.starlette.io) middleware for the [InternetData](https://internetdata.io) API.
37
+
38
+ It looks up the visitor behind each request, where they are, which network they come from and whether it's a VPN, a proxy, Tor or a hosting server, and hands the answer to your endpoints. Blocking is opt-in.
39
+
40
+ ## Getting Started
41
+
42
+ ```bash
43
+ pip install internetdata-fastapi
44
+ ```
45
+
46
+ Requires Python 3.11 or newer.
47
+
48
+ Without an API key a lookup is on Unlimited, the free plan: the country, the network and the company behind the address, Tor, relay, anycast, carrier and satellite space and the service flags, with no daily or monthly cap. Every lookup your app makes comes from your server's one address, though, so a busy site will see bursts refused. A paid plan answers every field, VPN, the proxy flags, hosting, CDN and the city among them; create a key in the [console](https://app.internetdata.io). A free account tries every field, 100 lookups a day.
49
+
50
+ ```python
51
+ from fastapi import FastAPI
52
+ from internetdata_fastapi import InternetDataMiddleware
53
+
54
+ app = FastAPI()
55
+ app.add_middleware(InternetDataMiddleware, api_key=os.environ.get("INTERNETDATA_API_KEY"))
56
+ ```
57
+
58
+ Pure ASGI, so this works on Starlette and Litestar too, not only FastAPI.
59
+
60
+ ```python
61
+ from fastapi import Request
62
+ from internetdata_fastapi import lookup
63
+
64
+
65
+ @app.get("/")
66
+ async def index(request: Request):
67
+ found = lookup(request)
68
+ result = found.result if found else None
69
+ return {"country": result.location.country if result else None}
70
+ ```
71
+
72
+ By default nothing is blocked. Every request gets an answer and your own code decides what it means: a currency to show, a sign-up to review, a page to keep from some countries. A request your `skip` claims gets no answer, and `lookup(request)` is `None` for it.
73
+
74
+ ## Blocking
75
+
76
+ Pass a `block_condition` and a matching request is answered with `403` and never reaches your endpoints.
77
+
78
+ ```python
79
+ app.add_middleware(
80
+ InternetDataMiddleware,
81
+ api_key=os.environ.get("INTERNETDATA_API_KEY"),
82
+ block_condition={"location": {"country": ["CU", "IR", "KP"]}},
83
+ )
84
+ ```
85
+
86
+ A condition is written in the shape of a result, keyed by the same names the API uses, and only the members you name are considered, so it can refuse on anything in the answer. The country works on every plan, and so do the first two of these:
87
+
88
+ ```python
89
+ {"asn": {"type": "hosting"}} # the network's type
90
+ [{"is_anycast": True}, {"is_satellite": True}] # anycast and satellite space
91
+ [{"is_hosting": True}, {"is_cdn": True}] # traffic from servers, not people
92
+ [{"is_vpn": True}, {"is_tor": True}, {"is_resproxy": True}] # anonymity: a list is OR
93
+ {"is_vpn": True, "vpn": {"provider": "nordvpn"}} # one provider
94
+ {"resproxy": {"hits": {"gte": 5}}} # a numeric threshold
95
+ ```
96
+
97
+ Values are matched by equality, strings without regard to case. A list means any-of. A dict of `gte`/`gt`/`lte`/`lt` compares numbers, and every bound you give must hold, so two of them are a range. Members set to `False` or `None` are ignored, so a condition states the signals you act on; one that constrains nothing would match every request, and is refused when the middleware is built rather than silently blocking all your traffic.
98
+
99
+ Replace the refusal with `on_blocked`, which takes the request and the answer and returns a response, or awaits one:
100
+
101
+ ```python
102
+ app.add_middleware(
103
+ InternetDataMiddleware,
104
+ api_key=os.environ.get("INTERNETDATA_API_KEY"),
105
+ block_condition={"location": {"country": ["CU", "IR", "KP"]}},
106
+ on_blocked=lambda request, found: JSONResponse({"error": "not available"}, status_code=451),
107
+ )
108
+ ```
109
+
110
+ ### Blocking one endpoint
111
+
112
+ `block_condition` applies to every endpoint. In FastAPI, refuse a visitor on some endpoints only with the `block_if` dependency, on a path operation, a router or the app:
113
+
114
+ ```python
115
+ from fastapi import Depends
116
+ from internetdata_fastapi import block_if
117
+
118
+ embargoed = block_if({"location": {"country": ["CU", "IR", "KP"]}})
119
+
120
+
121
+ @app.get("/checkout", dependencies=[Depends(embargoed)])
122
+ async def checkout(): ...
123
+ ```
124
+
125
+ A refused request gets an `HTTPException`, `403` with `{"detail": "access denied"}` unless you pass `status_code` and `detail`. Declared as a parameter, the dependency hands the endpoint the answer. `block_if` takes the same condition, `fail_closed` and `on_missing_field`. It judges the answer the middleware already attached, so a visitor is looked up once however many endpoints check them, and it warns once for a member your plan doesn't include. A request `skip` claimed reaches the endpoint. The middleware still has to be added: without it, the dependency raises `RuntimeError` instead of letting everyone through.
126
+
127
+ ## Where the client address comes from
128
+
129
+ This is the setting that decides whether any of the above works, and it is the one thing only you can get right.
130
+
131
+ By default the middleware uses `request.client.host`. uvicorn, and `fastapi run` with it, reads proxy headers by default, but only from a peer that `--forwarded-allow-ips` trusts, and that defaults to `127.0.0.1,::1` (or `$FORWARDED_ALLOW_IPS`). So behind a proxy on the same machine, the visitor's address arrives with no setup. Behind one anywhere else, such as nginx in its own container or a load balancer in a VPC, every visitor looks like the proxy. That address is usually a private one, which the middleware answers locally, as an address with no country: nothing is blocked, and the private-address warning below is the only sign. Name your proxy, by its address or its subnet: `--forwarded-allow-ips=172.28.5.0/28`. gunicorn's own `--forwarded-allow-ips` works the same way. Never pass `*`. It trusts every peer, so the left-most `X-Forwarded-For` entry wins, and that is whatever the visitor sent: someone who sends `X-Forwarded-For: 1.1.1.1` is looked up as `1.1.1.1`.
132
+
133
+ For an edge that writes the address into its own header, name the header:
134
+
135
+ ```python
136
+ from internetdata_fastapi import header_ip_selector
137
+
138
+ app.add_middleware(
139
+ InternetDataMiddleware,
140
+ ip_selector=header_ip_selector("CF-Connecting-IP"), # or True-Client-IP, or your own
141
+ )
142
+ ```
143
+
144
+ `xff_ip_selector()` reads `X-Forwarded-For` directly. Be aware that the left-most entry is whatever the caller sent, because proxies append to that header, so it's only trustworthy when an edge you control overwrites it. If you know how many proxies sit in front, count from the right instead: `xff_ip_selector(1)` is the address your nearest proxy saw.
145
+
146
+ Anything else, pass your own callable. It receives the request and returns an address.
147
+
148
+ If the address resolves to a private one, the middleware says so once through the `internetdata` logger. That is expected on localhost and is the signal to fix your configuration anywhere else.
149
+
150
+ ## When a lookup fails
151
+
152
+ The request is let through, and the reason is recorded on the answer's `error`. Our outage should not become yours, so a network failure, a rate limit or a rejected key all fail open. Pass `fail_closed=True` to block instead. Private addresses are answered locally and never fail, so this will not lock you out in development.
153
+
154
+ ## Cost and latency
155
+
156
+ Answers are cached for an hour, so a returning visitor costs nothing, and private addresses never leave the process. A cache miss is one request to our API, bounded at 2.5 seconds by default and not retried: on a request path, failing open quickly beats holding a visitor while we try again. Both are adjustable with `timeout` and `retries`, and the cache through an `AsyncInternetData` client you build yourself and pass as `client`.
157
+
158
+ Skip what you do not care about:
159
+
160
+ ```python
161
+ app.add_middleware(
162
+ InternetDataMiddleware,
163
+ api_key=os.environ.get("INTERNETDATA_API_KEY"),
164
+ skip=lambda request: request.url.path.startswith("/static"),
165
+ )
166
+ ```
167
+
168
+ Beyond a few million distinct visitors a day, stop calling the API per request: look addresses up locally in [our databases](https://internetdata.io/databases) instead.
169
+
170
+ ## Absent is not false
171
+
172
+ Unlimited, with a key or without one, leaves out `is_vpn`, `is_hosting`, `is_cdn` and the four proxy flags, the detail behind them, and the paid members inside `location`, `asn`, `company` and `abuse`, such as `location.city`. A field your plan does not include is `None`, which means "not in your plan" rather than "checked, and no".
173
+
174
+ ```python
175
+ lookup(request).result.flagged("is_vpn") # False rather than None on a plan without it
176
+ ```
177
+
178
+ A `block_condition` naming a member your plan does not serve, `location.city` on Unlimited included, can never match, so the middleware warns once instead of failing silently. Pass `on_missing_field="raise"` to make it an error.
179
+
180
+ ## Other Libraries
181
+
182
+ There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.
183
+
184
+ ## About InternetData
185
+
186
+ Geolocation, anonymity, ownership and network data for IP addresses, AS numbers and domains, as an API and as databases you download and query yourself.
187
+
188
+ [<img src="https://s3.internetdata.io/internetdata-public/brand/mark.svg" alt="InternetData" height="64"/>](https://internetdata.io/)
189
+
190
+ ## License
191
+
192
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,162 @@
1
+ # [<img src="https://s3.internetdata.io/internetdata-public/brand/mark.svg" alt="InternetData" height="28"/>](https://internetdata.io/) InternetData FastAPI Middleware
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/internetdata-fastapi.svg)](https://pypi.org/project/internetdata-fastapi/)
4
+ [![license](https://img.shields.io/pypi/l/internetdata-fastapi.svg)](LICENSE)
5
+
6
+ The official [FastAPI](https://fastapi.tiangolo.com) and [Starlette](https://www.starlette.io) middleware for the [InternetData](https://internetdata.io) API.
7
+
8
+ It looks up the visitor behind each request, where they are, which network they come from and whether it's a VPN, a proxy, Tor or a hosting server, and hands the answer to your endpoints. Blocking is opt-in.
9
+
10
+ ## Getting Started
11
+
12
+ ```bash
13
+ pip install internetdata-fastapi
14
+ ```
15
+
16
+ Requires Python 3.11 or newer.
17
+
18
+ Without an API key a lookup is on Unlimited, the free plan: the country, the network and the company behind the address, Tor, relay, anycast, carrier and satellite space and the service flags, with no daily or monthly cap. Every lookup your app makes comes from your server's one address, though, so a busy site will see bursts refused. A paid plan answers every field, VPN, the proxy flags, hosting, CDN and the city among them; create a key in the [console](https://app.internetdata.io). A free account tries every field, 100 lookups a day.
19
+
20
+ ```python
21
+ from fastapi import FastAPI
22
+ from internetdata_fastapi import InternetDataMiddleware
23
+
24
+ app = FastAPI()
25
+ app.add_middleware(InternetDataMiddleware, api_key=os.environ.get("INTERNETDATA_API_KEY"))
26
+ ```
27
+
28
+ Pure ASGI, so this works on Starlette and Litestar too, not only FastAPI.
29
+
30
+ ```python
31
+ from fastapi import Request
32
+ from internetdata_fastapi import lookup
33
+
34
+
35
+ @app.get("/")
36
+ async def index(request: Request):
37
+ found = lookup(request)
38
+ result = found.result if found else None
39
+ return {"country": result.location.country if result else None}
40
+ ```
41
+
42
+ By default nothing is blocked. Every request gets an answer and your own code decides what it means: a currency to show, a sign-up to review, a page to keep from some countries. A request your `skip` claims gets no answer, and `lookup(request)` is `None` for it.
43
+
44
+ ## Blocking
45
+
46
+ Pass a `block_condition` and a matching request is answered with `403` and never reaches your endpoints.
47
+
48
+ ```python
49
+ app.add_middleware(
50
+ InternetDataMiddleware,
51
+ api_key=os.environ.get("INTERNETDATA_API_KEY"),
52
+ block_condition={"location": {"country": ["CU", "IR", "KP"]}},
53
+ )
54
+ ```
55
+
56
+ A condition is written in the shape of a result, keyed by the same names the API uses, and only the members you name are considered, so it can refuse on anything in the answer. The country works on every plan, and so do the first two of these:
57
+
58
+ ```python
59
+ {"asn": {"type": "hosting"}} # the network's type
60
+ [{"is_anycast": True}, {"is_satellite": True}] # anycast and satellite space
61
+ [{"is_hosting": True}, {"is_cdn": True}] # traffic from servers, not people
62
+ [{"is_vpn": True}, {"is_tor": True}, {"is_resproxy": True}] # anonymity: a list is OR
63
+ {"is_vpn": True, "vpn": {"provider": "nordvpn"}} # one provider
64
+ {"resproxy": {"hits": {"gte": 5}}} # a numeric threshold
65
+ ```
66
+
67
+ Values are matched by equality, strings without regard to case. A list means any-of. A dict of `gte`/`gt`/`lte`/`lt` compares numbers, and every bound you give must hold, so two of them are a range. Members set to `False` or `None` are ignored, so a condition states the signals you act on; one that constrains nothing would match every request, and is refused when the middleware is built rather than silently blocking all your traffic.
68
+
69
+ Replace the refusal with `on_blocked`, which takes the request and the answer and returns a response, or awaits one:
70
+
71
+ ```python
72
+ app.add_middleware(
73
+ InternetDataMiddleware,
74
+ api_key=os.environ.get("INTERNETDATA_API_KEY"),
75
+ block_condition={"location": {"country": ["CU", "IR", "KP"]}},
76
+ on_blocked=lambda request, found: JSONResponse({"error": "not available"}, status_code=451),
77
+ )
78
+ ```
79
+
80
+ ### Blocking one endpoint
81
+
82
+ `block_condition` applies to every endpoint. In FastAPI, refuse a visitor on some endpoints only with the `block_if` dependency, on a path operation, a router or the app:
83
+
84
+ ```python
85
+ from fastapi import Depends
86
+ from internetdata_fastapi import block_if
87
+
88
+ embargoed = block_if({"location": {"country": ["CU", "IR", "KP"]}})
89
+
90
+
91
+ @app.get("/checkout", dependencies=[Depends(embargoed)])
92
+ async def checkout(): ...
93
+ ```
94
+
95
+ A refused request gets an `HTTPException`, `403` with `{"detail": "access denied"}` unless you pass `status_code` and `detail`. Declared as a parameter, the dependency hands the endpoint the answer. `block_if` takes the same condition, `fail_closed` and `on_missing_field`. It judges the answer the middleware already attached, so a visitor is looked up once however many endpoints check them, and it warns once for a member your plan doesn't include. A request `skip` claimed reaches the endpoint. The middleware still has to be added: without it, the dependency raises `RuntimeError` instead of letting everyone through.
96
+
97
+ ## Where the client address comes from
98
+
99
+ This is the setting that decides whether any of the above works, and it is the one thing only you can get right.
100
+
101
+ By default the middleware uses `request.client.host`. uvicorn, and `fastapi run` with it, reads proxy headers by default, but only from a peer that `--forwarded-allow-ips` trusts, and that defaults to `127.0.0.1,::1` (or `$FORWARDED_ALLOW_IPS`). So behind a proxy on the same machine, the visitor's address arrives with no setup. Behind one anywhere else, such as nginx in its own container or a load balancer in a VPC, every visitor looks like the proxy. That address is usually a private one, which the middleware answers locally, as an address with no country: nothing is blocked, and the private-address warning below is the only sign. Name your proxy, by its address or its subnet: `--forwarded-allow-ips=172.28.5.0/28`. gunicorn's own `--forwarded-allow-ips` works the same way. Never pass `*`. It trusts every peer, so the left-most `X-Forwarded-For` entry wins, and that is whatever the visitor sent: someone who sends `X-Forwarded-For: 1.1.1.1` is looked up as `1.1.1.1`.
102
+
103
+ For an edge that writes the address into its own header, name the header:
104
+
105
+ ```python
106
+ from internetdata_fastapi import header_ip_selector
107
+
108
+ app.add_middleware(
109
+ InternetDataMiddleware,
110
+ ip_selector=header_ip_selector("CF-Connecting-IP"), # or True-Client-IP, or your own
111
+ )
112
+ ```
113
+
114
+ `xff_ip_selector()` reads `X-Forwarded-For` directly. Be aware that the left-most entry is whatever the caller sent, because proxies append to that header, so it's only trustworthy when an edge you control overwrites it. If you know how many proxies sit in front, count from the right instead: `xff_ip_selector(1)` is the address your nearest proxy saw.
115
+
116
+ Anything else, pass your own callable. It receives the request and returns an address.
117
+
118
+ If the address resolves to a private one, the middleware says so once through the `internetdata` logger. That is expected on localhost and is the signal to fix your configuration anywhere else.
119
+
120
+ ## When a lookup fails
121
+
122
+ The request is let through, and the reason is recorded on the answer's `error`. Our outage should not become yours, so a network failure, a rate limit or a rejected key all fail open. Pass `fail_closed=True` to block instead. Private addresses are answered locally and never fail, so this will not lock you out in development.
123
+
124
+ ## Cost and latency
125
+
126
+ Answers are cached for an hour, so a returning visitor costs nothing, and private addresses never leave the process. A cache miss is one request to our API, bounded at 2.5 seconds by default and not retried: on a request path, failing open quickly beats holding a visitor while we try again. Both are adjustable with `timeout` and `retries`, and the cache through an `AsyncInternetData` client you build yourself and pass as `client`.
127
+
128
+ Skip what you do not care about:
129
+
130
+ ```python
131
+ app.add_middleware(
132
+ InternetDataMiddleware,
133
+ api_key=os.environ.get("INTERNETDATA_API_KEY"),
134
+ skip=lambda request: request.url.path.startswith("/static"),
135
+ )
136
+ ```
137
+
138
+ Beyond a few million distinct visitors a day, stop calling the API per request: look addresses up locally in [our databases](https://internetdata.io/databases) instead.
139
+
140
+ ## Absent is not false
141
+
142
+ Unlimited, with a key or without one, leaves out `is_vpn`, `is_hosting`, `is_cdn` and the four proxy flags, the detail behind them, and the paid members inside `location`, `asn`, `company` and `abuse`, such as `location.city`. A field your plan does not include is `None`, which means "not in your plan" rather than "checked, and no".
143
+
144
+ ```python
145
+ lookup(request).result.flagged("is_vpn") # False rather than None on a plan without it
146
+ ```
147
+
148
+ A `block_condition` naming a member your plan does not serve, `location.city` on Unlimited included, can never match, so the middleware warns once instead of failing silently. Pass `on_missing_field="raise"` to make it an error.
149
+
150
+ ## Other Libraries
151
+
152
+ There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.
153
+
154
+ ## About InternetData
155
+
156
+ Geolocation, anonymity, ownership and network data for IP addresses, AS numbers and domains, as an API and as databases you download and query yourself.
157
+
158
+ [<img src="https://s3.internetdata.io/internetdata-public/brand/mark.svg" alt="InternetData" height="64"/>](https://internetdata.io/)
159
+
160
+ ## License
161
+
162
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,5 @@
1
+ # Security policy
2
+
3
+ Please report a security issue in this repository by email to support@internetdata.io, not in a public issue, pull request or discussion. Include what you found and the steps that reproduce it.
4
+
5
+ Keep any testing against the InternetData API to your own account and API key, and give us a reasonable chance to fix the issue before you publish it.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "internetdata-fastapi"
7
+ dynamic = ["version"]
8
+ description = "Official FastAPI and Starlette middleware for the InternetData API. Look up the visitor behind every request: location, network, VPN, proxy, Tor and hosting."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ authors = [{ name = "Mslm Dev", email = "support@internetdata.io" }]
14
+ keywords = ["internetdata", "ip-geolocation", "ip-intelligence", "ip-lookup", "geoblocking", "vpn-detection", "proxy-detection", "tor", "hosting", "asn", "middleware", "fastapi"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Internet",
24
+ "Topic :: Security",
25
+ "Typing :: Typed",
26
+ ]
27
+ dependencies = ["internetdata>=2.12.0,<3", "starlette>=0.37"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://internetdata.io"
31
+ Source = "https://github.com/internetdata/sdk-python-fastapi"
32
+
33
+ [project.optional-dependencies]
34
+ dev = ["pytest>=8", "mypy>=1.11", "ruff>=0.6", "fastapi>=0.115"]
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/internetdata_fastapi"]
38
+
39
+ [tool.hatch.version]
40
+ path = "src/internetdata_fastapi/__init__.py"
41
+
42
+ [tool.ruff]
43
+ line-length = 96
44
+
45
+ [tool.mypy]
46
+ python_version = "3.11"
47
+ strict = true