DEV Community

Cover image for dnspython vs a DNS API: When Should You Query Resolvers Yourself?
Nadeem Khan
Nadeem Khan

Posted on AI-assisted

dnspython vs a DNS API: When Should You Query Resolvers Yourself?

DNS lookups look like the simplest thing in a script: give it a name, get back records. Then you hit a timeout on one domain out of fifty, a TXT record that comes back in pieces, or a cached answer from just before your change, and the simple part turns into a few hundred lines.

There are two ways to get DNS data into Python. You can query resolvers yourself with dnspython, or you can call an HTTP DNS API and get JSON back. I work at WhoisFreaks, which sells one of those APIs, so read the trade-offs with that in mind. I've tried to give the do-it-yourself route a fair hearing, because for a lot of jobs it's the right one.

Below, the same lookups are done both ways for two hostnames we tested recently: hybrit.co.uk, whose SPF policy is split across two TXT strings, and www.stovestoreonline.com, a CNAME alias of a CDN host.

Setup

pip install dnspython requests
export WHOISFREAKS_API_KEY="your-key"   # only needed for the API examples
Enter fullscreen mode Exit fullscreen mode

All the code below is Python 3.9+ and dnspython 2.x.

1. Every record type through your own resolver

dnspython's Resolver reads your system's resolver settings, so this asks the same server your machine already uses.

import dns.exception
import dns.resolver

RECORD_TYPES = ["A", "AAAA", "CNAME", "MX", "NS", "TXT", "SOA"]

def resolver_lookup(name, timeout=2.0, lifetime=5.0):
    resolver = dns.resolver.Resolver()   # reads /etc/resolv.conf
    resolver.timeout = timeout           # seconds per nameserver try
    resolver.lifetime = lifetime         # seconds for the whole query
    for rdtype in RECORD_TYPES:
        try:
            answer = resolver.resolve(name, rdtype, raise_on_no_answer=False)
        except dns.resolver.NXDOMAIN:
            print(f"{name} does not exist")
            return
        except (dns.resolver.NoNameservers, dns.exception.Timeout) as exc:
            print(f"{rdtype}: lookup failed ({exc.__class__.__name__})")
            continue
        if answer.rrset is None:
            continue
        for rdata in answer.rrset:
            if rdtype == "TXT":
                # join without spaces; tolerate non-UTF-8 bytes
                value = b"".join(rdata.strings).decode(errors="replace")
            else:
                value = rdata.to_text()
            print(f"{rdtype:6} ttl={answer.rrset.ttl:<6} {value}")

resolver_lookup("hybrit.co.uk")
Enter fullscreen mode Exit fullscreen mode

Three details matter here.

There is no "all" query. You ask for each type in turn, so one domain is seven round trips. The old ANY query type is no longer a reliable shortcut: RFC 8482 lets servers answer it with a minimal response.

Timeouts are yours to tune. timeout is per nameserver attempt and lifetime caps each query. The values above are dnspython's defaults (2 and 5 seconds), and because the cap applies to each record type separately, a domain whose nameservers never answer can cost up to 35 seconds in this function. In a batch job, set lifetime lower.

TXT records come back as a tuple of strings. A single TXT string holds at most 255 characters, so long SPF policies are split, and RFC 7208, section 3.3 says the pieces are joined with no space. hybrit.co.uk splits its policy right after ip4:. Join the decoded pieces with a space and you get ip4: 195.149.90.22, which no longer parses; call rdata.to_text() instead and you get both halves still wrapped in quotes. b"".join(rdata.strings) gets it right.

The TTL you print is the resolver's copy, counted down by however long it has been cached. Run the function twice a few seconds apart and the numbers usually drop. On a big public resolver they can also jump back up, because the next query may land on a different cache.

2. Skipping the cache: asking the zone directly

After a DNS change you usually want the zone's own answer, not whatever your resolver remembers. With dnspython that means finding an authoritative nameserver and sending it a query with recursion turned off.

import dns.flags
import dns.message
import dns.query
import dns.resolver

def authoritative_lookup(name, rdtype="CNAME", timeout=3.0):
    zone = dns.resolver.zone_for_name(name)
    ns_host = dns.resolver.resolve(zone, "NS")[0].target
    ns_ip = dns.resolver.resolve(ns_host, "A")[0].address
    query = dns.message.make_query(name, rdtype)
    query.flags &= ~dns.flags.RD             # recursion off: answer from your own zone
    # UDP first; retried over TCP if the answer comes back truncated
    response, _ = dns.query.udp_with_fallback(query, ns_ip, timeout=timeout)
    for rrset in response.answer:
        print(rrset.to_text())

authoritative_lookup("www.stovestoreonline.com")
Enter fullscreen mode Exit fullscreen mode

This returns the full TTL the zone publishes. In our test the zone's value was 300 seconds, while a cached answer through a resolver showed 262.

It also shows a catch. The zone that holds a CNAME only answers for its own names, so asking it for the A record of www.stovestoreonline.com gets you the CNAME and nothing else. To reach the addresses you have to repeat the whole process for the target's zone. That's a loop of NS lookups, A lookups and UDP queries you now own, along with retries, IPv6-only nameservers and the occasional lame delegation.

3. Many domains at once

dnspython's default resolver blocks (it also ships dns.asyncresolver if your code is already async), but threads work well for I/O like this:

from concurrent.futures import ThreadPoolExecutor

import dns.exception
import dns.resolver

def first_a_record(domain):
    try:
        answer = dns.resolver.resolve(domain, "A", lifetime=5.0)
        return domain, answer[0].address
    except dns.exception.DNSException as exc:
        return domain, f"error: {exc.__class__.__name__}"

