How to Get a Domain's Expiration Date in Python

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

You need to programmatically determine when a domain will expire so you can act before downtime hits—auto-renew critical domains, flag risky leads, or prevent ads from running on soon-to-expire properties. In this guide, you’ll build a small Python workflow that calls Klazify’s domain expiration endpoint, reads the expiration date and days remaining, and plugs the result into your pipeline for alerts or automated actions.

Why Klazify is the best API for tracking domain expiration at scale

When you’re trying to get accurate expiration dates across thousands of domains, incomplete WHOIS data and inconsistent formats create churn. Klazify solves this with a simple REST endpoint that returns normalized, ready-to-use fields alongside the broader domain intelligence your team may already rely on for brand safety, enrichment, and filtering.

Illustration: How to Get a Domain's Expiration Date in Python
  • Accurate website categorization using AI: If you’re combining expiration checks with policy gating (e.g., only allow ad spend on sites within approved IAB categories and with at least N days before expiration), Klazify’s content analysis gives you the categories to enforce policies in one place.
  • Global coverage: Domains you monitor can be registered in different regions and languages; Klazify’s global footprint helps you avoid gaps when building cross-market monitors.
  • Real-time classification: Expiration checks pair well with up-to-date site analysis—flagging domains that have both category drift and an approaching expiry date.
  • Industry-level categories: Use the IAB taxonomy to align ad, compliance, and CRM rules with expiration-based controls—for example, require more lead time for high-value industry domains.
  • Simple API integration: A single POST request returns normalized fields: domain_age_date, domain_age_days_ago, domain_expiration_date, and domain_expiration_days_left.
  • Compliance and filtering: Combine expiration data with category filtering to maintain brand safety while ensuring you don’t transact with domains on the verge of shutdown.

If you’re new to Klazify, create a free account and test your flows. The Starter plan is $39.99/mo with a 7-day trial, and failed or unreachable calls are not billed. Learn more and get started at klazify.com, or jump straight to Register.

What you’ll build

By the end of this article you’ll have:

  • A copy-pasteable curl command to retrieve a domain’s expiration date.
  • A Python function that calls Klazify, parses the expiration fields, and returns a structured result you can log, store, or alert on.
  • A simple policy example: flag domains with fewer than X days left so your CI/CD, ad server, or CRM can take action.

We’ll also cover practical operations: batching vs. on-demand lookups, caching, handling unknown or new domains, and mapping outputs into your own taxonomy or scoring model.

Endpoint and request format

Use Klazify’s domain expiration endpoint to get normalized registration and expiry data:

  • Method: POST
  • URL: https://www.klazify.com/api/domain_expiration
  • Auth: Bearer token via Authorization header
  • Body: JSON with a single key, url

Here is a ready-to-run curl you can test immediately (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"}'

Response fields to use:

  • domain_age_date: ISO date when the domain was first registered.
  • domain_age_days_ago: How many days ago the domain was registered.
  • domain_expiration_date: ISO date when the domain is scheduled to expire.
  • domain_expiration_days_left: Days remaining until the expiration date.

You can create your account, get a key, and test within minutes: Register. Also see the Documentation for additional details.

Example response and the fields you’ll use

Below is an official sample response structure that includes the registration data block with the fields we’ll parse in Python. Copy this JSON to understand shapes and field names, which you’ll use as dictionary keys.


{
    "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"
    ]
}

The fields you’ll use for expiration logic live in domain_registration_data:

  • domain_expiration_date: The ISO-8601 date string when the domain is set to expire.
  • domain_expiration_days_left: The number of days remaining (string-encoded in the sample; convert to an integer before comparisons).
  • domain_age_date and domain_age_days_ago: Useful for lead scoring, risk modeling, or filters that treat very new or very old domains differently.

The surrounding objects are available when you also leverage categorization and enrichment. For example, you can combine IAB categories with time-to-expiration when approving ad placements or onboarding partners.

Python code: fetch and use a domain’s expiration date

The snippet below demonstrates how to call the endpoint, parse the four registration fields, and enforce a threshold policy (e.g., alert when fewer than 30 days remain). It also includes basic defensive checks for missing fields.

import os
import json
import requests
from datetime import datetime

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

