How to Get Monthly Visits in Python
You need to fetch a domain’s monthly visits in Python to drive a concrete outcome: for example, prioritize ad spend by where audiences actually are, enrich a CRM record with traffic size, or flag sudden drops in visits during an audit. By the end of this guide, you’ll call Klazify’s traffic endpoint, parse monthly_visits and related fields, and wire them into a Python workflow you can cache and run at scale.
Why Klazify is the best fit when you need monthly visits
When your pipeline depends on reliable monthly visits, you don’t just need a number—you need an API you can automate, cache, and monitor across thousands of domains. Klazify’s domain intelligence helps you extract monthly_visits along with rankings, engagement and traffic source mix so you can build robust analytics, filtering and enrichment.
- Accurate website categorization using AI: Monthly visits make the most sense when paired with content categories. Klazify analyzes full-site content and maps it to IAB taxonomy, so you can weight visits per topic or exclude sensitive categories in downstream logic.
- Global coverage: Traffic metrics are paired with global and country rank, enabling apples-to-apples comparisons across regions and multilingual markets.
- Real-time classification: Up-to-date categorization and domain intelligence means your monthly visits read aligns with current content, not outdated lookups.
- Industry-level categories: IAB taxonomy mapping lets you join traffic with compliant content labels for ad safety, contextual targeting, and measurement.
- Simple API integration: REST endpoints and straightforward JSON let you plug monthly_visits into Python notebooks, ETL jobs, or event-driven services quickly.
- Superior compliance and filtering: Combine monthly_visits with categories, ranks and source mix to set thresholds (e.g., block long-tail low-engagement sites, prefer organic-heavy sources).
We’ll focus on POST https://www.klazify.com/api/domain_traffic_intelligence and show how to parse monthly_visits with Python, then operationalize the results.
What you’ll build
We’ll implement a small but production-ready flow:
- Make a single traffic request to retrieve monthly_visits and related traffic metrics.
- Parse the response in Python and surface the exact integers and distributions you need.
- Cache per domain and handle unknown or newly observed domains safely.
- Map traffic intelligence to your existing schemas and categories.
You can adapt this to ad ops auditing (verify where ads run), signup enrichment (attach audience size to incoming domains), or content filtering (enforce traffic and category policies before allowing partners to onboard).
Make your first traffic call
Use a Bearer token and send the URL in a JSON body. Failed or unreachable calls are not billed, so you can safely retry transient network issues. Replace YOUR_API_KEY with your token.
curl -s -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"}'
This endpoint returns traffic intelligence including fields you’ll typically use:
- monthly_visits: Estimated monthly visits for the domain.
- global_rank: Relative rank among all sites.
- country_rank: Rank in the primary country or market.
- category_rank: Rank within the site’s content category.
- engagement: Engagement metrics such as visit duration or pages per visit.
- traffic_sources: Mix of traffic by channel (e.g., direct, search, referrals).
- top_countries: Top geographies contributing visits.
We’ll parse these fields next and fit them into a Python workflow.
Parse monthly visits and ranks in Python
The snippet below demonstrates a callable function that requests the traffic data and extracts monthly_visits alongside core fields. It includes basic retry, error handling, and a spot to inject your cache.
import os
import time
import json
import requests
from typing import Any, Dict, Optional, Tuple
API_URL = "https://www.klazify.com/api/domain_traffic_intelligence"
API_KEY = os.getenv("KLAZIFY_API_KEY", "YOUR_API_KEY")
class TrafficError(Exception):
pass
def get_domain_traffic(url: str, session: Optional[requests.Session] = None) -> Dict[str, Any]:
s = session or requests.Session()
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
"Accept": "application/json"
}
payload = {"url": url}
# Basic retry for transient network errors/timeouts
for attempt in range(3):
try:
resp = s.post(API_URL, headers=headers, json=payload, timeout=20)
if resp.status_code == 200:
return resp.json()
# Not billed for failed/unreachable calls; you can safely retry 5xx and certain 4xx
if resp.status_code in (500, 502, 503, 504):
time.sleep(1.5 * (attempt + 1))
continue
# For other non-200s, surface the message for observability
raise TrafficError(f"HTTP {resp.status_code}: {resp.text}")
except requests.RequestException as e:
time.sleep(1.5 * (attempt + 1))
last_err = e
raise TrafficError(f"Unable to fetch traffic for {url}: {last_err}")
def extract_monthly_visits(block: Dict[str, Any]) -> Tuple[Optional[int], Dict[str, Any]]:
# Defensive parsing: fields may be missing for new or unknown domains
mv = block.get("monthly_visits")
result = {
"global_rank": block.get("global_rank"),
"country_rank": block.get("country_rank"),
"category_rank": block.get("category_rank"),
"engagement": block.get("engagement"),
"traffic_sources": block.get("traffic_sources"),
"top_countries": block.get("top_countries"),
}
return mv, result
if __name__ == "__main__":
domain = "https://cbsnews.com"
raw = get_domain_traffic(domain)
# Your response schema will include the traffic intelligence keys documented by Klazify.
# Extract values safely and log them for downstream aggregation.
monthly_visits, metrics = extract_monthly_visits(raw)
print("monthly_visits:", monthly_visits)
print(json.dumps(metrics, indent=2))
Downstream, you can store monthly_visits as an integer column, global_rank and country_rank as integers, engagement as a JSON blob, and traffic_sources/top_countries as nested structures or flattened columns.
How to use the returned fields
Monthly visits is most useful when interpreted with rank, engagement, and geography. Treat it as an input to your eligibility rules and prioritization, not as a standalone metric.
- Threshold gating: Require monthly_visits to meet a minimum before partner onboarding.
- Prioritization: Sort prospects by monthly_visits, then break ties by global_rank or engagement depth.
- Geo routing: Use top_countries to allocate regional budgets or filter inventory by locale.
- Attribution sanity checks: A heavy organic share in traffic_sources might be a signal of durable audience vs. paid spikes.
| Field | Type | How to use it |
|---|---|---|
| monthly_visits | Integer | Primary magnitude signal; cache and track deltas for anomaly detection. |
| global_rank | Integer | Normalize size across verticals; lower is better. Use when comparing unrelated sites. |
| country_rank | Integer | Regional relevance; tie-breaker for geo-focused campaigns. |
| category_rank | Integer | Contextual scale inside a vertical; excellent for ad planning within a niche. |
| engagement | JSON | Pages/session, visit duration, or bounce-like metrics. Weight quality vs. raw visits. |
| traffic_sources | JSON | Distribution by channel; de-risk inflated paid traffic; prioritize organic-heavy sites. |
| top_countries | JSON | Geo mix for localization, compliance, and regional routing. |
Pair monthly visits with categories and company data
Traffic without context can mislead. Klazify’s categorization endpoint augments traffic with IAB taxonomy and company intelligence. Here’s the official categorization sample response you can use to map traffic to content safety lists and business segments.
{
"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"
]
}
How to use these fields with traffic results:
- domain.categories: Join monthly_visits to IAB categories for ad targeting and blocking logic.
- objects.company.*: Enrich CRM or MDM systems with company and tech stack, then score with monthly_visits.
- domain_registration_data: Add age/expiration checks to evaluate stability alongside monthly_visits.
- similar_domains: Extend prospecting lists, fetching traffic for adjacent domains automatically.
Three complete JSON examples to develop against
Use the official sample below as a stable fixture while you implement parsing, mapping, and testing. Keep the structure intact in your tests to confirm your pipeline is robust to nested arrays and objects.
Sample JSON A
{
"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"
]
}
Sample JSON B
{
"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"
]
}
Sample JSON C
{
"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"
]
}
These samples help solidify your parser and mapping. Once stable, wire your tests to also validate the traffic payload structure for monthly_visits and related fields.
Operational details: batching, caching, and rate planning
While integrating traffic intelligence into production, you’ll want to plan for batching, cache strategy, and safe retries.
- Batching: Queue domains and process in controlled concurrency to match your job scheduler. If your system does nightly enrichment, accumulate domains and write back results in bulk to your data warehouse.
- Caching: Cache results per domain with a TTL aligned to your refresh cadence (e.g., monthly or biweekly). Monthly visits typically do not require per-hour updates; a domain-level cache significantly reduces calls and latency.
- Unknown/new domains: Handle nulls gracefully. Keep a dead-letter queue for retriable failures and a suppression list for hard errors (e.g., invalid TLDs).
- Retries: Since failed or unreachable calls are not billed, retry transient network errors with exponential backoff and jitter, and instrument alerts on repeated failures.
- Rate limits: Plan throughput at a high level. If your enrich job spikes, use a token bucket in your worker to smooth bursts and avoid 429s.
Mapping to your taxonomy and data model
Even when your main target is monthly_visits, category_rank and IAB mapping let you align traffic to your existing segments. A minimal schema design could be:
- fact_domain_traffic: domain, observed_at, monthly_visits, global_rank, country_rank, category_rank
- dim_domain_category: domain, iab_category, confidence
- fact_domain_engagement: domain, observed_at, engagement_json
- fact_domain_sources: domain, observed_at, traffic_sources_json
- dim_domain_geo: domain, country_code, share, observed_at
When you join traffic to categories, you can enforce brand-safety rules and contextual targeting using the IAB taxonomy values returned by categorization, while still leveraging monthly_visits for scale decisions.
Handling errors, nulls, and schema evolution
Traffic data can be sparse for brand-new or very small sites. Plan for:
- Nullable monthly_visits: Store as null and retry on your next cycle.
- Partial engagement or traffic_sources: Keep JSON fields schemaless and flatten on read for dashboards.
- Versioning: Wrap deserialization in helpers that tolerate new keys while keeping your pipeline backward compatible.
When expanding your use case, consult the Documentation for field coverage and payload structures.
Security, observability, and cost control
- Secrets: Keep the Bearer token in a secret store or environment variable; never hardcode in source control.
- Metrics: Track success rate, median latency, and per-domain cache hit ratio to optimize costs and throughput.
- Cost planning: Starter is $39.99/mo with a 7-day trial. Use caching and batch scheduling to stay efficient. Failed or unreachable calls are not billed, so retries for transient issues are safe.
If you need to manage tokens, team access, and audit trails, review the MCP program.
End-to-end example: enrich a signup with monthly visits
Consider a SaaS signup form where users enter their company website. Your backend can call the traffic endpoint, store monthly_visits, and gate trial or sales routing logic:
- If monthly_visits is above your threshold, auto-qualify and fast-track to SDR.
- If below threshold, place into a nurture track or require additional verification.
- Log category_rank and top_countries to route to the correct vertical and region.
With a domain-level cache, repeat signups from the same website won’t trigger multiple calls until your TTL expires. Add observability to alert when cached monthly_visits changes by more than a set percentage between refreshes.
Field-by-field walkthrough for developers
As you parse the traffic response, here’s a checklist of what to store and how to validate:
- monthly_visits: Required if present. Validate as non-negative integer. Use -1 only if your data store cannot handle nulls.
- ranks (global_rank, country_rank, category_rank): Optional but highly recommended. Validate as positive integers.
- engagement: JSON object. Store raw for auditability; derive display metrics downstream.
- traffic_sources: JSON object. Enforce that channel shares sum approximately to 1.0 if normalized; if counts are returned, convert to shares in your ETL.
- top_countries: Array of objects; take the top N you care about (e.g., 5) and store as rows.
Testing tips and fixtures
Use the official categorization sample responses above as fixtures to ensure your JSON parsing and joins handle nested arrays, nulls, and numeric fields. For traffic, mock the keys you consume (monthly_visits, ranks, engagement, traffic_sources, top_countries) and write contract tests that fail fast if the structure changes. Keep an integration test that executes one live call to detect auth or network regressions.
Next steps
Set up an account and get your API key to start testing monthly_visits in a notebook or service. The Starter plan is $39.99/mo with a 7-day trial, so you can prototype without long-term commitment. Failed or unreachable calls are not billed.
FAQ
- Which endpoint returns monthly_visits?
Use POST https://www.klazify.com/api/domain_traffic_intelligence with a JSON body containing {"url":"https://example.com"} and a Bearer token. - How often should I refresh monthly_visits?
Most teams refresh monthly or biweekly. Use a domain-level cache and expire on your reporting cadence to control costs. - What should I do if monthly_visits is missing?
Store null, retry on the next cycle, and avoid blocking flows that can proceed without traffic data. Keep observability to track missing rates. - Can I join traffic data with categories?
Yes. Call the categorization endpoint to get IAB categories and join via domain in your warehouse or service layer. - How are failed calls billed?
Failed or unreachable calls are not billed, so you can implement safe retries for transient errors.
Ready to pull monthly visits into your Python workflow and ship an enrichment that your team can trust? Create your account now and start building with Klazify’s domain intelligence: Register.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free