Company Data API in Python: Firmographics from a Domain

October 05, 2026
Company Data API in Python: Firmographics from a Domain

Your product needs firmographic facts from a domain—think: “What’s the company name, which city are they in, and roughly how big are they?” By the end of this guide, you’ll post a domain to Klazify’s Company Data API from Python, parse the JSON, and ship those fields into your enrichment or risk pipeline with caching, retries, and sensible fallbacks.

What you’ll build: firmographics from a domain

The Company Data API converts a URL or domain into core firmographic attributes you can use across growth, trust and safety, and analytics workflows. Given a domain, Klazify returns company data where you can read:

  • Company name (objects.company.name)
  • City (objects.company.city)
  • Employee range (objects.company.employee_range)

This is especially useful when you need to:

  • Enrich a signup in real time: infer the organization behind an email’s domain and store their name, city, and size band.
  • Score leads: route larger companies (by employee range) to the right SDR team and flag self-service for smaller orgs.
  • Automate risk checks: block or review access from domains outside your target regions based on city or related signals.
  • Segment analytics: break down usage or revenue by company size without asking users to self-report.

We’ll focus on the dedicated endpoint for company data. You’ll learn how to authenticate, parse the response, and operationalize it at scale. If you’re new to Klazify, start at the homepage to see how the platform fits domain intelligence use cases, then come back to wire it up.

Go live in four steps

  1. Register for a free 7-day trial (Starter $39.99/mo afterward).
  2. Copy your Bearer API key from your account dashboard.
  3. POST to /api/domain_company with a form field named url (the full URL or just the domain).
  4. Store objects.company.name and objects.company.city, and, when available, objects.company.employee_range.

You can find more request/response details in the product Documentation. If your organization needs governance or policy alignment for how this data is used across teams, review the MCP page as well.

Make your first request

Below is the official request example. It posts a sample URL (https://www.cbsnews.com) and reads the company object returned by the Company Data API.

Copy, paste, and replace YOUR_API_KEY with your Bearer token. Change the url form value to the domain you want to enrich in production.

curl 'https://www.klazify.com/api/domain_company' -X POST -H 'Authorization: Bearer YOUR_API_KEY' --data $'url=https://www.cbsnews.com'

Official JSON response and what to read

Here’s the official response for the CBS News sample (timestamp 2022-12-19). We’ll walk through the fields you’ll actually use right after the JSON.

{"success": true, "objects": {"company": {"name": "CBS News", "city": "New York", "stateCode": "NY", "countryCode": "US", "employeesRange": "1K-5K"}}}

How to interpret and use the fields you care about:

  • objects.company.name: The resolved company’s official name. Use this to normalize display names across your CRM and analytics. If you already store user-submitted company names, keep both the original and the normalized value for traceability.
  • objects.company.city: City for the company. Useful for regional routing, location-based risk checks, or tailoring outreach by geography.
  • objects.company.employee_range: Size band for approximate headcount. Map this to your internal size tiers for scoring, routing, or segmentation. When missing, fall back to “unknown” and use downstream defaults.
  • Other fields (if present): Treat any additional attributes as optional. Persist them if they’re useful for your use case, but don’t block your pipeline when a field is absent.

Note: The sample above uses https://www.cbsnews.com as the input to demonstrate a real response. In your integration, pass the domain you need to enrich (e.g., the domain extracted from a user’s email or the website field in a signup form) to get firmographics for that organization.

If the response contains a top-level success boolean and it’s false, read the error payload (if provided) and handle gracefully. For example, you might retry once on a transient error, or skip and record the domain for later review when the error indicates the domain cannot be resolved. Never assume every domain will have a complete company record.

Python example: request, parse, and store

The following Python snippet shows how to call the endpoint, extract firmographic fields, and apply basic error handling. It posts the same request you saw in the official example and demonstrates safe parsing when values are missing.

import os
import time
import requests

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

def get_company_data(domain_or_url, timeout=10):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
    }
    data = {
        "url": domain_or_url
    }
    try:
        resp = requests.post(API_URL, headers=headers, data=data, timeout=timeout)
        resp.raise_for_status()
        payload = resp.json()
    except requests.RequestException as e:
        # Network or HTTP error; log and surface a structured failure
        return {"ok": False, "error": f"http_error: {e}"}
    except ValueError:
        # JSON parsing error
        return {"ok": False, "error": "invalid_json"}

    # If the API includes a success flag, honor it; otherwise treat 200 + JSON as success
    if isinstance(payload, dict) and payload.get("success") is False:
        return {"ok": False, "error": payload.get("message", "unknown_error"), "raw": payload}

    # Defensive parsing: treat missing keys as None
    company_obj = (payload.get("objects") or {}).get("company") or {}
    result = {
        "ok": True,
        "name": company_obj.get("name"),
        "city": company_obj.get("city"),
        "employee_range": company_obj.get("employee_range"),
        "raw": payload,  # keep the full payload for debugging or future fields
    }
    return result

