Adding your domain using Netlify API

by Artem Denysov

Netlify exposes the Netlify REST API for different use cases to replicate the UI experience with code. Let’s explore a few ways to add a domain to your account and site programmatically.

#Add a custom domain API example

To add a custom domain to your site you have to make a PATCH request to the updateSite endpoint with a payload that includes the custom_domain parameter and its value.

Make sure you are authorized to make this request as a Developer or Owner on the Netlify team account.

curl example:

Terminal window
curl -X PATCH "https://api.netlify.com/api/v1/sites/{site_id}" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-H "Content-Type: application/json" \
-d '{
"custom_domain": "your-domain.com"
}'

#Add a subdomain API example

Adding a subdomain follows a similar process. You just have to provide the value of the subdomain in your payload.

If you haven’t added an apex domain to Netlify DNS, your domain will have to pass additional verification. Verification is important. Once a subdomain is added to Netlify DNS, no other account can add that subdomain. So to prevent domains takeovers, Netlify requires verification.

Before adding a subdomain to the site, add host netlify-challenge.your-domain.com with any value to your DNS TXT record. Netlify will verify the host netlify-challenge.your-domain.com value before adding your subdomain to the site. So, when passing custom_domain as part of the site update endpoint, you have to provide the parameter txt_record_value as well with the same value as you’ve added to your DNS record for host netlify-challenge.your-domain.com.

curl example:

Terminal window
curl -X PATCH "https://api.netlify.com/api/v1/sites/{site_id}" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-H "Content-Type: application/json" \
-d '{
"custom_domain": "subdomain.your-domain.com",
"txt_record_value": "value"
}'

To finish up the process of adding a domain you have to either use Netlify DNS or provide your custom SSL certificate.