Integrate the Traffic Sources API in Python

November 30, 2026
Integrate the Traffic Sources API in Python

You need to audit where an ad campaign runs, but a domain alone does not tell you how much traffic a site receives or where that traffic comes from. This guide shows how to call Klazify’s traffic intelligence endpoint from Python, extract the available traffic fields, and combine that information with website categorization for an audit or enrichment pipeline.

Why use Klazify for a traffic and category audit?

Traffic intelligence and content classification answer different questions. Traffic fields help you investigate a domain’s reach and acquisition profile; categories help you decide whether its content fits your placement policy. Using both gives an analyst more context than a rank or a domain name alone.

Illustration: Integrate the Traffic Sources API in Python

Klazify provides a REST API for domain intelligence, alongside categorization based on website content. Its hierarchical categorization system includes IAB taxonomy mapping, which can help advertising teams translate website classifications into their own placement rules. URL-level classification is also useful when a site contains different kinds of content on different pages.

For an ad placement audit, a practical workflow is to retrieve traffic intelligence for each domain, associate it with a classification result, and flag records that need review. Treat category-based filtering as a policy input, not proof that a site is safe or compliant. Review the Documentation for the current endpoint details and response definitions before deploying a policy.

Request traffic intelligence

The traffic endpoint accepts a JSON body containing a URL and authenticates with a Bearer token. Replace YOUR_API_KEY with your key before running the request:

curl -X POST 'https://www.klazify.com/api/domain_traffic_intelligence' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://cbsnews.com"}'

Save the returned response when testing so you can inspect its structure before designing a database schema. In particular, verify the nesting and meaning of the traffic fields, the units used for visits and engagement, and any time period associated with the measurements. Do not assume that every domain has a value for every field.

Call the same endpoint from Python

The following script uses Python’s standard library. Set KLAZIFY_API_KEY and DOMAIN_URL in your environment, save the script as traffic.py, and run python traffic.py "$DOMAIN_URL".

import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

ENDPOINT = "https://www.klazify.com/api/domain_traffic_intelligence"
FIELDS = {
    "global_rank",
    "country_rank",
    "category_rank",
    "monthly_visits",
    "engagement",
    "traffic_sources",
    "top_countries",
}


def find_fields(value, path="$"):
    """Find requested fields without assuming a response nesting."""
    if isinstance(value, dict):
        for key, child in value.items():
            child_path = path + "." + key
            if key in FIELDS:
                yield child_path, child
            yield from find_fields(child, child_path)
    elif isinstance(value, list):
        for index, child in enumerate(value):
            yield from find_fields(child, path + "[" + str(index) + "]")


def main():
    api_key = os.environ.get("KLAZIFY_API_KEY")
    if not api_key or len(sys.argv) != 2:
        sys.exit("Set KLAZIFY_API_KEY and pass one URL as an argument.")

    payload = json.dumps({"url": sys.argv[1]}).encode("utf-8")
    request = Request(
        ENDPOINT,
        data=payload,
        headers={
            "Authorization": "Bearer " + api_key,
            "Content-Type": "application/json",
        },
        method="POST",
    )

    try:
        with urlopen(request, timeout=7) as response:
            result = json.load(response)
    except HTTPError as exc:
        sys.exit("Klazify returned HTTP status: " + str(exc.code))
    except (URLError, TimeoutError) as exc:
        sys.exit("Request failed: " + str(exc))
    except (json.JSONDecodeError, UnicodeDecodeError):
        sys.exit("The response was not valid JSON.")

    matches = list(find_fields(result))
    if not matches:
        sys.exit("No requested traffic fields were found; inspect the response.")

    for path, value in matches:
        print(path + ": " + json.dumps(value, ensure_ascii=False))


if __name__ == "__main__":
    main()

The script searches the returned JSON recursively and prints each matching field with its path. This makes it useful for inspecting a response without assuming that all traffic fields sit at the top level. A matching name alone does not establish its meaning: verify the path and field definition before turning the output into a production parser.

The request timeout is a client-side setting, not an API limit. Tune it for your application, and keep the key in a secret manager or environment variable rather than committing it to source control. In production, record a safe error status and request context without logging the authorization header.

Turn traffic fields into an audit record

Keep the raw response alongside a normalized record while you validate the integration. That lets you revisit a field’s original context if the shape changes or an analyst questions a decision.

Field How to use it What to verify
global_rank Provide a global ranking signal for review. Ranking definition and the period it represents.
country_rank Add geographic context to a ranking. Which country the value refers to and how it is represented.
category_rank Assess a ranking in its category context. The associated category and ranking definition.
monthly_visits Add a visit-volume signal to an enrichment or audit record. Units, measurement period, and whether a value is available.
engagement Inspect available engagement information alongside volume. Subfields, units, and whether values can be compared across domains.
traffic_sources Investigate the acquisition information returned for the domain. Source labels, units, and whether values are counts or proportions.
top_countries Review the geographic information available for the domain. Country representation, units, and the measurement period.

For a placement audit, join these fields to your internal placement record using a consistently normalized domain. An analyst can then review the traffic context alongside the site category and your policy decision. Preserve the full URL separately when the placement is page-specific; a domain-level join can otherwise hide differences between pages.

Do not treat a missing rank as a rank of zero or an empty traffic field as evidence that a domain has no visitors. Store missing values as unknown, and distinguish them from a failed request. If your downstream system requires numeric values, validate their type and documented units before calculating thresholds or comparisons.

Use categorization alongside traffic intelligence

