Skip to content
iplogs.comSign up
Guide · Last updated 2026-11-19

VPN, proxy, and Tor detection in Python

Calling the IPLogs API from Python takes a few lines. Most of this guide is about the rest of a production setup: calling /v1/check from a request handler, caching verdicts per IP, batching with /v1/bulk-check, handling failures, typing the response, and testing without the network. None of it needs an API key or signup.

By Mehmood Ali ·

How do you add VPN detection to a Python service?

Post the visitor's IP to https://iplogs.com/v1/check with requests or httpx and a 10-second timeout, slightly longer than the API's roughly 8-second probing ceiling. The call is free and needs no API key or sign-up. The response holds a verdict of clean, suspicious, vpn_likely or vpn_detected, a score, is_vpn, ip_info and the matched signals. In async stacks such as FastAPI, share one httpx.AsyncClient. Read the client IP through ProxyFix or the header your trusted proxy sets, never from the request body. Cache each verdict per IP for about five minutes with cachetools.TTLCache, or Redis across instances. On a timeout or server error, fail open and treat the result as unknown. For offline jobs such as fraud queues, send up to 100 addresses to /v1/bulk-check. Map verdicts to policy per action: block or step up authentication on writes for vpn_detected, step up for vpn_likely, and never hard-block read traffic. Test with responses or respx, so CI needs no network.

Quick start (requests)

The smallest version worth deploying is a POST to /v1/check with a ten-second timeout:

import requests

def check_vpn(ip: str) -> dict:
    r = requests.post(
        "https://iplogs.com/v1/check",
        json={"ip": ip},
        timeout=10.0,
    )
    r.raise_for_status()
    return r.json()

verdict = check_vpn("1.1.1.1")
print(verdict["verdict"], verdict["score"])
print(verdict["ip_info"]["org"])

The response contains verdict (one of clean, suspicious, vpn_likely, vpn_detected), score (0 to 1), is_vpn, an ip_info object with ASN, geo, and provider data, and a signals[] array listing each feed or probe that matched. The API docs have the full schema.

Async variant (httpx)

import httpx

# One client for the whole process, so connections are reused.
# Close it on shutdown: await _client.aclose()
_client = httpx.AsyncClient(base_url="https://iplogs.com", timeout=10.0)

async def check_vpn(ip: str) -> dict:
    r = await _client.post("/v1/check", json={"ip": ip})
    r.raise_for_status()
    return r.json()

Reach for httpx in an async stack such as FastAPI, Starlette, aiohttp handlers or Sanic. While the call is in flight (up to ten seconds), the worker can get on with other I/O instead of blocking the event loop. Create the client once, as above, and share it. A new client per call opens a fresh connection and TLS handshake every time.

Reading the visitor IP from a trusted proxy

Which header carries the client IP depends on what sits in front of your app. Caddy, Nginx, and Traefik populate X-Forwarded-For, Cloudflare uses CF-Connecting-IP, and many proxies also set X-Real-IP to the immediate peer. Anyone can send these headers, so only read them on requests that actually came through your proxy.

from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)
# x_for = how many proxies sit in front of the app (Nginx alone: 1;
# Cloudflare + Nginx: 2). ProxyFix reads that many entries from the right
# of X-Forwarded-For, so an address the client wrote itself is never used.
# Run it only behind those proxies: a direct request could forge the header.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)

def client_ip() -> str:
    return request.remote_addr or ""

Caching verdicts per IP

With a 5-minute per-IP cache, hot-path lookups take under a millisecond and far fewer requests go upstream. The key can be the bare IP string, because the verdict for an IP is deterministic at any given point in time.

from cachetools import TTLCache
import requests

_cache: TTLCache = TTLCache(maxsize=10_000, ttl=300)

def check_vpn_cached(ip: str) -> dict:
    if ip in _cache:
        return _cache[ip]
    r = requests.post(
        "https://iplogs.com/v1/check",
        json={"ip": ip},
        timeout=10.0,
    )
    r.raise_for_status()
    data = r.json()
    _cache[ip] = data
    return data

Running several instances? Point them all at Redis with the same 300-second TTL. A key prefix that changes per deploy would empty the cache on every release, so leave the key as the plain IP.

Retries and failure handling

/v1/check caps the heaviest IPs at around 8 seconds server-side, with a 30-second handler timeout behind that. We suggest a single 10-second client timeout, just above that ceiling: a new IP usually answers in about 2 seconds, but the slowest datacenter IPs take 5–7, and a shorter timeout would drop exactly those. On a timeout or a 5xx, fail open and allow the request instead of failing your own service:

from typing import Optional
import requests

def check_vpn_safe(ip: str) -> Optional[dict]:
    try:
        r = requests.post(
            "https://iplogs.com/v1/check",
            json={"ip": ip},
            timeout=10.0,
        )
        if r.status_code >= 500:
            return None
        r.raise_for_status()
        return r.json()
    except (requests.Timeout, requests.ConnectionError):
        return None

