How to Get a Domain's Age in Python

November 19, 2026
How to Get a Domain's Age in Python

You need to programmatically determine how old a domain is and how soon it expires so you can make decisions like flagging risky signups, prioritizing outreach to mature companies, or preventing ad delivery on throwaway sites. By the end of this guide you’ll be able to call a single Klazify endpoint from Python, read a domain’s creation date, age in days, expiration date, and days left, and plug those values into your workflow with practical caching, batching, and error-handling patterns.

Why Klazify is the right API for domain age and expiration checks

When you’re gating signups, enriching CRM leads, auditing traffic sources, or scoring publishers, domain age is a high-signal feature. Klazify pairs domain registration data with the same infrastructure used to classify and analyze websites at scale, which helps you resolve edge cases and keep your checks fresh.

Illustration: How to Get a Domain's Age in Python
  • Accurate signals from live analysis: The same AI-driven crawling that powers Klazify’s categorization helps surface reliable registration data, so you can trust the creation and expiration timestamps you ingest.
  • Global coverage: If your intake is worldwide, you’ll meet domains registered across many TLDs and languages. Klazify’s global web analysis ensures you aren’t blind to non-US domains.
  • Real-time refresh: Stop relying on static CSVs. Klazify returns up-to-date domain registration data, which you can cache with a sensible TTL and refresh as needed.
  • Industry alignment with IAB categories: If you’re already using IAB taxonomies for ad tech or brand safety, Klazify lets you pair domain age with content categories from the same platform for unified decisions.
  • Simple REST integration: A single POST to retrieve creation date, age in days, expiration date, and days left—easy to wire into enrichment jobs, risk scoring services, and analytics pipelines.
  • Compliance and filtering: Combine domain age with website categorization to strengthen filters for new, parked, or suspicious sites without stitching multiple vendors together.

You can learn more about Klazify on the homepage: https://www.klazify.com, and you can get started for free: the Starter plan is $39.99/mo with a 7-day trial. Failed or unreachable calls are not billed.

What you will build: a Python check that returns domain age and expiration

We’ll integrate the Klazify Domain Expiration endpoint from Python. You’ll get:

  • domain_age_date: the domain’s creation date (YYYY-MM-DD)
  • domain_age_days_ago: how many days since creation
  • domain_expiration_date: when the domain registration expires (YYYY-MM-DD)
  • domain_expiration_days_left: how many days until expiration

We’ll also cover how to cache results per domain, batch requests, and handle unknown or new domains safely.

Endpoint and authentication

Use a POST request to the Klazify Domain Expiration endpoint with a Bearer token and a JSON body that includes the URL or domain you want to check.

  • Endpoint: https://www.klazify.com/api/domain_expiration
  • Method: POST
  • Auth: Bearer token in the Authorization header
  • Body: {"url": "the URL or domain you want to verify"}

If you don’t have an API key yet, create a free account here: Register. You can also browse the API reference: Documentation.

Copy-paste curl request

This example demonstrates the required headers and body. Replace YOUR_API_KEY with your token.

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

The example domain is included here to make the request concrete; use the domains from your own pipeline in production.

Python example: get domain age and expiration

The following Python script calls the same endpoint, parses the fields you need, and returns a normalized dict you can feed into your database or risk model.

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

import requests

API_URL = "https://www.klazify.com/api/domain_expiration"
API_KEY = "YOUR_API_KEY"