if __name__ == "__main__":
    # Example: enrich CBS News (replace with your target domain)
    res = get_company_data("https://www.cbsnews.com")
    if not res["ok"]:
        print(f"Lookup failed: {res['error']}")
    else:
        print(f"Company: {res['name']}")
        print(f"City: {res['city']}")
        print(f"Employee range: {res['employee_range']}")
        # Persist to your data store here (idempotent upsert keyed by domain)

Where to insert this in your pipeline

Here are common integration points and how to shape the request/response around them:

  • Signup enrichment: After email validation, parse the email’s domain (e.g., “example.com”), call the API, and attach name, city, and employee_range to the user profile. If you also collect a website field, prefer the website’s domain.
  • CRM enrichment: On lead creation or update, run the lookup asynchronously and upsert firmographics onto the Account object. Save the raw response in an audit field for transparency.
  • Security controls: In an allow/deny decision, require that the fetch completes within a short timeout. On timeout or failure, treat the result as “unknown” and apply your default policy (e.g., queue for manual review or apply stricter limits).

Data modeling: mapping and storage

Define a light, forward-compatible schema for your company table or enrichment object. Persist the fields you use today and keep a raw JSON column for future fields without migrations. A simple mapping might look like this:

Field you store Source path Type Notes / Example uses
company_name objects.company.name string Normalize display names in CRM, analytics, and billing.
company_city objects.company.city string Regional routing, geo-based policy checks, territory assignments.
employee_range objects.company.employee_range string Map to internal size tiers for scoring, quotas, or pricing experiments.
source_domain (input) string Primary key for idempotent upserts; store the domain you looked up.
klazify_raw (full JSON) json Keep the entire payload for audits and future fields.

Operational guidance for scale

Caching and deduplication

  • Cache results by normalized domain (e.g., lowercase, strip protocol and path). Consider subdomain rules that fit your use case; for corporate sites, top-level domains often suffice.
  • Use a TTL appropriate for your staleness tolerance. Company name and city rarely change; employee ranges may change less frequently than traffic-driven signals. In most enrichment flows, caching for days or weeks is reasonable.
  • Write idempotent upserts keyed by domain. If a lookup repeats, update changed fields and keep a last_seen timestamp on your side.

Unknown or new domains

  • If the API returns success=false or a missing objects.company, set your fields to null and record the attempt. You can schedule a later retry, for example after 24 hours, in case the domain becomes resolvable.
  • Use sensible defaults downstream. For example, treat a missing employee_range as “unknown” rather than “small.”

Throughput, batching, and rate limits

  • Send concurrent requests with backoff and jitter, but cap concurrency to respect API rate limits. If you see HTTP 429 or explicit rate-limit errors, reduce concurrency and retry with exponential backoff.
  • Where possible, run enrichment asynchronously and queue lookups to smooth spikes.
  • Batching strategy: de-duplicate domains in your queue first; then process in small worker pools (e.g., 5–20 concurrent workers), measuring latency and error rate to tune.

Error handling and retries

  • Retry on network timeouts or 5xx once or twice with exponential backoff. Avoid infinite retries.
  • Do not retry immediately on 4xx errors that indicate invalid input; instead, sanitize your domain and re-queue only after correcting the input.
  • Log the domain, HTTP status, and a compact error message for observability.

