Integrate IP Insights into Your Python Application: A Developer's Guide

15 min readOpportify Team

This guide shows how to add IP Insights, our IP reputation API, to a Python application with the official SDK. You will analyze a single IP, read the response, run batch jobs, export filtered results, handle errors, and route each result to a review step your team defines. Every method, endpoint, and field name below comes from the live Python SDK documentation and the API reference. Where a value is only an example, we say so.

This is the Python edition of our IP Insights SDK series. If you work in Node.js, see the Node.js guide. New to IP reputation? IP Reputation Check Explained covers what the score means and where it can mislead. For product details, see IP Insights.

Why Check an IP at Sign-Up, Login, or Form Submit

The IP behind a request carries context the form fields do not: whether it is a residential, mobile, VPN, cloud, open proxy, or anonymizing network connection, whether it appears on blocklists, and who owns the network. IP Insights returns that context with a risk score from 200 to 1000 and the top risk factors behind it. Your application can then send higher-risk requests to a step you choose, such as a review queue or an extra verification step. We score and flag; your code and your team decide what happens next.

Prerequisites

  • Python 3.8 or later, as the SDK documentation requires.
  • An API key. Create one in your account.
  • The SDK, installed from PyPI:
pip install opportify-sdk

One SDK and one API key cover Email Insights, IP Insights, and Fraud Protection. IP Insights calls go to the base URL https://api.opportify.ai/insights/v1, which the SDK sets for you.

Keep the API key out of code

Keep your API key server-side only, in a secret manager (preferred) or a securely managed environment variable, and never in source code, client-side code, or query strings. Rotate it if there is any risk of exposure. The examples below use a get_secret() placeholder for whichever secret manager you use.

How a Request Flows

Request flow for IP Insights in a Python app, shown left to right in six steps. 1, a user submits a sign-up, login, or form. 2, your app server reads the client IP. 3, your code calls the SDK method ip_insights.analyze with the ip and an optional enableAi flag. 4, the SDK sends POST /ip/analyze to api.opportify.ai/insights/v1 with the API key in the x-opportify-token header. 5, the response is a Python dict with connectionType, geo, whois, trustedProvider, blocklisted, and riskReport. 6, your app applies a policy your team defines: continue the normal flow, add a verification step, or send to a review queue. A footer reads: we score and flag; your team decides.

Under the hood, the SDK calls POST /ip/analyze. Per the Analyze IP API reference, the API key travels in a request header (x-opportify-token), and the API avoids query parameters for all operations so that sensitive data does not end up in access logs, browser history, or cached URLs.

Analyze a Single IP

The IpInsights class takes your API key and exposes analyze(), which accepts a dict with the IP address and an optional flag that the Python SDK accepts as enableAi or enable_ai. Both IPv4 and IPv6 are supported.

from opportify_sdk import IpInsights

# get_secret() is a placeholder for your secret manager client.
ip_insights = IpInsights(get_secret("opportify-api-key"))

result = ip_insights.analyze({
    "ip": "203.0.113.42",  # documentation-range address (RFC 5737), for illustration
    "enableAi": True,      # optional
})

risk = result.get("riskReport") or {}
print(result["connectionType"])   # e.g. "wired", "vpn", "open-proxy"
print(risk.get("score"))          # 200 to 1000, higher is riskier
print(risk.get("level"))          # "lowest" | "low" | "medium" | "high" | "highest"
print(risk.get("baseAnalysis"))   # top risk factors, e.g. ["ip-blocklisted"]

analyze() returns a plain Python dict. Its keys are the field names from the API reference, so you read result["riskReport"], not an attribute.

About enableAi: the API field is enableAI, an optional request parameter documented on the Analyze IP reference. The reference says it defaults to true, and that if you send false, riskReport comes back as an empty object. Python SDK 1.0.0, the current release on PyPI, reads the flag only as enableAi or enable_ai and sends it to the API as enableAI; in that release, a key spelled enableAI is not passed on, so the API default applies. enableAi works on every release, so the examples below use it and read riskReport with .get(), which handles both cases.

Validate the address first

Python's standard library can check the input before you spend a call on it. This also unwraps IPv4-mapped IPv6 addresses (::ffff:203.0.113.42), which some servers report for IPv4 clients.

import ipaddress

def clean_ip(raw: str) -> str:
    addr = ipaddress.ip_address(raw.strip())  # raises ValueError if invalid
    if addr.version == 6 and addr.ipv4_mapped:
        return str(addr.ipv4_mapped)
    return str(addr)

Read the Response

