Code Samples

Code Samples

Working examples for common integration patterns. Each sample authenticates with an API key and secret, obtains a token, and then calls one API endpoint.

Replace the placeholder API key and secret before running these examples. Tokens are passed in the request path, not as HTTP headers.

Domain Activity API: Python

Authenticates with the Domain Activity API and fetches added .com domains containing the keyword "bank".

import requests

API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
BASE_URL = "https://api.codepunch.com/dnfeed/v2"


def get_token():
    url = f"{BASE_URL}/auth/{API_KEY}/{API_SECRET}"
    response = requests.get(url, timeout=30)
    response.raise_for_status()

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "Authentication failed"))

    return data["token"]


def get_api_data(token, endpoint, params=None):
    url = f"{BASE_URL}/{token}/{endpoint}"
    response = requests.get(url, params=params or {}, timeout=60)
    response.raise_for_status()

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "API request failed"))

    return data


token = get_token()

params = {
    "kw": "bank",
    "tlds": "com",
    "start": 0,
    "limit": 500,
}

data = get_api_data(token, "added", params)

print(f"Total records: {data['records']}")
for row in data.get("data", []):
    print(row["domain"])

DNS and Subdomains API: Python

Authenticates with the DNS API and searches nameservers containing the keyword "wordpress".

import requests

API_KEY = "your_api_key"
API_SECRET = "your_secret_key"
BASE_URL = "https://api.codepunch.com/dns/v2"


def get_token():
    url = f"{BASE_URL}/auth/{API_KEY}/{API_SECRET}"
    response = requests.get(url, timeout=30)
    response.raise_for_status()

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "Authentication failed"))

    return data["token"]


def get_api_data(token, endpoint, params=None):
    url = f"{BASE_URL}/{token}/{endpoint}"
    response = requests.get(url, params=params or {}, timeout=60)
    response.raise_for_status()

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "API request failed"))

    return data


token = get_token()

# Find all nameservers that contain "wordpress".
params = {"kw": "wordpress"}
data = get_api_data(token, "nameservers", params)

print(data)

DNS and Subdomains API: Paginated gTLD Domain Search in Python

Authenticates with the DNS API, detects the total number of matching gTLD domains, and pages through all domains containing a command-line keyword.

import argparse
import json
import time
import requests

CODEPUNCH_API_KEY = "your_api_key"
CODEPUNCH_API_SECRET = "your_api_secret"

API_KEY = CODEPUNCH_API_KEY
API_SECRET = CODEPUNCH_API_SECRET
BASE_URL = "https://api.codepunch.com/dns/v2"

PAGE_LIMIT = 5000
MAX_START = 1000000


def get_token():
    url = f"{BASE_URL}/auth/{API_KEY}/{API_SECRET}"
    response = requests.get(url, timeout=30)

    if response.status_code != 200:
        raise RuntimeError(f"Authentication failed: {response.status_code}")

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "Authentication failed"))

    return data["token"]


def get_api_data(token, endpoint, params=None):
    url = f"{BASE_URL}/{token}/{endpoint}"
    response = requests.get(url, params=params or {}, timeout=60)

    if response.status_code != 200:
        raise RuntimeError(f"Invalid response code: {response.status_code}")

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "API request failed"))

    return data


def get_total_count(token, endpoint, keywords):
    params = {
        "kw": keywords,
        "dm": "stats",
    }

    data = get_api_data(token, endpoint, params)

    for key in ["domain_records", "records", "total", "count", "total_records"]:
        if key in data:
            return int(data[key])

    raise RuntimeError(f"Could not detect total count from response: {data}")


def get_all_domains(token, endpoint, keywords, limit=PAGE_LIMIT, delay_seconds=0.25):
    total_count = get_total_count(token, endpoint, keywords)
    print(f"Total records: {total_count}")

    domains = []
    start = 0

    while start < total_count:
        if start > MAX_START:
            print(
                "Reached the maximum supported start index. "
                "Use a narrower keyword search."
            )
            break

        params = {
            "kw": keywords,
            "start": start,
            "limit": limit,
        }

        data = get_api_data(token, endpoint, params)
        page_domains = data.get("domains", [])

        if not page_domains:
            break

        domains.extend(page_domains)

        print(
            f"Fetched start={start}, returned={len(page_domains)}, "
            f"collected={len(domains)}/{total_count}"
        )

        if len(page_domains) < limit:
            break

        start += limit
        time.sleep(delay_seconds)

    return domains


def parse_args():
    parser = argparse.ArgumentParser(
        description="Fetch gTLD domains containing a keyword."
    )

    parser.add_argument(
        "keywords",
        help='Keyword query, for example money, "*money*", or "money|finance".',
    )

    parser.add_argument(
        "--output",
        default=None,
        help="Output filename. Defaults to domains-KEYWORDS.txt.",
    )

    parser.add_argument(
        "--limit",
        type=int,
        default=PAGE_LIMIT,
        help="Page size. Maximum is 5000.",
    )

    return parser.parse_args()


args = parse_args()

token = get_token()
domains = get_all_domains(
    token=token,
    endpoint="domains",
    keywords=args.keywords,
    limit=min(args.limit, PAGE_LIMIT),
)

print(json.dumps(domains, indent=2))

if args.output:
    filename = args.output