The following is a categorization response example. It illustrates fields useful for classification and enrichment; it is not a response from the traffic intelligence endpoint. Use it to design the category side of the join, rather than assuming that the traffic endpoint returns the same structure.


{
    "domain": {
        "categories": [
            {
                "confidence": 0.92,
                "name": "/Computers & Electronics/Consumer Electronics",
                "IAB-632-596": "Consumer Electronics/Technology & Computing/Consumer Electronics"
            },
            {
                "confidence": 0.89,
                "name": "/Internet & Telecom/Mobile & Wireless/Mobile Phones"
            }
        ],
        "social_media": null,
        "logo_url": "https://klazify.s3.amazonaws.com/2110787991611585019600ed5fb1d1300.04730104.png"
    },
    "success": true,
    "objects": {
        "company": {
            "url": "https://www.apple.com/",
            "name": "Apple",
            "city": "Cupertino",
            "stateCode": "CA",
            "countryCode": "US",
            "employeesRange": "100K+",
            "revenue": 274515000000,
            "raised": null,
            "tags": [
                "E-commerce",
                "Consumer Electronics",
                "Mobile",
                "B2C"
            ],
            "tech": [
                "omniture_adobe_analytics",
                "atlassian_confluence",
                "successfactors",
                "apache_apex",
                "talend",
                "oracle_peoplesoft",
                "salesforce",
                "stripe",
                "dell_boomi_atomsphere",
                "gigya",
                "sage_50cloud",
                "quickbooks",
                "webmethods",
                "apache_tomcat",
                "alteryx",
                "tibco_rendezvous",
                "atlassian_jira",
                "..."
            ]
        }
    },
    "domain_registration_data": {
        "domain_age_date": "1987-02-19",
        "domain_age_days_ago": "13026",
        "domain_expiration_date": "2030-02-20",
        "domain_expiration_days_left": "123"
    },
    "similar_domains": [
        "bestbuy.com",
        "icloud.com",
        "microsoft.com",
        "macrumors.com",
        "google.com",
        "samsung.com",
        "twitter.com",
        "hp.com",
        "bhphotovideo.com",
        "dell.com"
    ]
}

In this example, domain.categories contains category names and confidence values. One category also carries an IAB mapping under IAB-632-596. A policy engine can map those returned categories to internal labels, but it should retain the original category and confidence so a reviewer can explain the decision.

The success field is relevant to the categorization result, while objects.company supplies enrichment fields such as company name and location. social_media is null in the example, so consumers must handle absent enrichment without treating it as an error. The registration dates and similar domains are additional context; neither should be treated as a traffic measurement or a safety verdict.

Map categories to your own policy

Maintain a versioned mapping from Klazify category names or IAB mappings to your internal taxonomy. For each decision, store the original result, the mapping version, and the action your policy selected. That record makes it possible to reprocess historical placements when policy changes without presenting a new rule as an old decision.

Define a separate outcome for an unmapped category or low-confidence result, such as manual review. For blocking workflows, decide explicitly whether unknown domains should be held for review or allowed temporarily. For CRM enrichment, leaving a category blank with an unknown status is usually more useful than assigning an unsupported label.

Run the integration at scale

Queue requests and control concurrency. Collect incoming domains in a work queue and process them at a rate consistent with your account’s limits. Confirm current limits and any supported batching behavior in the documentation; do not assume that sending a list in the single-URL request body is supported.

Cache per domain. Normalize domains consistently before lookup, then store the response and retrieval time. Choose a refresh interval based on how quickly your use case needs updated information: a placement audit may tolerate different freshness from an interactive signup flow. Keep page-level classification separate when the full URL matters, rather than reusing a domain result for every page.

Handle unknown and new domains deliberately. A new domain, an unavailable site, or a response with missing fields should enter an explicit unknown state. Keep the submitted domain and failure context, then schedule a later retry where appropriate. Do not infer a category or traffic volume from an unrelated domain simply to fill the record.

Retry safely. Use bounded retries with backoff for transient connection problems or rate limiting, and avoid retrying indefinitely for configuration or authentication errors. Make queue processing idempotent so that a retry updates the same domain record rather than creating duplicate audit rows. Klazify states that failed or unreachable calls are not billed; check the applicable billing terms for how failures are determined.

Monitor freshness and completeness. Track request outcomes, missing fields, cache age, and the proportion of records routed to review. This helps distinguish a genuine change in the incoming domain population from an integration problem. Keep raw responses protected according to your organization’s data-retention policy, and avoid placing API keys in logs.

For teams exploring other integration workflows, Klazify also provides an MCP resource. Validate that it supports your intended workflow before using it in place of the direct REST request shown above.

FAQ

Can I classify a domain using its traffic sources alone?

No. Traffic sources describe acquisition information, not the site’s content category. Use a categorization result for content policy and keep the traffic data as a separate signal.

What should I do when a traffic field is missing?

Record it as unknown and retain enough context to investigate or retry. Do not substitute zero unless the response and field definition explicitly establish that meaning.

Should I cache by domain or by URL?

Cache domain-oriented traffic records by a normalized domain when that matches your use case. Preserve full URLs and use a separate cache key for page-level classification when different pages may have different content.

How much does it cost to start?

The Starter plan is $39.99 per month with a seven-day trial. Check the current plan and billing terms before deploying a high-volume integration.

Create a free account through Register, then use your API key to test the request and inspect traffic data for domains in your pipeline.

Ready to use Klazify?

Start classifying websites, enriching company data, and exploring web intelligence.

Get Started Free