A successful call returns one object. These are the top-level fields from the API reference, all of which are marked required in the schema:

Field What it holds
ipAddress, ipAddressNumber, ipType, ipCidr The analyzed address, its numeric form, IPv4 or IPv6, and its CIDR notation
connectionType One of eight documented values: wired, mobile, enterprise, satellite, vpn, cloud-provider, open-proxy, or tor
hostReverse Reverse DNS lookup result
geo Location data such as continent, countryCode, countryName, region, city, timezone, latitude, and longitude
whois rir, asn (asnId, asName, ...), organization, and abuseContact, adminContact, techContact
trustedProvider isKnownProvider, plus provider, providerType, and description when known
blocklisted isBlockListed, sources, activeReports, and lastDetected
riskReport score (200 to 1000), level, and baseAnalysis (the highest-weight risk factors)

The riskReport object is the Explainable Risk Report: the score, the level, and the factors that explain it. The API reference notes that baseAnalysis lists the highest-weight factors, and that additional lower-weight signals may exist outside the array. Geolocation is returned as context for your reviewers; it is not a score input.

Annotated excerpt of an IP Insights response as a Python dict, with illustrative values; ellipses mark omitted fields. Six numbered callouts run top to bottom: 1, connectionType open-proxy, how the IP connects; 2, geo with countryCode and city, location context for reviewers that is not a score input, with city-level confidence the docs put at 50 to 70 percent; 3, whois with rir and asn, network ownership; 4, trustedProvider with isKnownProvider False, whether the IP belongs to a known enterprise or ZTNA provider; 5, blocklisted with isBlockListed True, 4 sources, and 6 activeReports, the blocklist evidence; 6, riskReport with score 870, level highest, and baseAnalysis ip-blocklisted, multiple-blocklist-sources, and open-proxy, the Explainable Risk Report. Field names are from the live docs.

The risk levels map to fixed score ranges in the API reference: lowest is 200 to 300, low is 301 to 400, medium is 401 to 600, high is 601 to 800, and highest is 801 to 1000. Scoring is a layered, explainable engine with safety floors. The same input always gets the same score, so key your logic to level and baseAnalysis rather than to an exact score.

Route Results to a Step Your Team Defines

IP Insights returns signals. It does not accept or reject anything. The pattern below maps each level to a step in your own flow. The mapping is an illustrative example: your team should set it based on your risk tolerance and your other signals.

# ip_policy.py: illustrative policy. Your team owns these choices.
IP_POLICY = {
    "lowest": "continue",
    "low": "continue",
    "medium": "monitor",   # e.g. flag for later sampling
    "high": "verify",      # e.g. add an email or phone confirmation step
    "highest": "review",   # e.g. hold for a manual review queue
}


def route_by_ip_risk(result: dict) -> dict:
    risk = result.get("riskReport") or {}
    level = risk.get("level")
    return {
        "step": IP_POLICY.get(level, "review"),  # unknown level: let a person look
        "level": level,
        "score": risk.get("score"),
        "factors": risk.get("baseAnalysis", []),  # store these so reviewers can see why
    }

A few practices make this pattern hold up in production:

  • Store the result with the record. Save riskReport["score"], riskReport["level"], baseAnalysis, connectionType, and blocklisted alongside the sign-up or login event. Reviewers need the factors, and you will want them when you tune the policy.
  • Read factors, not just levels. vpn and icloud-private-relay are both VPN-class, but the assessed signals page explains that iCloud Private Relay is scored as lower risk. An open-proxy with active reports deserves a different response than a VPN with an old blocklist entry.
  • Combine signals. IP is one layer. Pair it with email and session signals before you take an action a real customer would notice. Our guide to VPN and proxy detection for legitimate users shows how to avoid turning away legitimate VPN users.

Example: a Flask sign-up handler

This example assumes your app runs behind a load balancer or reverse proxy. Configure Werkzeug's ProxyFix to match your infrastructure so that request.remote_addr holds the client address rather than the proxy's.

from flask import Flask, jsonify, request
from werkzeug.middleware.proxy_fix import ProxyFix
from opportify_sdk import IpInsights

from ip_policy import route_by_ip_risk
from net_utils import clean_ip  # the helper from "Validate the address first"

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)  # match your own proxy setup

ip_insights = IpInsights(get_secret("opportify-api-key"))


