Integrate the Website Traffic API in Python
When you audit where ads run, a domain’s traffic signals can help you prioritize sites for review, while its content category helps you decide whether the placement fits your policy. This guide shows you how to request domain traffic intelligence in Python, inspect the returned fields, and use a separate categorization response to support an allow, block, or review decision.
Why combine traffic intelligence with classification?
Traffic data and website categories answer different questions. A traffic response can help an analyst investigate a domain’s reach and acquisition mix; a category can help a policy engine assess what the site is about. Neither signal alone proves that an ad placement is safe or suitable.
Documentation covers Klazify’s REST endpoints for these tasks. Its categorization capabilities include content analysis, IAB taxonomy mapping, URL classification, and analysis across languages. That is useful when a placement list contains sites whose subjects are not apparent from their domain names.
For example, a team might use the Consumer Electronics category in the response below to route a technology placement to an appropriate campaign. The traffic endpoint can supply additional signals for the audit, but the categorization example should not be mistaken for a traffic response.
Klazify’s content analysis can provide more context than a workflow based only on a domain name or metadata. Still, treat classification as an input to your own rules: a category match is not, by itself, proof of compliance or a cybersecurity verdict.
Send a traffic intelligence request
The traffic endpoint accepts a JSON object with a url and uses a Bearer token. Replace YOUR_API_KEY with your key before running this request:
curl --request POST 'https://www.klazify.com/api/domain_traffic_intelligence' \
--header 'Authorization: Bearer YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{"url":"https://cbsnews.com"}'
Keep the credential in a secret store or environment variable in an application; do not commit it to source control. For a production integration, consult the traffic response example and field definitions in the documentation before choosing a storage schema. The categorization JSON later in this article illustrates a different endpoint’s response.
Call the endpoint from Python
Install the requests package in your Python environment. Set KL`AZIFY_API_KEY without the backtick as your environment variable name, and set REQUEST_TIMEOUT_SECONDS to a timeout appropriate for your service. Save the following as traffic.py.
import json
import os
import sys
import requests
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 their nesting."""
if isinstance(value, dict):
for key, item in value.items():
item_path = f"{path}.{key}"
if key in FIELDS:
yield item_path, item
yield from find_fields(item, item_path)
elif isinstance(value, list):
for index, item in enumerate(value):
yield from find_fields(item, f"{path}[{index}]")
def main():
if len(sys.argv) != 2:
raise SystemExit("Usage: python traffic.py DOMAIN_URL")
api_key = os.environ["KLAZIFY_API_KEY"]
timeout = float(os.environ["REQUEST_TIMEOUT_SECONDS"])
try:
response = requests.post(
ENDPOINT,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={"url": sys.argv[1]},
timeout=timeout,
)
response.raise_for_status()
payload = response.json()
except requests.RequestException as exc:
raise SystemExit(f"Traffic request failed: {exc}") from exc
except ValueError as exc:
raise SystemExit("Traffic response was not valid JSON") from exc
matches = list(find_fields(payload))
if not matches:
raise SystemExit(
"No requested traffic fields found; inspect the response "
"and verify the current schema in the documentation."
)
for path, value in matches:
print(f"{path}: {json.dumps(value, ensure_ascii=False)}")
if __name__ == "__main__":
main()
Run python traffic.py "$DOMAIN_URL" after setting DOMAIN_URL to the site you want to inspect. The script prints the path and value of each matching field, preserving nested objects or lists rather than assuming their internal structure. A missing match is reported explicitly; it is not converted to zero.
This is an inspection tool, not a finished policy engine. Once you have verified the current traffic response schema, replace the recursive search with explicit parsing and validation for the fields your application stores. Handle missing values separately from valid zero values, and retain enough context to investigate a response that cannot be parsed.
Interpret traffic fields and category data
The traffic fields below are useful starting points for a placement audit. Check the documentation for their precise definitions, units, reporting periods, and nested structure before comparing or aggregating values.
| Field | How to use it | Implementation check |
|---|---|---|
global_rank | Include a broad rank signal in an audit record. | Confirm its interpretation before sorting domains. |
country_rank | Review rank information with a geographic context. | Preserve the associated context rather than treating it as a global rank. |
category_rank | Inspect rank information alongside the relevant category context. | Do not assume it is the same as a content-policy classification. |
monthly_visits | Use as a traffic signal when prioritizing review. | Verify the period and units before comparing records. |
engagement | Inspect the engagement data available for the domain. | Keep the returned structure and validate individual measures. |
traffic_sources | Examine the returned acquisition-source information. | Check definitions before calculating or displaying shares. |
top_countries | Review the geographic information returned for the domain. | Do not infer a complete country distribution from a top-countries field. |
Traffic signals do not identify whether a site falls into a content category. For that, Klazify provides https://www.klazify.com/api/categorize. The following is the supplied categorization response example, not a response from the traffic request above:
{
"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, success indicates the result’s success state, and domain.categories contains multiple category entries. Each entry has a name and confidence; the first also contains an IAB mapping under IAB-632-596. A policy engine should examine the full category list rather than assume the first entry is the only relevant one.
The objects.company data can enrich an audit or CRM record, while domain.social_media and domain.logo_url provide additional context when present. Here, social_media is null: preserve that as unavailable rather than interpreting it as proof that no social profiles exist. Registration data and similar domains are separate signals, not substitutes for a category decision.
Build a reliable domain pipeline
Normalize and validate each submitted URL before lookup, then use a consistent domain key for traffic caching and deduplication. Preserve the original URL as well. If your classification workflow evaluates individual pages, do not collapse page-level results into one domain-wide category without deciding how that affects your policy.
For a large placement list, group work in your application and control concurrency according to your account’s current limits. Avoid assuming that a batch endpoint or a particular quota exists. Start conservatively, monitor latency and errors, and adjust throughput using the account and documentation details available to you.
Cache traffic results per domain with a refresh policy suited to the decision. Record when your application fetched the data, and distinguish that timestamp from any reporting period described by the API. A stale result may still help an analyst investigate a placement, but it should not silently stand in for a current policy check.
Model unavailable, new, or unreachable domains as an explicit unknown state. Depending on the consequence of an incorrect decision, send unknowns for review or apply your organization’s default policy. Retry transient failures with controlled backoff; do not repeatedly retry an invalid input without correcting it. Klazify states that failed or unreachable calls are not billed, but your integration should still monitor failures and avoid unnecessary requests.
Keep a versioned mapping from Klazify category names or IAB mappings to your own allow, block, and review labels. Store the original categories and confidence values alongside the mapped decision so an auditor can reconstruct it. Set any confidence threshold through your own validation process; the example values are not a recommended cutoff.
Finally, keep traffic and classification as separate records joined by your domain key. A traffic lookup can succeed while categorization is unavailable, or vice versa. That separation lets downstream systems show what is known without presenting an incomplete enrichment as a complete assessment.
FAQ
Does the traffic request also classify a website?
The traffic request retrieves traffic intelligence. Use the categorization endpoint and its documented response when your workflow also needs website categories or IAB mappings.
What should I do when a traffic field is missing?
Store it as unavailable, not as zero. Check the response and current field definitions, then decide whether the record can proceed or needs a retry or review.
How should I handle rate limits?
Control concurrency and queue excess work in your application. Check your account and the documentation for applicable limits rather than hard-coding an assumed quota.
Can I use Klazify with an MCP workflow?
See the MCP information for that integration path. The Python example above uses the REST traffic endpoint directly.
Register for a free account to start integrating Klazify. The Starter plan is $39.99 per month with a seven-day trial; review the available account details before choosing a plan for your workload.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free