def get_domain_age(domain_or_url: str, timeout: float = 10.0) -> Optional[Dict[str, Any]]:
    """
    Returns a dict with domain age and expiration fields, or None if unavailable.
    """
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }
    payload = {"url": domain_or_url}

    try:
        resp = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
    except requests.RequestException:
        # Network error. Consider retry with backoff. Not billed for failed/unreachable calls.
        return None

    if resp.status_code != 200:
        # Handle 4xx/5xx. For 429 or transient 5xx, retry later.
        return None

    try:
        data = resp.json()
    except json.JSONDecodeError:
        return None

    # The fields live under "domain_registration_data" in the sample format.
    reg = data.get("domain_registration_data") or {}

    # Values may arrive as strings; coerce where needed.
    age_date = reg.get("domain_age_date")
    age_days_ago_raw = reg.get("domain_age_days_ago")
    exp_date = reg.get("domain_expiration_date")
    exp_days_left_raw = reg.get("domain_expiration_days_left")

    def to_int(x):
        try:
            return int(x) if x is not None else None
        except (TypeError, ValueError):
            return None

    result = {
        "domain_age_date": age_date,  # YYYY-MM-DD
        "domain_age_days_ago": to_int(age_days_ago_raw),
        "domain_expiration_date": exp_date,  # YYYY-MM-DD
        "domain_expiration_days_left": to_int(exp_days_left_raw),
        "fetched_at_epoch": int(time.time()),
        "input": domain_or_url,
    }

    # If all key fields are missing, consider returning None to signal unavailability.
    if not any([age_date, age_days_ago_raw, exp_date, exp_days_left_raw]):
        return None

    return result

if __name__ == "__main__":
    # Example usage: read from stdin or a list.
    test_domain = "https://example.com"
    info = get_domain_age(test_domain)
    print(json.dumps(info, indent=2, sort_keys=True))

Official sample response and how to use it

Below is the exact JSON example format. Your code should read the domain_registration_data object and use the four fields shown.