else:
    safe_keywords = (
        args.keywords.replace("*", "")
        .replace(" ", "_")
        .replace("|", "_")
        .replace('"', "")
        .replace("'", "")
        .replace("^", "")
        .replace("$", "")
    )
    filename = f"domains-{safe_keywords}.txt"

with open(filename, "w", encoding="utf-8") as fp:
    for domain in domains:
        fp.write(domain + "\n")

print(f"Saved {len(domains)} domains to {filename}")

Command-line usage examples

Save the script as fetch_domains.py, add your API key and secret, and pass the keyword query as the first command-line argument. Quote keyword queries that contain shell-sensitive characters such as |, spaces, *, ^, or $.

# Basic keyword search.
python fetch_domains.py money

# Partial match search using wildcards.
python fetch_domains.py "*money*"

# OR search for either keyword.
python fetch_domains.py "money|finance"

# AND search for domains containing both words.
python fetch_domains.py "money loan"

# Starts-with search.
python fetch_domains.py "^money*"

# Custom output filename.
python fetch_domains.py money --output money-domains.txt

# Smaller page size for testing.
python fetch_domains.py money --limit 500

DNS and Subdomains API: PHP

Authenticates with the DNS API and retrieves nameserver data for the keyword "wordpress".

<?php

$api_key = "paste_your_key_here";
$api_secret = "paste_your_secret_here";
$base_url = "https://api.codepunch.com/dns/v2";

function get_json($url) {
    $contents = file_get_contents($url);

    if ($contents === false) {
        throw new Exception("Request failed: " . $url);
    }

    $data = json_decode($contents, true);

    if (!is_array($data)) {
        throw new Exception("Invalid JSON response");
    }

    if (empty($data["status"])) {
        $message = isset($data["error"]) ? $data["error"] : "API request failed";
        throw new Exception($message);
    }

    return $data;
}

try {
    // Authenticate and get token.
    $auth_url = $base_url . "/auth/" . rawurlencode($api_key) . "/" . rawurlencode($api_secret);
    $auth_data = get_json($auth_url);
    $token = $auth_data["token"];

    // Get all nameservers that contain "wordpress".
    $params = http_build_query([
        "kw" => "wordpress"
    ]);

    $url = $base_url . "/" . rawurlencode($token) . "/nameservers/?" . $params;
    $nameservers = get_json($url);

    echo "<pre>";
    print_r($nameservers);
    echo "</pre>";

} catch (Exception $e) {
    echo "Error: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, "UTF-8");
}
?>

SSL/TLS Certificates API: Python

Authenticates with the SSL/TLS Certificate API and searches yesterday's certificates containing the keyword "amazon".

import datetime
import requests

API_KEY = "your_api_key"
API_SECRET = "your_secret_key"
BASE_URL = "https://api.codepunch.com/tlscerts/v2"


def get_token():
    url = f"{BASE_URL}/auth/{API_KEY}/{API_SECRET}"
    response = requests.get(url, timeout=30)
    response.raise_for_status()

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "Authentication failed"))

    return data["token"]


def get_api_data(token, endpoint, params=None):
    url = f"{BASE_URL}/{token}/{endpoint}"
    response = requests.get(url, params=params or {}, timeout=60)
    response.raise_for_status()

    data = response.json()
    if not data.get("status"):
        raise RuntimeError(data.get("error", "API request failed"))

    return data


token = get_token()

yesterday = datetime.date.today() - datetime.timedelta(days=1)
date_code = yesterday.strftime("%Y%m%d")

# Find certificates that contain "amazon".
params = {
    "date": date_code,
    "limit": 50,
    "kw": "amazon",
}

data = get_api_data(token, "certificates", params)

for cert in data.get("data", []):
    print(cert)

SSL/TLS Certificates API: PHP

Authenticates with the SSL/TLS Certificate API and retrieves yesterday's certificate records matching "amazon".

<?php

$api_key = "paste_your_key_here";
$api_secret = "paste_your_secret_here";
$base_url = "https://api.codepunch.com/tlscerts/v2";

function get_json($url) {
    $contents = file_get_contents($url);

    if ($contents === false) {
        throw new Exception("Request failed: " . $url);
    }

    $data = json_decode($contents, true);

    if (!is_array($data)) {
        throw new Exception("Invalid JSON response");
    }

    if (empty($data["status"])) {
        $message = isset($data["error"]) ? $data["error"] : "API request failed";
        throw new Exception($message);
    }

    return $data;
}

try {
    // Authenticate and get token.
    $auth_url = $base_url . "/auth/" . rawurlencode($api_key) . "/" . rawurlencode($api_secret);
    $auth_data = get_json($auth_url);
    $token = $auth_data["token"];

    // Get yesterday's certificates containing "amazon".
    $date_code = date("Ymd", strtotime("-1 day"));

    $params = http_build_query([
        "kw" => "amazon",
        "date" => $date_code,
        "limit" => 50
    ]);

    $url = $base_url . "/" . rawurlencode($token) . "/certificates/?" . $params;
    $certificates = get_json($url);

    echo "<pre>";
    print_r($certificates);
    echo "</pre>";

} catch (Exception $e) {
    echo "Error: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, "UTF-8");
}
?>

Need more complete scripts with full pagination or custom filters? Contact us with your subscription details and we will send them across.