To check domain availability programmatically, ask the registrar where you plan to register the name. Read the result for that exact domain, even when the HTTP request succeeds. A useful domain picker can tell a customer “available at this registrar,” “unavailable here,” or “we couldn’t complete the check.” Each answer leads to a different next step.
Choose the lookup that answers your question
Suppose a merchant wants a domain for a new store. Visiting the address shows a blank page. That tells you little about whether the merchant can buy it. An owner can hold a domain for email, leave it undelegated, or simply choose never to launch a website.
If you need evidence of an existing registration, look up the exact domain in WHOIS or RDAP and check that the returned record matches the name. If you need a fast status signal while someone builds a shortlist, the WhoisJSONAPI Domain Availability API reports active or inactive using DNS and, when applicable, WHOIS. A registered name with no DNS delegation can return inactive. If your interface promises that a customer can register a name, use the registrar’s availability endpoint before showing that promise.
Check domain availability with cURL
This example uses Cloudflare Registrar. Set ACCOUNT_ID and CLOUDFLARE_API_TOKEN in your server-side shell to credentials for an account with access to the registrar check. Run this Bash command with example.com as a known registered name, then replace it with a candidate of your own. The request is read-only.
curl --silent --show-error --fail-with-body --max-time 15 \
"https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/registrar/domain-check" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
-H 'Content-Type: application/json' \
--data '{"domains":["example.com"]}'Find the matching name in result.domains. When registrable is true, the pricing object includes the currency, registration cost, and renewal cost. When it is false, inspect reason. For instance, domain_unavailable can mean registered or reserved. By contrast, extension_not_supported_via_api means the customer may still be able to use the registrar’s dashboard. Both responses contain false, but only one calls for suggesting a different name.
Check one or more domains with Python
Save the following as check_domains.py. It uses Python 3’s standard library and the same two environment variables as the cURL example. Run python check_domains.py example.com example.org. It accepts up to 20 distinct names per run, the registrar’s limit for one request.
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
names = list(dict.fromkeys(s.lower().strip().rstrip('.') for s in sys.argv[1:]))
if not 1 <= len(names) <= 20:
sys.exit('Supply 1 to 20 domain names.')
account = os.environ['ACCOUNT_ID']
token = os.environ['CLOUDFLARE_API_TOKEN']
request = Request(
f'https://api.cloudflare.com/client/v4/accounts/{account}/registrar/domain-check',
data=json.dumps({'domains': names}).encode(),
headers={'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'},
)
try:
with urlopen(request, timeout=15) as response:
payload = json.load(response)
except HTTPError as error:
sys.exit(f'Availability unknown for this batch (HTTP {error.code}).')
except (URLError, TimeoutError, ValueError) as error:
sys.exit(f'Availability unknown for this batch ({error}).')
if payload.get('success') is not True:
sys.exit('Lookup failed. Availability is unknown for this batch.')
rows = {r['name'].lower(): r for r in payload['result']['domains']}
for name in names:
row = rows.get(name, {})
if row.get('registrable') is True:
status = 'Available at this registrar'
elif row.get('registrable') is False:
status = row.get('reason') or 'Unavailable at this registrar'
else:
status = 'Unknown: no decision returned'
print(f'{name}: {status}')The script matches results by name. If the API returns two rows for three requested domains, the missing domain gets its own unknown result. For longer lists, split the input into groups of 20 and record the outcome of each batch. A failed second batch should leave the first batch’s results intact.
Handle failures before checkout
For a 401 or 403, check credentials and account permissions. For a 429, respect the provider’s retry instructions. On a timeout or temporary server error, show “Couldn’t check right now” and allow a later retry. Keep the token on your backend and send only the domain decision and relevant pricing to the browser.
When the customer chooses a name, run a fresh check with the registrar that will handle the purchase. Show the current price and renewal terms before asking them to proceed. Another customer can register the same name between the lookup and checkout. Show registration as
complete only after your registrar confirms it. Cloudflare Registrar endpoint reference
Walk through a merchant’s shortlist
A merchant pastes three names into your store builder and asks which one she can use today. Imagine the first has an active website, the second has no visible website, and the third is on an extension your registrar cannot sell. Those observations are enough to start a conversation. They are a poor basis for enabling a Buy button. Here is how to turn the three checks into something the merchant can act on.
Start with the first name. A successful registration lookup returns a matching domain record. The merchant may already own it, so give her a way to connect an existing domain. Asking her to choose another name is the wrong next step if she came to your app to use the address printed on her business cards. Connecting an existing domain is a separate operation and should require its own proof of control.
For the second name, suppose the registrar returns a positive decision and prices in USD. Show the exact spelling alongside the price for the first term and the renewal price. Keep the result attached to that name. If the merchant edits one letter, clear the old price and check the new spelling. A green badge next to a new name with the previous name’s price can be more misleading than an empty result.
For the third name, inspect the restriction. If the extension is unavailable through your integration, say so and offer the supported extensions the merchant can check from this screen. A message like “We can’t register this extension here” preserves a useful distinction. The merchant can still investigate that exact name elsewhere without assuming a third party already owns it.
Decide which domain the user actually wants
A surprisingly common input is a complete address copied from a browser. Someone pastes https://shop.example.com/summer and expects a meaningful answer. The path identifies a page, shop.example.com identifies a host, and example.com is the domain in this example that someone can register. Before sending a lookup, decide whether the field accepts a domain name or a website address. Give the field a label and an example that match that decision.
For a registration form, the simplest behavior is to ask for the exact domain, such as example.com, and show a correction when the input contains a path. If your product accepts URLs for convenience, display the extracted candidate and let the customer confirm it. Dropping the leftmost label blindly creates another problem. A customer may have entered a name under a multi-label suffix such as co.uk. Keeping the final two labels would leave you checking co.uk itself.
A bulk import has another wrinkle. The same candidate can appear several times, in different letter case or with surrounding spaces. Keep the original row numbers, normalize each candidate once, and make one lookup for each distinct name. Map each result back to every source row that requested it. This saves calls while still letting a customer reconcile your output with their spreadsheet. Include rejected inputs in the export with a plain explanation so a missing row never has to stand in for an error message.
Interpret a response one domain at a time
Consider a sample response with two results. The first row says registrable is true. The second says registrable is false and gives domain_premium as the reason. Both rows arrived in one successful HTTP response. If your code uses the status of the HTTP request to paint every row green, your customer sees two purchase buttons even though the registrar API can fulfill only one of those requests.
Keep the original reason alongside your display text. That gives support something specific to look up and lets you change the wording without rewriting past observations. For the premium example, explain that the API cannot complete that premium registration. Avoid quoting a standard price for it. If your app offers an alternative provider, ask that provider for its own answer before presenting a price or promising that it can sell the name.
Now consider an unexpected response. The service adds a reason code you have never seen. Your app still knows that the registrar returned false. It can say that registration is unavailable through this registrar and retain the new code for investigation. If the decision field itself is missing, the app knows less. Treat that case as unknown and keep the purchase action disabled. These two cases deserve separate tests because a missing field can otherwise quietly become false when JSON is converted to application objects.
Process a spreadsheet of 47 names
Suppose an agency sends a spreadsheet with 47 distinct, valid candidate domains. At 20 domains per request, the example endpoint needs three batches containing 20, 20, and seven names. Give each input row a place in the output before making the first call. A small output file can use these columns: original input, normalized name, registrar, outcome, reason, and time checked. Add price and currency when the response supplies them.
Imagine that the first batch succeeds, the second times out, and the last succeeds. The agency now has 27 completed checks and 20 unresolved checks. Write those counts in the summary. Reporting “27 available” would be misleading because a completed check may have returned an unavailable name. Reporting “import failed” would hide the 27 decisions the agency can already use. A retry should target the unresolved group and preserve the outcomes already delivered.
A partial response needs one more step. Suppose the retried batch contains 20 requested names but the reply has 19 usable decisions. Match every response by domain, mark the unmatched input as unknown, and include it in the next retry if the job still has time. Matching by array position can attach the price or availability of one candidate to another. This bug is easy to miss during development because a small sample response often happens to arrive in input order.
If the agency returns tomorrow, let it choose whether to resume an interrupted job or start a fresh check of the entire list. Those actions answer different questions. Resuming fills gaps in yesterday’s report. Starting again gives the agency a new set of observations for its current shortlist. Keep the timestamp on each row so a report assembled over two days never looks like a single simultaneous survey.
Keep the search box accurate while someone types
Consider a customer typing a name, pausing, and then adding an s. The first lookup starts before the second. The second lookup finishes quickly and displays its answer. A moment later, the slower first response arrives. Without a guard in the interface, it can replace the correct answer with the decision for a different spelling. The backend can be completely correct while the customer still sees the wrong status.
One practical fix is to give each search a sequence number. Store the latest number next to the current input. When a response arrives, update the screen only if its number still matches and the normalized name is still the one in the field. Also clear the previous result when the customer edits or empties the box. Waiting for a short pause in typing reduces requests, but the sequence check handles the separate problem of responses arriving out of order.
A cached result can make a shortlist feel faster. If you use one, include the registrar and normalized domain in the cache key and keep the observation time with the answer. Show the time when someone revisits a saved shortlist. Keep failed requests out of the cache used for positive purchase decisions. An outage at ten in the morning should never cause every name a customer viewed during that outage to appear taken for the rest of the day.
Test the checker without buying a domain
Start with saved sample responses and a fake HTTP client. Give the client a fixture for each outcome you promise to display. A fixed fixture lets you test a positive decision at any time, even after a real name changes hands. Keep live checks as a separate integration test for account permissions, endpoint paths, and response shape. That separation lets a developer work on the user interface without an API token or a live registration attempt.
For the first test, ask for two names and return them in reverse order with different decisions. Assert the displayed status for each exact name. For the second test, leave one name out of a successful response. Assert that the missing name remains visible and gets an unknown result. For the third, make the first call time out and the second return a good response. Verify that the retry updates the failed row and removes its earlier error message.
Test the words the customer will see as well as the data fields. Give the app an unsupported extension and check that the screen explains the registrar restriction. Give it a premium restriction and check that the standard checkout button is disabled. Then give it a successful result with different first-year and renewal amounts. Assert that both labels and the currency are visible. A test that checks only for a green badge would pass even if those two prices were accidentally reversed.
Finally, test a change of mind. Start a check for one spelling, type a different spelling, and deliver the older response last. Confirm that the screen still describes the second name. Repeat the exercise with an empty input. There should be no price and no active checkout action after the customer clears the field. This is a quick way to catch a bug that a command-line test of the same endpoint will never reveal.
Diagnose a report that a domain was shown as available
Ask for the exact name, the approximate time, and the step where the user saw the message. A result shown while browsing suggestions has different evidence behind it from a result shown after a live registrar check. Look for the normalized name in your application record and verify the provider, decision, reason, and observation time. Compare the name in that record with the name actually sent to checkout, including the extension.
Suppose a customer says a .net name showed as available, but the record contains a successful lookup for the .com spelling. Repeating the .net lookup today might give a perfectly valid answer and still reveal nothing about yesterday’s bug. Trace the request associated with the displayed row. If the names differ, inspect your row matching and search-box updates first. If the names match but the lookup was hours old, investigate when the application refreshes a saved suggestion.
If the evidence shows a fresh positive result followed by a negative result for the same name at checkout, preserve both observations. Availability can change between those events. Keep the customer’s other choices and show the new decision with its time. Support can then explain exactly what happened without guessing who registered the name or implying the first lookup ever held it for the customer.
Frequently asked questions
Can I use DNS alone to check whether a domain is registered?
No. A registered domain can have no public DNS delegation. Use a registration lookup when ownership status matters and a registrar check when purchase eligibility matters.
Does an empty WHOIS or RDAP result mean I can buy the domain?
An empty result alone is inconclusive. Check for lookup errors and confirm the exact name with the registrar. A registry can reserve a name even when there is no ordinary registration record.
Why do two domain checkers disagree?
Check what each service measures and when it checked. A DNS status service can report inactive for a registered domain. Registrars can also support different extensions or apply different rules to premium names.
Does an availability check reserve the name?
No. Treat availability as a point-in-time answer. Keep the customer’s alternatives until registration succeeds.