Treat None as “unknown” and degrade the policy: skip the VPN check, for instance, but keep the rest of the risk score. Don't retry aggressively by default. One in-line retry with backoff is usually enough.

Batch with /v1/bulk-check

Offline jobs, such as reviewing a fraud queue or running analysis, can post up to 100 IPs at once. Each IP comes back as a compact row (verdict, score, country, ASN, provider) rather than the full signal set:

import requests

def bulk_check(ips: list[str]) -> list[dict]:
    r = requests.post(
        "https://iplogs.com/v1/bulk-check",
        json={"ips": ips},
        timeout=95.0,  # endpoint has a 90s server-side budget
    )
    r.raise_for_status()
    return r.json()["results"]

# Chunk a larger list into batches of 100
def review_queue(all_ips: list[str]) -> dict:
    results = []
    for i in range(0, len(all_ips), 100):
        results.extend(bulk_check(all_ips[i : i + 100]))
    return {row["ip"]: row for row in results}

Type definitions

With static types, shape drift shows up in code review instead of in production logs. A minimal TypedDict / Pydantic-style model:

from typing import Literal, TypedDict

Verdict = Literal["clean", "suspicious", "vpn_likely", "vpn_detected"]

class IPInfo(TypedDict, total=False):
    ip: str
    asn: str
    org: str
    country: str
    country_code: str
    is_vpn: bool
    vpn_provider: str
    vpn_provider_sources: list[str]

class Signal(TypedDict):
    type: str
    weight: float
    matched: bool
    detail: str

class CheckResponse(TypedDict):
    verdict: Verdict
    score: float
    is_vpn: bool
    confidence: float
    signals: list[Signal]
    ip_info: IPInfo
    request_id: str

Applying policy by verdict

Each verdict bucket maps to a policy decision per route. The reasoning is in the longer compliance write-up, and the code is short:

def policy(verdict: dict, action: str) -> str:
    v = verdict.get("verdict", "clean")
    is_write = action in {"signup", "payment", "kyc", "withdrawal", "admin"}

    if v == "vpn_detected" and is_write:
        return "block"
    if v in {"vpn_detected", "vpn_likely"} and is_write:
        return "step_up_auth"
    if v == "suspicious" and is_write:
        return "elevate_risk"
    return "allow"

Don't hard-block read traffic on any verdict. False positives there are visible to users, and they tend to be ordinary customers on CGNAT, Apple Private Relay, or Cloudflare WARP. The glossary explains why those are separate categories.

Testing without hitting the network

# pytest + responses
import responses
from myapp.ip import check_vpn

@responses.activate
def test_check_vpn_clean():
    responses.add(
        responses.POST,
        "https://iplogs.com/v1/check",
        json={"verdict": "clean", "score": 0.0, "is_vpn": False,
              "ip_info": {"ip": "1.1.1.1"}, "signals": []},
        status=200,
    )
    out = check_vpn("1.1.1.1")
    assert out["verdict"] == "clean"

FAQ

Do I need an API key to use the IPLogs Python integration?

No. /v1/check is public and needs no signup or token. Limits apply per source IP: each one gets 2,000 full-depth checks a day and 60 requests a minute. After the 2,000th check you still get answers, but from the in-memory fast path ("mode": "fast", no real-time probing). Email admin@iplogs.com if you need more full-depth capacity.

What Python HTTP client should I use?

Either requests or httpx. requests is the most-installed synchronous HTTP client in the ecosystem; httpx has a near-identical API and adds async support and HTTP/2. The examples on this page use both. Whichever you pick, set a 10-second timeout. That is just above the API's ~8-second probing ceiling, so slow IPs still get an answer and a stuck upstream can't block your request handler.

How should I cache verdicts in Python?

Per IP, for about five minutes. A single-process service can use cachetools.TTLCache in memory; multi-instance deployments should share Redis. Each verdict is only a small JSON object, so caching it costs almost nothing compared with the round trip it saves.

When should I use /v1/bulk-check instead of /v1/check?

When you score IPs offline in batches, for example a nightly fraud-queue job that reviews yesterday's signups. The bulk endpoint accepts up to 100 IPs per request and returns a compact row per IP instead of the full signal set. Anything on the request path should keep using /v1/check.

How do I test the integration without hitting the network?

Stub the HTTP layer with responses (for requests) or respx (for httpx), then assert on the URL and body. The verdict shape is stable: verdict (one of clean / suspicious / vpn_likely / vpn_detected), score (0–1), is_vpn, ip_info, and signals[]. With the client mocked, CI never needs network access.

Schema details are in the API docs, other stacks are covered in the multi-language overview, and the accuracy benchmark gives the published false-positive rate. To see a real response first, paste an IP into the live checker.