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 v2: Python
Authenticates with the Domain Activity API v2 and fetches the first page of current-date added .com domains containing the keyword bank. The requests library handles URL encoding for the % wildcard in the parameter value.
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,
"sorton": "date",
"sortorder": "asc",
"format": "json",
}
data = get_api_data(token, "added", params)
print(f"Total matching records: {data['records']}")
print(f"Rows in this page: {len(data.get('data', []))}")
for row in data.get("data", []):
print(row["domain"])
To retrieve historical activity, add date=yyyymmdd and choose a dcm comparison such as gte. For result sets larger than one page, keep the same sorton/sortorder and advance start.
Domain Activity API v2: Daily ZIP in Python
Downloads the previous day's completed ZIP by default. Set date for a specific dated ZIP, or use the presence-only latest flag for the current day's partial ZIP.
import requests
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
BASE_URL = "https://api.codepunch.com/dnfeed/v2"
def get_token():
response = requests.get(
f"{BASE_URL}/auth/{API_KEY}/{API_SECRET}",
timeout=30,
)
response.raise_for_status()
data = response.json()
if not data.get("status"):
raise RuntimeError(data.get("error", "Authentication failed"))
return data["token"]
token = get_token()
url = f"{BASE_URL}/{token}/dailyzip/"
# Previous day's completed added-domains ZIP:
params = {"source": "added"}
filename = "added-domains.zip"
# For a specific date instead:
# params = {"source": "deleted", "date": "YYYYMMDD"}
# filename = "deleted-domains-YYYYMMDD.zip"
# For the current day's partial ZIP instead:
# params = {"source": "added", "latest": ""}
# filename = "added-domains-latest-partial.zip"
with requests.get(url, params=params, stream=True, timeout=120) as response:
response.raise_for_status()
with open(filename, "wb") as output:
for chunk in response.iter_content(chunk_size=1024 * 1024):
if chunk:
output.write(chunk)
print(f"Saved {filename}")
Do not combine date and latest. The ready-to-use dnfeed-app.py exposes these modes as -zip, -zd, and -latest.
DNS and Subdomains API: Python
Authenticates with the DNS API and retrieves the first page of nameserver matches for the search term "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()
# Fetch the first page of nameservers matching "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, requests the matching count from dm=stats, and pages through the domains endpoint using its endpoint-specific domain_records count field.
import argparse
import json
import re
import time
import requests
CODEPUNCH_API_KEY = "your_api_key"
CODEPUNCH_API_SECRET = "your_api_secret"
BASE_URL = "https://api.codepunch.com/dns/v2"
DEFAULT_PAGE_LIMIT = 5000
MAX_PAGE_LIMIT = 5000
SEARCH_RANGE_CEILING = 1_005_001
def get_token():
url = f"{BASE_URL}/auth/{CODEPUNCH_API_KEY}/{CODEPUNCH_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
def get_total_count(token, keywords):
data = get_api_data(
token,
"domains",
{"kw": keywords, "dm": "stats"},
)
if "domain_records" not in data:
raise RuntimeError(f"Missing domain_records in stats response: {data}")
return int(data["domain_records"])
def get_all_domains(token, keywords, limit=DEFAULT_PAGE_LIMIT, delay_seconds=0.25):
total_count = get_total_count(token, keywords)
print(f"Matching domains: {total_count}")
domains = []
start = 0
while start < total_count:
if start + limit + 1 > SEARCH_RANGE_CEILING:
print(
"Reached the DNS search traversal ceiling. "
"Use a narrower keyword expression to continue."
)
break
data = get_api_data(
token,
"domains",
{"kw": keywords, "start": start, "limit": limit},
)
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 page_limit(value):
value = int(value)
if not 1 <= value <= MAX_PAGE_LIMIT:
raise argparse.ArgumentTypeError(
f"limit must be between 1 and {MAX_PAGE_LIMIT}"
)
return value
def parse_args():
parser = argparse.ArgumentParser(
description="Fetch gTLD domains using the DNS API v2 domains endpoint."
)
parser.add_argument(
"keywords",
help=(
'Keyword expression, for example money, money|finance, '
'"money loan", ^money, or money$.'
),
)
parser.add_argument(
"--output",
default=None,
help="Output filename. Defaults to domains-QUERY.txt.",
)
parser.add_argument(
"--limit",
type=page_limit,
default=DEFAULT_PAGE_LIMIT,
help=f"Page size from 1 to {MAX_PAGE_LIMIT}.",
)
return parser.parse_args()
args = parse_args()
token = get_token()
domains = get_all_domains(token, args.keywords, args.limit)
print(json.dumps(domains, indent=2))
if args.output:
filename = args.output
else:
safe_query = re.sub(r"[^A-Za-z0-9._-]+", "_", args.keywords).strip("_")
filename = f"domains-{safe_query or 'query'}.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 one verified DNS search expression as the first argument. Shell quoting varies by platform; the examples below preserve the expression characters for a POSIX-style shell.
# Basic term. python fetch_domains.py money # OR search. python fetch_domains.py 'money|finance' # Quoted phrase. The double quotes are part of the API expression. python fetch_domains.py '"money loan"' # Start-of-field and end-of-field searches. python fetch_domains.py '^money' 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
The gTLD/nameserver indexes do not support * as a generic wildcard, and plain unquoted whitespace is not documented as an AND operator. Use the verified query forms shown above.
DNS Subdomains API: PHP
Authenticates with the DNS API, calls the dedicated /subdomains.php endpoint, and prints certificate-derived hostnames observed for the requested domain. The optional scan limit controls certificate rows examined, not the number of hostnames returned.
This sample reads api_base, api_key, and api_secret from a neighboring config.php file. Download the sample here: test_subdomains.php.
# config.php
<?php
$config['api_base'] = 'https://api.codepunch.com';
$config['api_key'] = 'YOUR_API_KEY';
$config['api_secret'] = 'YOUR_API_SECRET';
# Usage
php test_subdomains.php
php test_subdomains.php softnik.com
php test_subdomains.php softnik.com 25000
<?php
###############################################################################
# test_subdomains.php
#
# Test client for the DNS v2 certificate-derived Subdomains endpoint.
# Reads credentials from config.php in the same directory.
#
# Usage:
# php test_subdomains.php
# php test_subdomains.php softnik.com
# php test_subdomains.php softnik.com 25000
#
# The optional second argument is the certificate-row scan limit (1..100000).
# It is not a cap on the number of unique hostnames returned.
###############################################################################
# -----------------------------------------------------------------------
# Configuration — loaded from config.php
#
# config.php should define:
# $config['api_base'] = 'https://api.codepunch.com';
# $config['api_key'] = 'YOUR_API_KEY';
# $config['api_secret'] = 'YOUR_API_SECRET';
# -----------------------------------------------------------------------
$configFile = __DIR__ . '/config.php';
if (!file_exists($configFile))
die("ERROR: config.php not found. Create it next to this script.\n");
$config = [];
include $configFile;
foreach (['api_base', 'api_key', 'api_secret'] as $key) {
if (empty($config[$key]))
die("ERROR: Missing '$key' in config.php\n");
}
define('API_BASE', rtrim($config['api_base'], '/'));
define('API_KEY', $config['api_key']);
define('API_SECRET', $config['api_secret']);
define('BASE_URL', API_BASE . '/dns/v2');
define('AUTH_URL', BASE_URL . '/auth/' . rawurlencode(API_KEY) . '/' . rawurlencode(API_SECRET));
define('SUBS_URL', BASE_URL . '/subdomains.php');
# -----------------------------------------------------------------------
$domain = $argv[1] ?? 'softnik.com';
$scanLimit = isset($argv[2]) ? (int)$argv[2] : 50000;
if ($scanLimit < 1 || $scanLimit > 100000)
die("ERROR: scan limit must be between 1 and 100000.\n");
echo "=================================================================\n";
echo " DNS Subdomains API Test Client\n";
echo "=================================================================\n";
echo " Domain : $domain\n";
echo " Scan limit : $scanLimit certificate rows\n";
echo "-----------------------------------------------------------------\n";
# -----------------------------------------------------------------------
# Step 1 — Authenticate and get a session token
# -----------------------------------------------------------------------
echo "\n[1] Authenticating...\n";
$authResponse = api_get(AUTH_URL);
if (!$authResponse)
die(" ERROR: No response from auth endpoint.\n");
$auth = json_decode($authResponse, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo " Raw response: $authResponse\n";
die(" ERROR: Invalid JSON in auth response.\n");
}
if (empty($auth['status']) || empty($auth['token'])) {
$err = $auth['error'] ?? 'Unknown error';
die(" ERROR: Authentication failed — $err\n");
}
$token = $auth['token'];
echo " OK — token obtained: " . substr($token, 0, 8) . "...\n";
# -----------------------------------------------------------------------
# Step 2 — Fetch certificate-derived hostnames
# -----------------------------------------------------------------------
echo "\n[2] Fetching observed hostnames for '$domain'...\n";
$params = [
'domain' => $domain,
't' => $token,
'limit' => $scanLimit,
];
$subsResponse = api_get(SUBS_URL . '?' . http_build_query($params));
if (!$subsResponse)
die(" ERROR: No response from subdomains endpoint.\n");
$result = json_decode($subsResponse, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo " Raw response: $subsResponse\n";
die(" ERROR: Invalid JSON in subdomains response.\n");
}
if (empty($result['status'])) {
$err = $result['error'] ?? 'Unknown error';
die(" ERROR: API call failed — $err\n");
}
# -----------------------------------------------------------------------
# Step 3 — Display results
# -----------------------------------------------------------------------
echo "\n[3] Results\n";
echo "-----------------------------------------------------------------\n";
echo " Domain : " . $result['domain'] . "\n";
echo " Records scanned : " . $result['records_scanned'] . "\n";
echo " Hostnames found : " . $result['count'] . "\n";
if (!empty($result['subdomains'])) {
echo "-----------------------------------------------------------------\n";
foreach ($result['subdomains'] as $sub) {
echo " $sub\n";
}
}
echo "-----------------------------------------------------------------\n";
echo "Certificate-derived results may include wildcard or apex hostnames\n";
echo "and do not prove that a hostname is currently active in DNS.\n";
echo "=================================================================\n";
###############################################################################
# Helper
###############################################################################
function api_get(string $url): string|false {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_USERAGENT => 'DNSSubdomains-Client/1.0',
]);
$response = curl_exec($ch);
if (curl_error($ch))
echo " CURL ERROR: " . curl_error($ch) . "\n";
curl_close($ch);
return $response;
}
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"];
// Fetch the first page of nameservers matching "wordpress".
$params = http_build_query([
"kw" => "wordpress",
"start" => 0,
"limit" => 500,
]);
$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 Certificates API, runs a filtered search for yesterday, and handles the v2 zero-result response without treating it as an API failure.
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") and data.get("error"):
raise RuntimeError(data["error"])
return data
token = get_token()
today_utc = datetime.datetime.now(datetime.timezone.utc).date()
yesterday = today_utc - datetime.timedelta(days=1)
date_code = yesterday.strftime("%Y%m%d")
params = {
"date": date_code,
"kw": "amazon",
"start": 0,
"limit": 50,
"sorton": "valid_from",
"sortorder": "desc",
}
data = get_api_data(token, "certificates", params)
rows = data.get("data", [])
if not rows:
print("No matching certificates on this page.")
else:
for cert in rows:
print(
cert.get("id"),
cert.get("subject_cn"),
cert.get("valid_from_date_time"),
cert.get("thumprint_sha_256"),
)
For /certificates, a valid empty page can return status=false with records=0, data=[], and no error. Check the explicit error field before treating that response as a failed request.
SSL/TLS Certificates API: PHP
Authenticates with the SSL/TLS Certificates API, requests yesterday's first result page with a keyword filter, and distinguishes an empty page from an explicit API error.
<?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"]) && !empty($data["error"])) {
throw new Exception($data["error"]);
}
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"];
// Request yesterday's first certificate page with a plain keyword filter.
$date_code = gmdate("Ymd", time() - 86400);
$params = http_build_query([
"kw" => "amazon",
"date" => $date_code,
"start" => 0,
"limit" => 50,
"sorton" => "valid_from",
"sortorder" => "desc"
]);
$url = $base_url . "/" . rawurlencode($token) . "/certificates?" . $params;
$certificates = get_json($url);
echo "<pre>";
if (empty($certificates["data"])) {
echo "No matching certificates on this page.\n";
} else {
foreach ($certificates["data"] as $cert) {
printf(
"%s %s %s\n",
$cert["id"] ?? "",
$cert["subject_cn"] ?? "",
$cert["valid_from_date_time"] ?? ""
);
}
}
echo "</pre>";
} catch (Exception $e) {
echo "Error: " . htmlspecialchars($e->getMessage(), ENT_QUOTES, "UTF-8");
}
?>
These examples intentionally use a plain keyword term. The public v2 reference does not promise wildcard/operator syntax or a specific indexed-field scope for TLS keyword search.