How to Get a Company Logo in Python
You have a sign-up flow or CRM job that takes a user’s domain and shows their company logo in your product. By the end of this guide, you’ll have a working Python function that returns a hosted, production-ready logo URL for any given domain, plus practical guidance to cache, validate, and plug it into your pipeline.
Why Klazify is the best fit for fetching and using company logos
When your goal is to reliably render a company logo from a domain—at scale—you need more than a static database. You need an API that can discover the right brand asset, keep it fresh, and give you the context to decide if and how to use it in your UI. Klazify’s strengths line up with this job:
- Accurate website categorization using AI: Klazify analyzes full website content, which helps it also identify and surface the correct brand assets tied to the canonical site, not random image URLs.
- Global coverage: If your users paste domains from multiple countries and languages, Klazify can still identify the site and locate the appropriate logo asset.
- Real-time classification: You’re not stuck with stale logos—Klazify’s analysis runs in real time, which is critical when brands update their identity.
- Industry-level categories with IAB mapping: If you also want to gate where a logo appears (for example, only show logos for certain industries), Klazify’s categorization makes it simple to filter or whitelist domains based on standardized IAB categories.
- Simple API integration: A straightforward REST call returns a hosted logo URL you can drop directly into your frontend, email templates, or reports.
- Compliance and filtering: When you need to avoid rendering logos from sites that don’t fit your policy, pair the logo call with categorization data to decide what to show and where.
If you’re building onboarding enrichment, account overview cards, or partner directories, Klazify’s combination of logo URL extraction and content classification provides the control you need to both display the right logo and enforce guardrails.
What we’re building: a Python function that returns a hosted logo URL
We’ll call Klazify’s logo endpoint with a user-provided domain or URL, handle basic errors, and extract the logo URL from the JSON response. You can then:
- Display the logo in your product (cards, headers, tables).
- Persist a cached copy of the logo URL with your customer record.
- Optionally enrich the same domain with categories and company data for policy checks and segmentation.
We’ll start with a minimal request, then discuss batching, caching, fallbacks, and integration patterns.
Endpoint and request: get a hosted logo URL
Use the logo endpoint to request a hosted logo for a domain or URL. Authenticate with a Bearer token and post the target URL in JSON.
curl -s -X POST "https://www.klazify.com/api/domain_logo" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://cbsnews.com"}'
Notes:
- Replace YOUR_API_KEY with your API key.
- Use a fully qualified URL or bare domain. Klazify will resolve the canonical site and return a hosted logo URL in the JSON.
- If the target site is unreachable or the request fails, the call is not billed.
If you don’t have an account yet, you can start on the Starter plan ($39.99/mo) with a 7-day trial. Create your key here: Register.
Python implementation
The snippet below posts the user’s domain to the logo endpoint, extracts a logo URL from the JSON, and returns it as a string. It’s designed to be simple to drop into a webhook, background job, or CLI enrichment tool.
import os
import requests
API_KEY = os.getenv("KLAZIFY_API_KEY", "YOUR_API_KEY")
API_URL = "https://www.klazify.com/api/domain_logo"
def get_company_logo_url(target_url: str) -> str | None:
"""
Returns a hosted logo URL for the given domain/URL, or None if not available.
"""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {"url": target_url}
try:
resp = requests.post(API_URL, json=payload, headers=headers, timeout=20)
# If the site is unreachable or the call fails, Klazify does not bill the request.
resp.raise_for_status()
except requests.RequestException as e:
# Network error, timeout, 4xx/5xx, etc.
print(f"Klazify logo request failed: {e}")
return None
data = resp.json()
# Extract a hosted logo URL from the JSON.
# If the endpoint returns a nested structure, check both top-level and nested fields.
logo_url = None
if isinstance(data, dict):
logo_url = data.get("logo_url")
if not logo_url and "domain" in data and isinstance(data["domain"], dict):
logo_url = data["domain"].get("logo_url")
# Basic sanity checks before returning
if isinstance(logo_url, str) and logo_url.startswith("http"):
return logo_url
return None
if __name__ == "__main__":
# Example usage
domain = "https://example.com"
logo = get_company_logo_url(domain)
if logo:
print(f"Logo URL for {domain}: {logo}")
else:
print(f"No logo found for {domain}")
Integration tips:
- Return None when no logo is present and let the caller decide a fallback (e.g., initials avatar or a generic placeholder).
- Set a reasonable timeout. The example uses 20 seconds.
- Store successful logo URLs with your entity record and add an updated_at timestamp for cache control (see caching below).
Using categorization to validate or enrich the logo result
Beyond logos, Klazify’s main categorization endpoint can help you decide if a domain is eligible to display a logo in your UI (e.g., exclude certain verticals), or to add context next to the logo. The response also includes a logo URL field that you can use as a fallback if you are already calling categorization for policy checks.
Here is the official example response format from the categorization endpoint:
{
"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 in practice:
- domain.logo_url: A hosted image URL you can render immediately in your UI or email templates. It’s a good fallback if you already requested categorization.
- domain.categories: The category names and confidence help you determine eligibility to show a logo, segment lists, or drive ad or content placement rules.
- objects.company: Basic company profile fields you can display alongside the logo, such as name, location, and tags.
- domain_registration_data: Useful metadata for internal audits or heuristics (e.g., extremely new domains may be treated cautiously in UI placement).
- similar_domains: Handy for surfacing alternatives or deduplicating related properties when grouping multiple brands or subsidiaries.
How to plug the logo into your product pipeline
1) Enrich sign-ups or leads
When a user enters an email or website domain, call the logo endpoint, store the returned URL, and render it on the account profile view. Optionally call the categorization endpoint to tag the company with IAB-aligned categories and business tags for routing and scoring.
2) CRM and data warehouse enrichment
Add a batch job that resolves missing logos for accounts. Cache the returned URL with a last_checked timestamp. Store the canonical domain (company.url from categorization) so you can reconcile multiple domains for the same organization.
3) Brand safety and filtering
If your UI renders partner or publisher logos, use categories to block or warn on disallowed verticals. Only store or render logo URLs for domains that pass your policy checks.
Operational details that save you time
Batching and throughput
- Application-level batching: If you have a list of domains, run them in small concurrent batches with backoff on errors. Keep batches idempotent so retries don’t duplicate work.
- Pipeline design: For ingestion streams, separate “new domain” detection from “logo fetch” workers so you can scale those steps independently.
Caching strategy
- Cache key: Use the normalized domain (lowercase, punycode for IDNs). If you ingest full URLs, derive the registrable domain as your cache key.
- TTL: Logo URLs are hosted and stable. A 30–90 day TTL works well for most products. Shorten TTL if you support rapid brand refreshes.
- Revalidation: On cache miss, call the logo endpoint. On stale hits, refresh in the background to keep UI snappy.
- Invalidation: If a logo fails to load in the client, queue a refresh. Avoid hot loops—debounce refresh attempts.
Error handling and unknown domains
- Network or 5xx errors: Surface a generic avatar and schedule a retry with exponential backoff.
- No logo available: Return None from your enrichment function and mark the record. You can retry on a longer cadence because sites may add branding later.
- Unreachable sites: Calls that fail or can’t reach the target are not billed. Track these separately from “no logo found.”
Mapping categories to your own taxonomy
- Use the category name and, when present, IAB mapping codes in the categorization response to align with your internal taxonomy.
- Maintain an internal lookup table that maps Klazify category names (and IAB mappings) to your business-specific segments (e.g., “Target Vertical,” “Risk Tier”).
- Keep your mapping versioned. When categories evolve, reprocess affected domains to keep your segments consistent.
Security and compliance
- Store only the hosted logo URL from the response. There’s no need to proxy or download images unless your policy requires it.
- If you must host images yourself, download the logo URL asynchronously and serve it via your CDN. Respect robots and legal constraints for derived assets.
End-to-end flow: from user input to a rendered logo
- Normalize input: Extract and normalize the domain from user input.
- Cache check: If you have a fresh logo URL for this domain, use it.
- API call: POST the domain to the logo endpoint and capture the hosted logo URL from the JSON.
- Policy check (optional): If your UI requires filtering by industry, call the categorization endpoint and evaluate domain.categories.
- Persist: Save the logo URL and timestamps to your data store.
- Render: Use the URL directly in your frontend components or email templates.
- Refresh: On a background schedule, refresh stale logos and handle failures gracefully.
Testing and monitoring
- Smoke tests: Maintain a small list of well-known domains to validate basic success, empty results, and error paths.
- Client-side metrics: Track image load failures to trigger targeted refreshes.
- Alerting: Alert on spikes in HTTP error rates or timeouts to adjust concurrency and backoff policies.
Common pitfalls and how to avoid them
- Rendering raw, user-supplied URLs: Always resolve via the API first; do not attempt to scrape favicons or parse HTML yourself at scale.
- Skipping caching: You’ll hurt latency and burn quota. Cache per domain and refresh on a schedule.
- Hard-failing the UI: If a logo is missing or fails to load, render a safe fallback and enqueue a refresh rather than blocking the user experience.
- Ignoring categorization: When logos appear in sensitive contexts, call categorization and only render if categories pass your policy.
Where to go next
- See the full API reference and endpoints: Documentation
- Explore integration options and control planes: MCP
When you’re ready to implement, create a key on the Starter plan ($39.99/mo) with a 7-day trial. Failed or unreachable calls are not billed. Register
FAQ
-
What input should I send: a URL or a domain?
Send whichever you have. If you receive raw emails from users, derive the domain and post it. Klazify will resolve the canonical site before returning a logo. -
How do I know which field contains the logo URL?
The logo endpoint returns a hosted logo URL in the JSON. If you also call the categorization endpoint, read the logo from domain.logo_url in that response. -
What happens if the site is down or unreachable?
The request is not billed. Treat it as a transient failure: render a fallback and retry later with exponential backoff. -
Can I use categories to decide whether to display a logo?
Yes. Evaluate the categories in the categorization response and apply your allow/block rules before rendering the logo. -
How should I handle rate limits and high volume?
Batch requests at the application layer with controlled concurrency and caching. Reuse cached results per domain to avoid unnecessary calls.
Ready to add company logos to your Python workflow and enrich domains with context? Create your free trial key and start integrating in minutes: Register. For implementation details, see the Documentation and explore control-plane options in MCP.
Ready to use Klazify?
Start classifying websites, enriching company data, and exploring web intelligence.
Get Started Free