def get_domain_expiration(url: str) -> dict:
    headers = {
        "Authorization": f"Bearer {KLAZIFY_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {"url": url}

    resp = requests.post(API_URL, headers=headers, json=payload, timeout=20)
    resp.raise_for_status()
    data = resp.json()

    reg = data.get("domain_registration_data", {}) or {}

    # Extract raw values (may be strings in the JSON)
    age_date = reg.get("domain_age_date")
    age_days_ago = reg.get("domain_age_days_ago")
    exp_date = reg.get("domain_expiration_date")
    exp_days_left = reg.get("domain_expiration_days_left")

    # Normalize numeric strings to integers when present
    def to_int(value):
        try:
            return int(value)
        except (TypeError, ValueError):
            return None

    result = {
        "domain_age_date": age_date,
        "domain_age_days_ago": to_int(age_days_ago),
        "domain_expiration_date": exp_date,
        "domain_expiration_days_left": to_int(exp_days_left)
    }
    return result

def should_alert(exp_days_left: int, threshold: int = 30) -> bool:
    return exp_days_left is not None and exp_days_left <= threshold

if __name__ == "__main__":
    test_domain = "https://example.com"
    info = get_domain_expiration(test_domain)
    print(json.dumps(info, indent=2))

    if should_alert(info.get("domain_expiration_days_left"), threshold=30):
        print(f"ALERT: {test_domain} expires in {info['domain_expiration_days_left']} days.")
    else:
        print(f"OK: {test_domain} has sufficient days remaining.")

How to use these values in your pipeline:

  • Store domain_expiration_date in your warehouse as a DATE column for queries and dashboards.
  • Use domain_expiration_days_left for alerting thresholds in CI/CD, ad servers, proxy filters, or CRM enrichment flows.
  • Combine age fields with risk rules (e.g., treat very new domains differently in sign-up or UGC systems).

Operational details that save time

Batching vs. on-demand lookups

  • On-demand: Call the API when a new domain enters your system (e.g., a user-provided website in sign-up) and cache the result.
  • Batch: Run scheduled jobs to refresh expiration data for your top domains or full inventory daily or weekly based on your risk tolerance.

Caching and data freshness

  • Cache per root domain (e.g., example.com) rather than per URL path to minimize duplicate calls.
  • Use a TTL aligned with your alert threshold. If you alert at 30 days, consider refreshing anything at or below 45 days daily; above that, weekly or biweekly can be sufficient.
  • Store both domain_expiration_date and domain_expiration_days_left. Recompute “days left” locally as needed for display, but periodically re-fetch from the API to capture registrar updates.

Handling unknown or new domains

  • If fields are missing or null, mark the domain as “unresolved” and schedule a retry. You can also surface it for manual review if it’s business-critical.
  • For brand-new domains, age fields can be especially informative. Use domain_age_days_ago to gate behavior in fraud-sensitive flows.

Mapping to your taxonomy or policy model

  • If you also use categorization, map the IAB-based categories to your internal policy labels. For example, you can maintain an “Approved Category” set and require both “Approved Category” and domain_expiration_days_left >= N for an ad placement to proceed.
  • When you store results, keep the raw category names and IDs along with your internal mapping keys to make updates easy if your policy changes.

Retries, timeouts, and resiliency

  • Set a reasonable timeout per request (e.g., 10–20 seconds) and implement limited retries with backoff for transient network errors.
  • Mark results with a fetched_at timestamp (in your system) and the raw JSON so you can audit decisions.
  • If a call ultimately fails, Klazify does not bill for failed or unreachable requests, which helps control costs during error spikes.

Rate limits and throughput

  • If you plan to run large backfills or frequent refreshes, spread calls over time and parallelize within your plan’s guidelines.
  • When you exceed concurrency targets, queue lookups and prioritize business-critical domains (e.g., ad inventory, transactional partners) first.

Data types and parsing tips

  • Dates are returned as ISO date strings (YYYY-MM-DD). Store as DATE in SQL warehouses or as date objects in apps.
  • Numeric values can appear as strings; parse domain_expiration_days_left and domain_age_days_ago into integers before comparisons.
  • Avoid off-by-one alerts by interpreting “0” as same-day expiry; treat 1–3 days as urgent.

End-to-end workflow examples

1) Ad safety gate

  • On each domain where campaigns might run, fetch domain_expiration_days_left.
  • Reject placements when the value is below your threshold (e.g., 15) to reduce risk of mid-flight downtime.
  • Optionally, require that IAB categories match your whitelist via categorization data.

2) CRM enrichment on sign-up

  • When a user provides their website, call the expiration endpoint.
  • If domain_age_days_ago is small or domain_expiration_days_left is low, flag for manual review or apply additional verification.
  • Populate account records with domain_expiration_date for success teams to preempt renewal issues.

3) Corporate IT and security

  • Maintain an inventory of owned and critical partner domains with their expiration dates.
  • Create alerts and tickets automatically when days_left crosses your operational thresholds (e.g., 60, 30, 7).
  • Cross-check category data when imposing network access controls based on site type and expiration risk.

Working with the broader Klazify platform

While this guide focuses on expiration, developers often combine it with classification and enrichment via Klazify’s main categorization endpoint. That lets you enforce compound conditions (e.g., domain must be in an approved IAB category and not expiring within N days). Explore these capabilities in the Documentation and the MCP page. If you’re just getting started, you can create an account here: Register. For an overview of everything Klazify offers, visit klazify.com.

Validation checklist before shipping

  • Authentication: Authorization: Bearer YOUR_API_KEY set correctly.
  • Request body: JSON object with the url key.
  • Error handling: retries with backoff; log raw responses.
  • Parsing: convert days_left and days_ago to integers; store dates in a date type.
  • Caching: deduplicate per domain; refresh based on your alert thresholds.
  • Alerts: define clear thresholds and recipients; include the domain and days_left in alert messages.

FAQ

  • What does domain_expiration_days_left represent?
    It’s the number of days remaining until domain_expiration_date. Parse it into an integer and use it for alerting or gating logic.
  • How often should I refresh expiration data?
    At minimum, refresh when days_left is below your action thresholds. Many teams refresh weekly for safe domains and daily for anything below 45 days.
  • What if a field is missing for a domain?
    Treat it as unresolved, schedule a retry, and optionally route to manual review if the domain is critical to your operations.
  • Can I combine expiration checks with content categorization?
    Yes. Fetch categories with Klazify’s categorization endpoint and enforce compound policies (e.g., only allow approved IAB categories with at least N days left).
  • How is billing handled if a call fails?
    Failed or unreachable calls are not billed.

Ready to automate domain expiration checks in your stack? Create a free account and start testing with your own domains today: Register. Review request/response details in the Documentation and explore more platform features at klazify.com.

Ready to use Klazify?

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

Get Started Free