@app.post("/api/signup")
def signup():
    try:
        result = ip_insights.analyze({
            "ip": clean_ip(request.remote_addr or ""),
            "enableAi": True,
        })
        ip_check = route_by_ip_risk(result)
    except Exception:
        # If the check is unavailable, record that and let your policy decide.
        ip_check = {"step": "check-unavailable"}

    account = create_pending_account(request.get_json(), ip_check=ip_check)

    if ip_check["step"] == "verify":
        return jsonify(next="verify-email", account_id=account.id)
    if ip_check["step"] == "review":
        add_to_review_queue(account.id, ip_check)
    return jsonify(next="welcome", account_id=account.id)

get_secret, create_pending_account, and add_to_review_queue stand in for your own code. What happens when the check is unavailable is a business decision. Some teams continue and review later; others add a verification step.

The SDK methods are synchronous. In an async framework, run the call in a worker thread, for example with asyncio.to_thread (Python 3.9 or later), so it does not hold up the event loop.

Handle Errors

The SDK documentation recommends wrapping every call in try/except and catching ApiException from openapi_client.exceptions. The exception carries status, reason, and body. When the API returns an error, the body is JSON with two fields, errorCode and errorMessage, and the Analyze IP reference lists the codes: IP_VALIDATION_FAILED and MALFORMED_REQUEST for 400; INVALID_TOKEN, FORBIDDEN, INVALID_PLAN, QUOTA_EXCEEDED, TOO_MANY_REQUESTS, and others for 403; NOT_FOUND for 404. Key your handling to errorCode, because several different problems share the 403 status.

import json
import random
import time

from openapi_client.exceptions import ApiException

DO_NOT_RETRY = {
    "IP_VALIDATION_FAILED",  # 400: not a valid IPv4 or IPv6 address
    "MALFORMED_REQUEST",     # 400/403: fix the request
    "NOT_FOUND",             # 404: IP not found in any RIR database
    "INVALID_TOKEN",         # 403: check the key
    "FORBIDDEN",             # 403: check permissions and ACL rules
    "INVALID_PLAN",          # 403: check your account
    "QUOTA_EXCEEDED",        # 403: check your account
}


def error_code(exc: ApiException):
    try:
        return json.loads(exc.body or "{}").get("errorCode")
    except (TypeError, ValueError, AttributeError):
        return None


def analyze_with_backoff(ip: str, attempts: int = 4, base_delay: float = 0.5) -> dict:
    for attempt in range(attempts):
        try:
            return ip_insights.analyze({"ip": ip, "enableAi": True})
        except ApiException as exc:
            code = error_code(exc)
            if code in DO_NOT_RETRY:
                raise  # alert or fix input; retrying will not help
            rate_limited = code == "TOO_MANY_REQUESTS" or exc.status == 429
            server_error = (exc.status or 0) >= 500
            if not (rate_limited or server_error) or attempt == attempts - 1:
                raise
            # Exponential backoff with jitter; do not wait on a Retry-After header.
            time.sleep(base_delay * (2 ** attempt) + random.uniform(0, base_delay))

The status codes documented for POST /ip/analyze are:

Code Meaning (from the API reference)
200 The IP analysis is successful
400 The request is improperly formatted, or the IP is invalid
403 An authentication or permission error
404 The IP address was not found in any RIR database
500 Internal server error

The batch endpoints can also return 413 when the payload is over 3 MB. Authentication, quota, and rate-limit problems on these endpoints come back as 403, with an error code such as TOO_MANY_REQUESTS for rate limits. Do not rely on a Retry-After header: retry rate-limited calls with exponential backoff and avoid large retry bursts. Network failures raise ordinary Python exceptions rather than ApiException, so decide how your policy treats them too.

Analyze IPs in Batches

For larger lists, such as auditing existing accounts or reviewing a day of traffic, submit a batch job. Batches run asynchronously and return a jobId you can poll.

Batch lifecycle for IP Insights in Python, in four steps. Step 1: submit with ip_insights.batch_analyze, which calls POST /ip/batch and returns a jobId with status QUEUED. Step 2: poll ip_insights.get_batch_status every 1 to 3 seconds, which calls GET /ip/batch/{jobId}, as status moves from QUEUED to PROCESSING to COMPLETED or ERROR, with progress from 0 to 100. Step 3: create a filtered export with ip_insights.create_batch_export, which calls POST /ip/batch/{jobId}/exports and returns an exportId. Step 4: poll ip_insights.get_batch_export_status, which calls GET /ip/batch/{jobId}/exports/{exportId}, until COMPLETED or FAILED, then download from the time-limited downloadUrl before expiresAt.

Submit and poll

import time

batch = ip_insights.batch_analyze({
    "ips": ["192.0.2.10", "198.51.100.23", "203.0.113.5"],  # documentation-range examples
    "name": "Weekly account audit",  # optional
    "enableAi": True,                # optional
})
job_id = batch["jobId"]