{
    "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:

  • domain_age_date: cast to a date object to persist as YYYY-MM-DD. Useful for historical trend analysis.
  • domain_age_days_ago: store as an integer for fast filtering (for example, exclude domains younger than 30 days).
  • domain_expiration_date: use to schedule refresh checks as the expiration approaches.
  • domain_expiration_days_left: trigger alerts or decisions (for example, avoid partnerships with domains expiring in less than 7 days).

Field reference at a glance

Field Meaning Type Common Usage
domain_age_date Domain creation date YYYY-MM-DD (string) Store canonical creation timestamp; display in UI
domain_age_days_ago Days since creation String in payload; cast to int Risk scoring and filters (e.g., > 365 days preferred)
domain_expiration_date Registration expiration date YYYY-MM-DD (string) Set refresh cadence and renewal monitoring
domain_expiration_days_left Days until expiration String in payload; cast to int Alerts, de-risking short-lived partnerships

Plugging the result into your pipeline

Blocking, enriching, and auditing with domain age

  • Signup and fraud controls: Drop or step-up verify users whose email domains are younger than N days.
  • Ad placement safety: Exclude publishers with domain_age_days_ago below your threshold or with domain_expiration_days_left under a short window.
  • CRM enrichment: Append domain_age_date and domain_age_days_ago to lead records to prioritize mature organizations.
  • Analytics: Track aggregate age distributions of referrers or partners over time.

Combine with categorization when needed

If you also need content context, use the main categorization endpoint to obtain IAB taxonomy categories side-by-side with domain age. This lets you build rules such as “older than 180 days and in an approved IAB category.” See the Documentation for the categorize endpoint details. You can explore capabilities here as well: https://www.klazify.com.

Operational guidance: batching, caching, errors, and mapping

Batching at scale

  • Micro-batch: Group domains into small chunks and issue sequential POSTs. Parallelize conservatively to respect rate limits (do not hard-code assumptions; consult the docs if needed).
  • Idempotency: Deduplicate work by hashing domains (lowercased, trimmed) and skipping duplicates within a batch.
  • Backoff: On transient errors (e.g., 429 or 5xx), retry with exponential backoff and jitter. Failed or unreachable calls are not billed.

Caching domain results

  • Cache key: the registrable domain (e.g., example.co.uk), not the full URL. Normalize inputs before lookup.
  • TTL strategy: set a long TTL for domain_age_date and domain_age_days_ago (for example, refresh monthly), and a shorter TTL as domain_expiration_days_left approaches zero (for example, refresh weekly, then daily when under 14 days).
  • Write-through: update your cache immediately on successful responses; tag with fetched_at_epoch to support freshness checks.

Handling unknown or new domains

  • Graceful nulls: If domain_registration_data is missing or fields are empty, treat the domain as unknown. Retry after a delay or route for manual review depending on your risk posture.
  • Fallback logic: For risky flows, you can enforce stronger controls (e.g., additional verification) when the age is unknown.

Mapping to internal taxonomies

Even if your rules run primarily on domain age, you may map results into your own risk classes. For example:

  • New: domain_age_days_ago ≤ 30
  • Young: 31–180
  • Established: 181–1825
  • Mature: > 1825

Store both the raw fields and your derived bucket. This makes it easy to re-run analyses if you change thresholds.

Testing and monitoring

  • Fixture coverage: Include tests for old domains, very new domains, and near-expiration cases. Validate integer coercion for days fields.
  • Schema stability: Assert presence of domain_registration_data and its four fields; allow for nulls without hard failure.
  • Alerting: Page or notify when a partner domain’s domain_expiration_days_left drops below your operational threshold.
  • Latency and retries: Track P95 latency and retry rates in your job metrics; tune concurrency to keep within your SLOs.

Cost, account, and governance notes

  • Starter plan: $39.99/mo with a 7-day trial.
  • Billing safety: Failed or unreachable calls are not billed.
  • Access model: Use your Bearer token; keep it in a secure secrets store and rotate on a schedule.
  • Teams and monitoring: If you manage multiple services, centralize access via your internal platform and track usage with tags per service.

To create your account and get an API key, visit: Register. You can also explore the Model Compatibility Program here: MCP.

Practical pipeline patterns

Daily enrichment job

  • Input: a deduped list of registrable domains from yesterday’s signups, referrals, or publishers.
  • Process: call domain_expiration, store normalized fields and fetched_at_epoch, and merge into your entities table.
  • Output: derived risk score that gates downstream actions (e.g., nurture sequence vs. human review).

Real-time scoring for signups

  • Inline check: fire a single POST for the user’s email domain during signup.
  • Timeout control: cap request timeout so the UX remains snappy; fall back to a cached value if present.
  • Decision: if domain_age_days_ago is below your cutoff or unknown, apply step-up verification.

Ad inventory QA

  • Pre-flight: validate all publisher domains have domain_expiration_days_left above N days before a campaign.
  • Mid-flight: re-check weekly, with more frequent checks as expirations approach.
  • Audit log: store both raw and derived fields for compliance evidence.

Data hygiene and edge cases

  • Normalization: always lowercase domains, trim trailing dots, and extract registrable domains from full URLs.
  • Timezones: Dates are returned as YYYY-MM-DD strings. Treat them as calendar dates in UTC when converting to timestamps.
  • Type coercion: The sample shows “days” values as strings; cast to integers for comparisons.
  • Partial data: Be prepared for cases where creation date is known but expiration is missing (or vice versa). Default your logic safely.

FAQ

  • Can I pass either a full URL or just a domain? Yes. Provide either in the url field. For caching and deduplication, normalize to the registrable domain before storage.
  • How often should I refresh domain age data? Creation date changes rarely, so monthly is fine. Refresh more frequently as domain_expiration_days_left approaches your operational threshold.
  • What happens if the endpoint can’t retrieve data for a domain? Your call won’t be billed if it fails or is unreachable. In your code, handle missing domain_registration_data gracefully and retry later with backoff.
  • Can I use these fields with IAB categories from Klazify? Yes. You can call the categorization endpoint and use both sets of signals in one policy (e.g., approved IAB categories and domain age above a threshold).
  • How do I get started? Create an account to obtain your API key: Register, then review the reference: Documentation.

Ready to enrich your pipeline with reliable domain age and expiration data? Create a free account, get your API key, and ship your integration today: Register. For product background and capabilities, visit https://www.klazify.com.

Ready to use Klazify?

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

Get Started Free