def resolver_bulk(domains, workers=20):
    with ThreadPoolExecutor(max_workers=workers) as pool:
        for domain, result in pool.map(first_a_record, domains):
            print(f"{domain:30} {result}")

resolver_bulk(["example.com", "example.org", "python.org"])
Enter fullscreen mode Exit fullscreen mode

This scales further than you'd expect, but the limit isn't your code. Push thousands of names through one resolver and you start seeing SERVFAILs and timeouts that have nothing to do with the domains. Public resolvers rate-limit heavy clients, and a small local resolver can start dropping queries. You end up adding backoff, rotating resolvers or running your own recursive server.

4. The same lookup through a DNS API

Here is the first lookup again, through the WhoisFreaks live DNS endpoint:

import os

import requests

API_URL = "https://api.whoisfreaks.com/v2.0/dns/live"

def api_lookup(domain, authoritative=False, cname_depth=0):
    params = {
        "apiKey": os.environ["WHOISFREAKS_API_KEY"],
        "domainName": domain,
        "type": "all",
    }
    if authoritative:
        params["isAuthoritative"] = "true"
    if cname_depth:
        params["cnameDepth"] = cname_depth   # 1 to 4 hops
    resp = requests.get(API_URL, params=params, timeout=30)
    if resp.status_code == 404:
        # 404 covers "domain does not exist" and "no records found"
        print(f"{domain}: {resp.json().get('message', 'not found')}")
        return None
    if resp.status_code == 429:
        raise RuntimeError("Rate limited: back off before retrying")
    resp.raise_for_status()
    data = resp.json()
    for rec in data.get("dnsRecords", []):
        print(f"{rec['dnsType']:6} ttl={rec['ttl']:<6} {rec['rawText']}")
    return data

api_lookup("www.stovestoreonline.com", authoritative=True, cname_depth=1)
Enter fullscreen mode Exit fullscreen mode

What changes:

  • One request covers every record type. type=all returns A, AAAA, MX, NS, CNAME, SOA, TXT and SPF together, or you can pass a comma-separated list.
  • The authoritative read is a flag. isAuthoritative=true asks the zone's own nameservers, and cnameDepth follows the alias for up to 4 hops. Together they replace section 2's loop.
  • Records come back as JSON fields. TXT and SPF records include a strings array with the pieces as published, and SOA records split out serial, refresh, retry, expire and minimum. Each record also carries rawText if you want the zone-file line.
  • Errors are HTTP status codes. A 404 means the domain doesn't exist or has no matching records, and the message field says which. A 429 means you've hit the per-minute rate limit, and the right move is to back off, not retry in a loop. A 408 ("Unable to fetch dns records") is worth retrying later, and a 413 means you're out of credits or sent more than 100 domains in one bulk request.

5. Bulk through the API

The bulk endpoint takes up to 100 domains per request as a JSON body, so longer lists go in batches:

import json
import os

import requests

BULK_URL = "https://api.whoisfreaks.com/v2.0/dns/bulk/live"

BATCH_SIZE = 100  # the endpoint's limit per request

def api_bulk(domains, outfile="bulk_dns.json", cname_depth=0):
    params = {"apiKey": os.environ["WHOISFREAKS_API_KEY"], "type": "A,MX"}
    if cname_depth:
        params["cname_depth"] = cname_depth  # bulk spelling, not cnameDepth
    results = []
    for start in range(0, len(domains), BATCH_SIZE):
        batch = domains[start:start + BATCH_SIZE]
        resp = requests.post(
            BULK_URL,
            params=params,
            json={"domainNames": batch},
            timeout=120,
        )
        resp.raise_for_status()
        results.append(resp.json())
    with open(outfile, "w") as f:
        json.dump(results, f, indent=2)
    print(f"Saved {len(domains)} domains in {len(results)} batches to {outfile}")
Enter fullscreen mode Exit fullscreen mode

Note that the bulk endpoint spells the CNAME option cname_depth, not cnameDepth.

The trade-off

dnspython against a resolver HTTP DNS API
Cost Free Per lookup (WhoisFreaks: 1–3 credits per live query; 1 without cnameDepth)
Record types One query per type type=all in one request
Cached vs zone answer Write the NS lookup and non-recursive query yourself isAuthoritative=true
CNAME chains Resolver follows them; authoritative reads stop at the alias cnameDepth up to 4
Bulk Threads, until resolver throttling bites 100 domains per request
Network needs Outbound port 53 (or HTTPS to a DoH resolver, for cached answers) Outbound HTTPS only
Who sees your queries Your resolver The API provider
Failure modes DNS exceptions per query HTTP status codes

Use dnspython when you're resolving a handful of names, you can reach a resolver over port 53 or DNS-over-HTTPS, cost matters more than convenience, or you don't want a third party to see which domains you're looking up. That covers most application code, health checks and one-off scripts.

Use an API when you need every record type for many domains, you need authoritative answers without writing the delegation walk yourself, your code runs somewhere port 53 is blocked but you still need authoritative answers (dnspython's dns.query.https can reach a DoH resolver, but a zone's own nameservers generally answer only on port 53), or you want one JSON shape to store and diff. Security tooling and monitoring jobs often end up here.

Plenty of teams use both: dnspython inside the app, and an API for audits and investigations.

Two things to check, whichever you pick

  1. Compare TTLs to the zone's own value. A lower number means a cached copy that may predate your last change.
  2. Join TXT strings without spaces. It's the cheapest bug to prevent and one of the most confusing to debug.

We wrote up the test these examples come from, comparing what different sources returned for the same two hostnames, in our SecurityTrails alternative comparison. If you run the dnspython code against your own domains and get something different, I'd like to hear about it in the comments.

Top comments (0)