How to Get a Company's City and Country in Python
You have a dataset of signups, partner domains, or referral URLs and you need the company’s city and country in Python so you can route leads, comply with regional rules, or localize outreach. By the end of this guide, you’ll call a single endpoint to resolve a domain into company location fields (city, stateCode, countryCode), plug the result into your pipeline, and ship it with caching and batching strategies that work at scale.
Why Klazify is the right fit for resolving a company’s city and country
When your core task is to derive accurate company location from a URL or domain and act on it inside code, the API’s coverage, freshness, and predictable integration workflow matter. Here’s how Klazify aligns specifically with getting city/country data into Python pipelines:
- Accurate website categorization using AI: Even when you only need city and country, classification quality signals matter for quality control. Klazify’s content analysis helps ensure the domain actually represents the company you’re enriching, reducing false matches and allowing you to flag edge cases.
- Global coverage: Location fields such as city and countryCode are useful only if you can resolve domains in many regions. Klazify analyzes websites in multiple languages, which is essential for normalizing international domains to ISO-like location fields (e.g., countryCode).
- Real-time classification: New or updated sites can affect company resolution. Real-time analysis helps keep location data current when you re-enrich or backfill.
- Industry-level categories using IAB taxonomy: If you also need to filter or route by vertical, Klazify maps to IAB categories alongside company data. This is useful for segmentation when country-specific rules differ by industry.
- Simple API integration: A single POST with a domain yields company fields, including city, stateCode, and countryCode, ready for Python usage in CRMs, ETL jobs, and data warehouses.
- Compliance and filtering: Combining location fields with IAB categories enables you to gate access, ensure regional compliance, or whitelist by locale at the edge.
In short, you can retrieve city and country from a domain with one call, and optionally leverage categorization for downstream filtering—without building and maintaining your own crawling and NLP stack. Explore the platform at klazify.com.
What you’re building: Enrich a domain to company city and country in Python
The scenario: you collect a domain on signup (e.g., “acme.co”) and need to attach location for territory routing, dedupe, and compliance checks. We’ll call Klazify’s company endpoint, extract city and countryCode, and return a normalized object you can write to your CRM or data warehouse.
We will use this endpoint:
- POST https://www.klazify.com/api/domain_company
- Auth: Bearer {YOUR_API_KEY}
- Body: JSON with the company’s URL or domain
Key fields we will read from the response:
- name
- city
- stateCode
- countryCode
- employeesRange
- revenue
- raised
- tags
cURL: Resolve a domain to company city and country
Copy-paste this request and replace YOUR_API_KEY with your token. The example domain below is used only in this cURL so you can test quickly.
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:
- Use a full URL or bare domain in the url field.
- Failed or unreachable calls are not billed.
- Plan details and rate limits are available in the Documentation.
Python example: Extract city and countryCode safely
This Python snippet calls the same endpoint, handles common edge cases, and returns normalized data for your pipeline.
import json
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"
# Basic in-memory cache; replace with Redis or your datastore in production
CACHE = {}
CACHE_TTL_SECONDS = 7 * 24 * 3600 # cache per domain for 7 days
def cache_get(key):
v = CACHE.get(key)
if not v:
return None
expires_at, data = v
if time.time() >= expires_at:
del CACHE[key]
return None
return data
def cache_set(key, data, ttl=CACHE_TTL_SECONDS):
CACHE[key] = (time.time() + ttl, data)
def get_company_location(url_or_domain):
# normalize key for cache
key = url_or_domain.strip().lower()
cached = cache_get(key)
if cached is not None:
return cached
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {"url": url_or_domain}
resp = requests.post(API_URL, headers=headers, data=json.dumps(payload), timeout=15)
# Minimal error handling; expand per your logging/metrics standards
resp.raise_for_status()
data = resp.json()
# Some responses include a success flag. Verify and handle missing objects defensively.
objects = data.get("objects") or {}
company = objects.get("company") or {}
result = {
"name": company.get("name"),
"city": company.get("city"),
"stateCode": company.get("stateCode"),
"countryCode": company.get("countryCode"),
"employeesRange": company.get("employeesRange"),
"revenue": company.get("revenue"), # may be a range per docs
"raised": company.get("raised"),
"tags": company.get("tags") or []
}
# Cache even partial results to reduce repeat calls; adjust TTL based on your SLA
cache_set(key, result)
return result
if __name__ == "__main__":
enriched = get_company_location("https://cbsnews.com")
print(enriched)
# Example: {'name': '...', 'city': '...', 'stateCode': '...', 'countryCode': 'US', ...}
Implementation tips:
- Cache by domain for 7–30 days to save calls and reduce latency. Most company headquarters don’t move often.
- Store the original lookup domain and the resolved fields side-by-side for auditing and replays.
- For batch jobs, use connection pooling and concurrency with backoff on HTTP errors.
The official response structure and how to use it
Klazify’s platform can also return categorization and related company data. This JSON block demonstrates the overall structure, including where company fields appear. Use it as a guide for traversing the objects.company node to read location fields in your integration.
{
"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 for location enrichment:
- objects.company.city: City name for routing and localization.
- objects.company.stateCode: Region or state code when applicable.
- objects.company.countryCode: Two-letter country code you can map to your internal region table.
Other helpful fields:
- objects.company.name: Normalize or match against CRM records.
- objects.company.employeesRange: Assign lead tiers alongside location.
- objects.company.revenue and objects.company.raised: Additional context for prioritization.
- domain.categories: If you also classify content, use this for brand safety, compliance, or targeting.
How to wire the response into your pipeline
Normalize, validate, and store
- Normalization: uppercase countryCode, trim whitespace, and fall back to None if empty.
- Validation: keep a whitelist of expected ISO-like country codes; log or quarantine outliers for review.
- Storage: write city, stateCode, countryCode to dedicated columns and maintain a “last_enriched_at” timestamp.
Routing and segmentation
- Sales territory: map countryCode (and stateCode for certain countries) to account owner pools.
- Compliance: gate features by countryCode when regulations differ by jurisdiction.
- Localization: pick default language and currency for the user experience based on location fields.
Caching and refresh
- Cache per domain to reduce redundant lookups and latency. A 7–30 day TTL is typical.
- Trigger refresh on significant account events (e.g., domain change) or after cache expiration.
- Persist raw JSON snapshots for auditing and reproducible analytics.
Batching, rate limits, and operational guidance
- Batching: run enrichment as an ETL step with pagination over your source table. Use connection pooling and controlled concurrency.
- Rate limits: consult the Documentation for your plan and design backoff/retry accordingly.
- Idempotency: dedupe by domain before calling to avoid duplicate work and cost.
- Error handling: on HTTP errors or timeouts, retry with exponential backoff; on persistent failure, mark the record for later reprocessing. Failed or unreachable calls are not billed.
- Observability: track success ratio, mean latency, and cache hit rate to keep SLOs.
Handling unknown or new domains
- Soft nulls: if location fields are missing, store nulls and tag the record as “location_unresolved.”
- Retry policy: re-enrich after a delay; new domains may gain sufficient signals over time.
- Fallback strategy: if you must hard-block flows without location, use countryCode as the must-have field and allow city/stateCode to be optional.
Comparing approaches to company location resolution
| Approach | Primary Input | What You Get | Pros | Cons | Operational Fit |
|---|---|---|---|---|---|
| Klazify domain_company | URL or domain | city, stateCode, countryCode + company context | One call, normalized fields, integrates with categorization | Requires API call and token management | Best for CRMs, signups, ETL pipelines |
| Manual web scraping | Homepage HTML | Heuristic extraction of addresses | Full control | Brittle, maintenance-heavy, locale issues | Research, not production enrichment |
| IP geolocation | Server IP | Server location, not company HQ | Simple | Often wrong for HQ; CDNs obscure origin | Networking diagnostics, not enrichment |
Mapping Klazify fields to your taxonomy
- countryCode: map to your region enum (e.g., AMER, EMEA, APAC). Maintain a lookup table in your data warehouse.
- stateCode: for countries with state/province codes, map to your sub-regional routing rules.
- city: free-form text; keep normalized capitalization and consider a reference table for large metros you treat specially.
- tags and employeesRange: use for tiering or product gating alongside geography.
Putting it together: a working path you can ship
- Create a free account at Register and get an API key. Starter is $39.99/mo with a 7-day trial.
- Call POST https://www.klazify.com/api/domain_company with the signup domain.
- Parse objects.company.city, stateCode, and countryCode; store alongside the account.
- Cache per domain for 7–30 days; retry on transient errors. Failed or unreachable calls are not billed.
- Optional: also use categories from the platform for brand safety or policy enforcement.
If you also need to manage keys, usage, and workflow policies, review the MCP.
For endpoint details and more response fields, see the Documentation. Visit klazify.com to explore the broader domain intelligence suite.
FAQ
-
How should I handle domains that return no city or country?
Store nulls, mark the record as unresolved, and schedule a re-enrichment after your cache TTL. Use countryCode as the minimum required field for most routing policies.
-
Is there a bulk/batch workflow?
Yes. Run enrichment as a scheduled job over your domain list, use connection pooling and concurrency, and respect plan rate limits noted in the documentation.
-
How do I ensure I don’t pay for failures?
Log HTTP statuses and response bodies. Failed or unreachable calls are not billed, so implement retries with exponential backoff and surface persistent failures to a dead-letter queue.
-
What’s the best way to map countryCode to my internal regions?
Maintain a simple lookup table mapping countryCode to region enums and join on write in your ETL or at query time. Keep it in version control for audits.
-
Can I combine location with content categorization?
Yes. While your primary need is city/country, using categorization from the platform lets you enforce regional and industry-specific rules in one pass.
Ready to enrich domains to city and country in your Python pipelines? Create your API key now and start building with the 7‑day trial: Register.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free