How to Get the IAB Category for a Website in Python
You need to look up a website’s IAB category in Python so you can block a content class, enrich a signup with industry tags, or audit where your ads run. By the end of this guide, you’ll call the Klazify API to retrieve IAB taxonomy categories for any domain, parse the response in Python, and wire the results into your filtering, enrichment, or analytics pipeline.
Why Klazify is a strong fit for IAB classification in Python
When you need IAB categories to automate decisions (e.g., brand safety, contextual targeting, content filtering), details matter: accurate labels, fast response times, and easy integration. Klazify focuses on extracting reliable, up-to-date signals directly from live website content and mapping them to industry-standard IAB taxonomy keys you can act on immediately in code.
- Accurate website categorization using AI: Klazify analyzes on-page content (not just metadata), so you get more precise categories for nuanced sites and sections. That’s critical when a single mislabel can block a good page or let a risky one through.
- Global coverage: You can classify domains across multiple languages, enabling consistent categorization across markets and regions from a single integration point.
- Real-time classification: Because classifications are derived from live content, you avoid depending on outdated lookups, which reduces false positives/negatives when sites change their focus.
- Industry-level IAB taxonomy: The response includes IAB taxonomy mappings using sibling keys on each category object (for example, an IAB code alongside the category name), giving you granular, standards-aligned labels for ad tech and brand safety.
- Simple API integration: A single POST request with a URL is enough to get IAB categories. The Python examples below can drop directly into your service or job.
- Compliance and filtering: If your goal is to block or whitelist categories, IAB keys let you enforce clear, organization-wide policies consistently across products and teams.
If you’re ready to try it, create a free account and get an API key: Register. You can also explore the endpoints here: Documentation.
What we’re building: get IAB categories for a URL
We’ll call the Klazify endpoint designed for IAB taxonomy retrieval. The workflow is:
- Send a POST request with the website URL.
- Read the returned categories array.
- Extract the category name and its IAB keys (sibling fields on each category object).
- Use the result to allowlist/block content, add tags to a lead or company profile, or route traffic in your ad stack.
We’ll demonstrate the HTTP request with curl and then show a Python script you can adapt. The JSON format you’ll parse in your app is also shown below, with IAB mappings as sibling keys in each category object.
The IAB categories endpoint
Endpoint:
- POST https://www.klazify.com/api/domain_iab_categories
Authentication:
- Authorization: Bearer YOUR_API_KEY
Request body (JSON):
- {"url": "https://example.com"}
curl example: get IAB categories for a website
curl -sSL -X POST "https://www.klazify.com/api/domain_iab_categories" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://cbsnews.com"}'
Replace YOUR_API_KEY with your token. The response contains category objects; each object includes a human-readable name and one or more IAB keys as sibling fields you can use for policy checks and integrations.
Python: request IAB categories and extract the fields you need
The snippet below posts a URL to the IAB endpoint, finds the categories array, and reads sibling IAB keys present for each category. You can then enforce allow/block decisions or append the IAB codes to your CRM or analytics warehouse.
import os
import requests
API_KEY = os.getenv("KLAZIFY_API_KEY", "YOUR_API_KEY")
ENDPOINT = "https://www.klazify.com/api/domain_iab_categories"
def get_iab_categories(url: str):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {"url": url}
resp = requests.post(ENDPOINT, json=payload, headers=headers, timeout=15)
resp.raise_for_status()
data = resp.json()
# Categories may be provided in a 'domain' object as shown in the example response below.
# We'll handle that shape and also a top-level 'categories' as a fallback.
categories = []
if isinstance(data, dict):
if "domain" in data and isinstance(data["domain"], dict) and "categories" in data["domain"]:
categories = data["domain"]["categories"] or []
elif "categories" in data:
categories = data["categories"] or []
results = []
for c in categories:
if not isinstance(c, dict):
continue
name = c.get("name")
confidence = c.get("confidence")
# Collect all sibling IAB keys for this category (e.g., "IAB-632-596", "IAB12", etc.)
iab_keys = {k: v for k, v in c.items() if k.startswith("IAB")}
results.append({
"name": name,
"confidence": confidence,
"iab_keys": iab_keys
})
return results, data
if __name__ == "__main__":
url_to_classify = "https://cbsnews.com"
categories, raw = get_iab_categories(url_to_classify)
print("Detected categories:")
for cat in categories:
print(f"- {cat['name']} (confidence={cat['confidence']})")
if cat["iab_keys"]:
print(" IAB mappings:")
for k, v in cat["iab_keys"].items():
print(f" {k}: {v}")
# Example: decide if the site passes an allowlist policy of acceptable IAB keys.
allowed_iab_prefixes = {"IAB-632"} # example policy prefix match
allowed = any(
any(k.startswith(tuple(allowed_iab_prefixes)) for k in cat["iab_keys"].keys())
for cat in categories
)
print(f"Allowed by policy? {allowed}")
The JSON response you will parse
Below is the official example structure to illustrate how categories and IAB mappings appear. Note how the category object includes a human-readable name and a sibling IAB key (e.g., “IAB-632-596”).
{
"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"
]
}
Fields you’ll use most often:
- domain.categories: An array of category objects for the URL or domain.
- domain.categories[].name: Human-readable, hierarchical category path.
- domain.categories[].confidence: Numeric confidence score for the classification.
- domain.categories[].IAB...: One or more IAB keys as sibling fields (for example, “IAB-632-596”). The key name encodes the IAB taxonomy path, and the value is a textual mapping. Use these for policy and integration logic.
- domain.logo_url: Helpful for UI/ops dashboards when reviewing classifications.
How to act on IAB categories
Once you’ve retrieved categories, plug them into your workflow:
- Brand safety and ad placement: Allow or deny ad delivery if any returned IAB key matches your blocklist. For example, if your policy forbids a particular IAB family, check sibling keys on each category and short-circuit delivery.
- Signup enrichment: Attach the IAB mapping to a lead or signup domain to pre-segment accounts (e.g., a lead from a site categorized under a specific IAB code might route to a specialized SDR team or product line).
- Content filtering: In corporate networks or parental controls, maintain an IAB allowlist and block domains whose categories fall outside that list.
- Analytics and audience: Store IAB keys in your warehouse to analyze engagement by content class or to power downstream recommendation and targeting.
Understanding category names and IAB keys
Each category object may contain multiple identifiers:
- name: A descriptive, hierarchical path like “/Computers & Electronics/Consumer Electronics.”
- IAB keys: Keys that begin with “IAB” (e.g., “IAB-632-596”). These are sibling fields on the category object, not nested in a separate IAB_categories array. Your integration should scan category objects for keys that start with “IAB” and collect them.
In practice, store both because:
- name is easy to display in UI and support ticket reviews.
- IAB keys are stable targets for automated policies, reporting, and data joins across systems.
Operational guidance: batching, caching, latency, and unknown domains
Reliability at scale comes down to predictable throughput and repeatable decisions. Here is how to integrate smoothly:
Batching and throughput
- Batch by concurrency: While the request model is one URL per POST, you can parallelize calls from a worker pool. Keep an eye on your job queue and apply backoff on transient HTTP errors.
- Queue design: For large lists (e.g., nightly audits), push URLs into a queue and let workers process at a controlled concurrency. Record classification time in your output so you can age out stale results later.
Caching and TTLs
- Cache per domain or registrable domain: If you classify multiple pages on the same site, reuse prior results unless you need page-level specificity. Use a TTL that matches how fast you expect the site content to change.
- Store raw JSON: Save the raw response alongside parsed fields. It helps during audits and reprocessing if your category mapping policy evolves.
Handling unknown or new domains
- Empty or low-confidence categories: If the category array is empty or confidences are below your threshold, fall back to a review queue, a retry policy, or a “temporary unknown” label that restricts risky actions (e.g., don’t show ads).
- Retry strategy: Use exponential backoff for network errors and recheck after a short delay. Failed or unreachable calls are not billed, reducing the cost of safe retry logic.
Mapping to your own taxonomy
- Build a mapping layer: Maintain a lookup from IAB keys to your internal categories. Because IAB keys are distinct fields on each category, it’s straightforward to translate into your own enums or dimensions.
- Fallback to name: If a category lacks an IAB key, use the human-readable name and a best-effort mapping (documented exceptions in your policy).
Comparing fields you’ll most likely store
| Field | Why store it | How it’s used downstream |
|---|---|---|
| domain.categories[].name | Readable label for UI and audits | Dashboards, content review workflows |
| domain.categories[].confidence | Decision thresholding | Block/allow based on confidence; QA low-confidence cases |
| domain.categories[].IAB... | Standards-based taxonomy ID | Policy enforcement, analytics joins, ad routing |
| domain.logo_url | Operational clarity | Agent tools, backoffice review pages |
End-to-end example: build a simple allowlist filter
Suppose your ad server should only run on sites within a specific IAB family. Your steps:
- Call the IAB endpoint with the page URL.
- Extract all sibling IAB keys from each category in the response.
- Compare against your allowlist. A match at any category is sufficient to proceed.
- If no match, withhold ads and log the result for later review. If the confidence is low, push to a review queue regardless of a match.
This approach yields deterministic behavior and a clear audit trail because you store the exact keys returned by the API and the decision logic used.
Working with other Klazify data when you need it
Klazify provides additional domain signals you can use alongside categories:
- Company details: Enrich leads or accounts with organization name, location, size, revenue, and tags.
- Similar domains: Expand targeting lists or create exclusions for brand safety checks.
- Logo URL and social media presence: Improve reviewer tooling and data completeness in your CRM.
When you need a broader dataset beyond IAB categories (e.g., classifications, logos, social links, or company profile from a single call), you can use the main categorization endpoint shown in the docs: Documentation. For managed compliance workflows and partner integrations, explore the MCP page.
Cost, errors, and rollout tips
- Plan selection: A Starter plan is available at $39.99/mo with a 7-day trial, which is enough to validate your integration and tune your policies before scaling.
- Error handling: Failed or unreachable calls are not billed. Implement retry with exponential backoff for safe, resilient ingestion.
- Rollout: Start with read-only logging to compare your current rules with IAB-driven logic. Once aligned, flip to enforcement and gradually expand your allowlists/blocklists.
Troubleshooting and practical tips
- HTTP 401/403: Verify your Bearer token and that it hasn’t expired or been mistyped.
- Empty categories: Queue a recheck later and apply a conservative default policy (e.g., no ads, restricted access) until classification is known.
- Inconsistent mapping: Always parse category objects dynamically for keys starting with “IAB”; avoid hardcoding a field name like “IAB_categories.” IAB IDs are sibling keys on each category.
- Latency budgeting: For synchronous flows (e.g., serving ads), cache domain-level results with a TTL and revalidate asynchronously in a background process.
FAQ
-
Where in the JSON do I find the IAB code?
In each category object, look for keys that start with “IAB” (for example, “IAB-632-596”). These are sibling fields next to name and confidence. -
Can I use these results for allow/deny policies?
Yes. Extract the IAB keys from returned categories, compare against your allowlist or blocklist, and make a decision. Store the raw JSON for audits. -
What should I do if the API returns low confidence?
Set a confidence threshold. If categories fall below it, send the domain to a review queue, retry later, or apply a safer default policy. -
How do I scale classification for millions of domains?
Use a worker pool to parallelize POST requests, cache by domain with a TTL, and reclassify on a schedule. Save the raw JSON and your parsed fields for fast lookups. -
How do I get started?
Create a free account to get your API key and try the curl/Python examples above: Register.
Ready to ship your integration? Grab your API key and classify your first domain in minutes. Create a free account here: Register. If you need endpoint specifics or example payloads, check the Documentation, and review integration options on MCP.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free