Integrate the Company Location API in Python

November 21, 2026
Integrate the Company Location API in Python

You need to enrich user signups and inbound leads with reliable company location data so you can route accounts, score prospects, and comply with territory rules. In this guide, you’ll integrate Klazify’s Company Location API in Python to turn any URL or domain into actionable fields like city, stateCode, countryCode, employeesRange, revenue (as a range), raised, and tags—and ship the results into your pipeline with production-ready patterns for scale.

Why Klazify is the right fit for company location enrichment

When your workflow depends on routing accounts to the right region or building country-specific automations, accuracy and coverage of company location data matter. Klazify analyzes the website itself and extracts company signals that are tied to the domain you send. Here’s how that helps for location-driven use cases:

Illustration: Integrate the Company Location API in Python
  • Accurate website categorization using AI: Klazify inspects on-page content rather than relying only on metadata, improving the odds of aligning a domain with the right company entity and surface-level details (like location and size) that you’ll use to route leads.
  • Global coverage: City, stateCode, and countryCode are provided using internationally relevant formats, letting you normalize to your own region tables when operating across multiple countries and languages.
  • Real-time classification: Rather than fixed snapshots, Klazify analyzes domains dynamically, which helps reduce “unknown” outcomes for newly launched or updated sites.
  • Industry-level categories (IAB): If you combine location routing with vertical-based routing, Klazify’s IAB mapping can complement your lead assignment or brand-safety rules.
  • Simple API integration: A single REST endpoint gives you company location, employeesRange, revenue (range), raised, and business tags in one response—easy to plug into Python-based ETL jobs or microservices.
  • Compliance and filtering: Enforce country restrictions, geofenced offerings, or partner eligibility by evaluating location fields alongside categories and tags in one call.

If you’re new to the platform, you can explore capabilities and get started quickly at klazify.com. To begin integrating, create a free trial on the Starter plan ($39.99/mo, 7‑day trial) and retrieve your API key.

What you’ll build: enrich any domain with location fields in Python

We’ll implement a small Python utility that:

  • Takes a URL or domain from your form, CRM, or data file.
  • Calls the Company endpoint to retrieve company details.
  • Extracts name, city, stateCode, countryCode, employeesRange, revenue (range), raised, and tags.
  • Normalizes and returns a lean record you can store or forward to your CRM, CDP, or data warehouse.

We’ll also cover caching, batching, error handling, and mapping these fields to your internal schema so you can run this at scale.

Make your first request (cURL)

The Company Location API is available via a POST request. Authenticate using a Bearer token and include the URL you want to enrich in JSON. Failed or unreachable calls are not billed.

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

Notes:

  • Authorization: Use your API key as a Bearer token.
  • Body: Provide a fully qualified URL or bare domain in the url field.
  • Timeouts: In production, set a network timeout and a limited number of retries with backoff.

You can generate and manage your key after you Register. Endpoint reference is available in the Documentation.

Python example: extract location, size, and business signals

This snippet posts a domain, checks for success, and extracts the fields used most often in routing and enrichment.

import os
import json
import time
import requests
from typing import Dict, Any, Optional

API_URL = "https://www.klazify.com/api/domain_company"
API_KEY = os.getenv("KLAZIFY_API_KEY", "YOUR_API_KEY")

SESSION = requests.Session()
SESSION.headers.update({
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
})

def fetch_company(url: str, timeout: float = 10.0, retries: int = 2, backoff: float = 0.75) -> Optional[Dict[str, Any]]:
    payload = {"url": url}
    attempt = 0
    while True:
        try:
            resp = SESSION.post(API_URL, json=payload, timeout=timeout)
            # Non-2xx codes should raise for handling
            resp.raise_for_status()
            data = resp.json()
            # Expect a structure with objects.company when available
            company = (data or {}).get("objects", {}).get("company")
            return company
        except requests.RequestException as e:
            attempt += 1
            if attempt > retries:
                # Log and return None; failed or unreachable calls are not billed
                print(f"Request failed after {retries} retries: {e}")
                return None
            time.sleep(backoff * attempt)

def normalize_company_record(company: Dict[str, Any]) -> Dict[str, Any]:
    if not company:
        return {}
    return {
        "name": company.get("name"),
        "domain_url": company.get("url"),
        "city": company.get("city"),
        "state_code": company.get("stateCode"),
        "country_code": company.get("countryCode"),
        "employees_range": company.get("employeesRange"),
        # Revenue is provided as a range. Treat it as non-exact for scoring/segmentation.
        "revenue_range": company.get("revenue"),
        "raised": company.get("raised"),
        "tags": company.get("tags", []),
        # Keep the raw object if downstream consumers need tech/categories later
        "raw": company
    }

def enrich(url: str) -> Dict[str, Any]:
    company = fetch_company(url)
    if not company:
        return {"status": "not_found", "input": url}
    return {
        "status": "ok",
        "input": url,
        "company": normalize_company_record(company)
    }

if __name__ == "__main__":
    test_url = "https://cbsnews.com"
    result = enrich(test_url)
    print(json.dumps(result, indent=2))

Implementation notes:

  • Treat revenue as a range, not an exact value, for routing and scoring.
  • Keep employeesRange as-is or map it to your numeric buckets before saving to your CRM.
  • Cache by registrable domain (e.g., example.com) to avoid repeat calls on the same input.

Understand the full response and what to use

Below is the official sample JSON response format (unchanged). It includes domain categories, social links, a logo URL, and company objects with name, location, employee size, revenue, raised, tags, and detected technologies.