def wait_for_batch(job_id: str, interval: float = 2.0, timeout: float = 600) -> dict:
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        status = ip_insights.get_batch_status(job_id)
        state = status.get("status")
        if state == "COMPLETED":
            return status
        if state == "ERROR":
            raise RuntimeError(status.get("statusDescription") or "Batch failed")
        print(f"Batch {job_id}: {state}, {status.get('progress', 0)}%")
        time.sleep(interval)
    raise TimeoutError("Batch did not complete in time")


done = wait_for_batch(job_id)
print(done["downloadUrls"]["json"])  # also csv, csvCompressed, jsonCompressed

You can also submit a file or plain text. batch_analyze_file() sends a .csv as multipart/form-data and other extensions as newline-delimited text, and batch_analyze() accepts a text key with the text/plain content type:

batch = ip_insights.batch_analyze_file("ips.csv", {"name": "Firewall review", "enableAi": True})

batch = ip_insights.batch_analyze({"text": "192.0.2.10\n198.51.100.23"}, "text/plain")

Details from the docs worth knowing:

  • Status values: QUEUED, PROCESSING, COMPLETED, or ERROR. On ERROR, read statusDescription. progress runs from 0 to 100.
  • Polling cadence: the SDK page recommends a short delay of 1 to 3 seconds between status checks.
  • Payload limit: 3 MB per request. Split larger lists into several jobs.
  • Input formats: the Batch Analyze IPs reference accepts JSON arrays, CSV, TSV, or XLSX uploads, and line-separated text.
  • Results: when the job completes, downloadUrls holds pre-signed links for CSV, JSON, and gzip-compressed versions. They are time-limited, so download promptly and store what you need.
  • Partial failures: per the FAQ, a batch keeps processing when some items fail, and errors are flagged in the output so you can resubmit only those entries.

Export a filtered view

Exports let you pull only the rows and columns you need from a completed job, for example every IP your policy would send to review.

created = ip_insights.create_batch_export(job_id, {
    "exportType": "csv",  # or "json"
    "columns": [
        "result.ipAddress",
        "result.connectionType",
        "result.riskReport.score",
        "result.riskReport.level",
    ],
    "filters": {
        "result.riskReport.level": ["high", "highest"],
    },
})


def wait_for_export(job_id: str, export_id: str, interval: float = 2.0, timeout: float = 600) -> dict:
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        status = ip_insights.get_batch_export_status(job_id, export_id)
        if status["status"] == "COMPLETED":
            return status
        if status["status"] == "FAILED":
            raise RuntimeError(f"Export failed: {status.get('errorCode')} {status.get('errorMessage')}")
        time.sleep(interval)
    raise TimeoutError("Export did not complete in time")


export_status = wait_for_export(job_id, created["exportId"])
print(export_status["downloadUrl"], export_status["expiresAt"])  # download before expiresAt

wait_for_export polls get_batch_export_status the same way wait_for_batch polls the job: its status moves through QUEUED, PROCESSING, and then COMPLETED or FAILED. The Create IP Batch Export reference documents the filter rules: string filters accept exact values, comma-separated lists, or arrays; numeric filters accept exact values, arrays, or min/max ranges; nested fields use dot notation. Limits are 25 filters, 50 values per filter, and 100 columns. If the batch has not finished, the export request returns 409.

Production Checklist

  • Secrets: load the API key from a secret manager, never from source code. Rotate keys by deploying a new key first, confirming it works, then removing the old one, as the FAQ describes.
  • ACL rules: restrict API access to your servers' IP addresses or ranges with ACL rules in your account.
  • No sensitive data in URLs: the API takes everything in headers or the request body. Keep it that way in your own logs and proxies.
  • Debug mode stays local: the SDK's set_debug_mode(True) helps while you build. Keep it off in production so request details do not end up in your logs.
  • Short-lived caching: the FAQ says blocklist data is updated continuously and recommends caching risk and blocklist results only for short periods. Stable data such as ASN can be cached longer.
  • Store the factors: keep riskReport and the key signals with each event so reviewers can see why a request was flagged.
  • Test your policy: documentation-range addresses (RFC 5737) are not routed on the public internet, so a live call with one may return 404 (not found in any RIR database). In unit tests, patch ip_insights.analyze with unittest.mock to return fixture dicts, then test each level value, each error path, and the "check unavailable" path.

Next Steps

The SDK is also available for Node.js, PHP, and Java. See the SDK overview for each language's setup.