Security and compliance

  • Use HTTPS only and keep your Bearer token outside source control (e.g., environment variables or a secrets manager).
  • Rotate keys periodically and revoke unused credentials.
  • Restrict where the key can be used from and monitor access in your logging system.

Input normalization: feeding clean domains

You’ll get better hit rates and fewer errors by standardizing inputs:

  • Accept either a full URL (https://example.com/path) or a bare domain (example.com). Extract the registrable domain if you ingest arbitrary URLs.
  • Lowercase, trim whitespace, and strip trailing slashes. Remove URL fragments and query strings.
  • Handle internationalized domains consistently in your system (punycode to ASCII if needed) before sending to the API.

Governance: mapping employee_range to internal tiers

Downstream systems often work with custom size tiers (e.g., Small, Mid-Market, Enterprise). Create a deterministic mapping from objects.company.employee_range to your tiers and document it alongside your data contracts. Keep unknowns explicit, and don’t overload them as a proxy for “small.” If you maintain centralized policy or taxonomy references, align them with your organization’s model and review processes described in the MCP.

End-to-end example flow

  1. User signs up with email [email protected] and provides website https://www.contoso.com.
  2. Your service validates the website field; if absent, fallback to the email domain.
  3. Call /api/domain_company with url=https://www.contoso.com and parse the JSON.
  4. Upsert into your “companies” table:
    • company_name = objects.company.name
    • company_city = objects.company.city
    • employee_range = objects.company.employee_range
    • source_domain = contoso.com
    • klazify_raw = full JSON
  5. Cache the result keyed by domain with your chosen TTL to avoid redundant lookups.
  6. Emit an event (e.g., CompanyEnriched) for downstream consumers (CRM sync, scoring, analytics).

Troubleshooting tips

  • Start with the official curl and confirm a 200 response before you write app code.
  • If you consistently see empty company fields, test with a well-known domain (like in the sample) to isolate whether it’s input-specific or environmental (auth, network, etc.).
  • Log raw payloads for failed or partial results in a temporary store. This accelerates debugging without redeploys.
  • Re-run a few known-good domains in CI to catch unexpected contract changes in your parsing layer.

Production checklist

  • Authentication: Bearer token loaded from secure storage.
  • Input hygiene: URLs/domains normalized consistently.
  • Parsing: Defensive access to optional fields with safe defaults.
  • Resilience: Timeouts, retries with backoff, and clear error surfaces.
  • Caching: Idempotent upserts and TTLs aligned with your staleness tolerance.
  • Observability: Metrics on success rate, latency, and cache hit ratio.
  • Documentation: Data contracts and mappings (e.g., employee_range → internal tiers) shared with stakeholders.

When to consider plan upgrades

If you’re enriching a trickle of signups or nightly CRM updates, the Starter plan with a 7-day trial may be sufficient to validate your flow. As volume grows, measure concurrency and cache hit rates to estimate steady-state call volume and decide on plan adjustments. For any specifics on quotas, advanced usage, or endpoint details, consult the Documentation and your account dashboard.

You can explore more platform capabilities at the Klazify website and integrate additional signals alongside company data as your use cases expand.

FAQ

What if the response doesn’t include employee_range?
Treat it as unknown, keep the raw response, and proceed with defaults. You can schedule a later retry if the record is important to your workflow.

How should I handle subdomains (e.g., blog.example.com)?
Normalize to the registrable domain for caching and identity unless your use case truly differs by subdomain. Pass either the full URL or the base domain to the API; be consistent in your inputs.

Can I use this synchronously in a signup flow?
Yes, but enforce timeouts and define a fallback path when the call fails or exceeds your latency budget. Many teams enrich asynchronously and update the profile shortly after creation.

What do I do when the API returns success=false?
Check the accompanying message if present, avoid infinite retries, and log the domain for later review. Retry transient errors with backoff; for invalid inputs, correct the domain first.

Where can I see all fields and constraints?
Review the endpoint details in the Klazify Documentation and test with your domains to understand which fields populate for your dataset.

Get started

Spin up your enrichment in minutes. Create a free account, grab your key, and post your first domain to the Company Data API. Register now and use the 7-day trial to validate your Python integration before rolling it out to production.

Ready to use Klazify?

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

Get Started Free