{
    "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 typically plug into your pipeline:

  • objects.company.name: Company display name.
  • objects.company.city, stateCode, countryCode: Location fields for territory routing and compliance checks.
  • objects.company.employeesRange: Size bucket (e.g., “1–10”, “11–50”, “100K+”).
  • objects.company.revenue: Use as a range for segmentation and scoring, not an exact figure.
  • objects.company.raised: Total capital raised where available; useful for prioritizing venture-backed accounts.
  • objects.company.tags: High-level business descriptors that can drive ICP filters.
  • domain.categories: IAB-aligned categories; helpful if routing depends on industry alongside location.
  • domain.logo_url: Useful when enriching CRM/account list views.

Map the response to your systems

The table below shows a practical mapping from Klazify fields to common CRM or data warehouse columns you might maintain. Adapt to your schema and taxonomies as needed.

Klazify field Suggested destination Notes
objects.company.name accounts.name Use for display; do not dedupe solely on name—combine with domain.
objects.company.url accounts.domain Primary key for caching and deduplication.
objects.company.city accounts.city String; consider normalizing diacritics for search.
objects.company.stateCode accounts.region_code Typically two-letter codes for certain countries (e.g., US states).
objects.company.countryCode accounts.country_iso2 Uppercase ISO 3166-1 alpha-2 recommended.
objects.company.employeesRange accounts.employees_bucket Keep as categorical; map to numeric spans only if needed.
objects.company.revenue accounts.revenue_bucket Treat as a range, not an exact amount, in your scoring rules.
objects.company.raised accounts.capital_raised Populate only when present to avoid noisy defaults.
objects.company.tags accounts.tags Array; store as a JSON array or many-to-many table.
domain.categories accounts.iab_categories Store confidence; use for industry/brand-safety logic.
domain.logo_url accounts.logo_url Display in UI; cache via your CDN if desired.

Run it reliably at scale

Caching and idempotency

  • Cache by registrable domain (e.g., example.com) for a configurable TTL (e.g., 24–72 hours), since company data won’t change minute-to-minute.
  • Store the raw response for audit and replay; keep a normalized record for quick reads in your app.
  • Use ETag-style fingerprints or last-updated timestamps in your own store to avoid unnecessary overwrites.

Batching and throughput

  • Batch domains in worker queues. A simple pattern is “fan-out” jobs that each process N domains serially with small sleeps to smooth bursts.
  • If you parallelize, cap concurrency to a safe number and use connection pooling (e.g., requests.Session in Python) to minimize TLS overhead.

Error handling and retries

  • Implement short timeouts and limited retries with exponential backoff. Log all request IDs and response codes for observability.
  • When a domain is unreachable or times out, mark the record as “pending” and reschedule. Failed or unreachable calls are not billed.
  • Fallback behavior: return a minimal object with the input URL and a status flag so downstream systems don’t block.

Unknown or new domains

  • If a domain is new and returns sparse data, enqueue a recheck after a delay. You can escalate to manual review for high-value accounts.
  • Keep your cache soft—allow a miss to trigger a fresh lookup even if a stale value exists.

Combine location with categorization when it matters

Many routing rules depend on both where a company is based and what industry it operates in. Alongside location fields, the same response provides IAB-aligned categories you can store and evaluate with confidence scores. If your taxonomy differs from IAB, maintain a simple mapping table from IAB names to your internal industry or segment codes and resolve it at write-time.

  • Use domain.categories[].name for industry routing.
  • Use domain.categories[].confidence as a threshold for automatic assignment vs. manual review.

Explore categorization capabilities on klazify.com and review endpoint details in the MCP.

Practical details you’ll want on day one

  • Data shapes: Treat revenue as a range and employeesRange as a categorical bucket—avoid using them as exact numeric metrics.
  • Currencies and units: Revenue values should be handled as approximations for scoring and segmentation; don’t perform precise financial math on them.
  • Timestamps and timezones: If you attach your own processed_at or fetched_at timestamps, store in UTC and ISO 8601 for consistency across services.
  • Versioning: Keep a schema version for your normalized record so ETL changes don’t break downstream dashboards.
  • Security: Load the API key from environment variables or a secrets manager; don’t hardcode it in source control.

Testing, monitoring, and costs

  • Plan: Starter is $39.99/mo with a 7‑day trial so you can validate fit quickly.
  • Non-billable failures: Failed or unreachable calls are not billed—instrument your logs to distinguish them from successful enrichments.
  • Synthetic tests: Maintain a small suite of known domains to check for regressions in your parsing and mapping logic.
  • Observability: Track success rate, average latency, and percentage of “unknown” records across queues.

Putting it all together

With a single POST to the Company endpoint, you’ll capture city, stateCode, countryCode, employeesRange, revenue (range), raised, and tags—ready to route leads, score accounts, and enforce country-specific logic. The Python example above is minimal by design; integrate it into your queue workers or ETL jobs, add caching by domain, and map fields to your CRM schema using the table provided.

FAQ

  • Can I send either a URL or a bare domain?
    Yes—include the value in the JSON body as url. The service will resolve and return company data tied to the domain.
  • How should I treat revenue and employee size?
    Treat revenue as a range and employeesRange as a bucket for routing and segmentation, not exact values.
  • What if the domain is new or returns incomplete data?
    Cache what you receive, mark the record as partial, and schedule a retry. You can also flag high-value accounts for manual review.
  • Is there a way to align Klazify categories with my own taxonomy?
    Yes—store IAB names and maintain a mapping table to your internal categories. Apply it at write-time so downstream systems consume your normalized codes.
  • How do I manage throughput safely?
    Use a worker queue, requests.Session for connection pooling, bounded concurrency, and retries with backoff. Cache results per domain to reduce calls.

Ready to enrich domains with location and company context? Start your trial and get an API key now: Register. Review the Documentation for endpoint details and explore platform capabilities on klazify.com.

Ready to use Klazify?

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

Get Started Free