# List agents
Source: https://developers.dnsradar.dev/api-reference/agents/list-agents
https://api.dnsradar.dev/openapi.json get /agents
Get a paginated list of all team members in the organization.
# Get event details
Source: https://developers.dnsradar.dev/api-reference/events/get-event-details
https://api.dnsradar.dev/openapi.json get /monitors/{monitor_id}/events/{event_id}
Get details of a specific event.
# List events for monitor
Source: https://developers.dnsradar.dev/api-reference/events/list-events-for-monitor
https://api.dnsradar.dev/openapi.json get /monitors/{monitor_id}/events
Get a paginated list of DNS changes (as events) detected for a specific monitor.
An events is recorded each time a DNS change is detected for the monitor or when a monitor stays on an invalid state. In that last case, the `incidence_count` increases and triggers an event.
You can filter the events by either `occurred_before` or `occurred_after`, as UTC Timestamps. You can use the pagination parameters to navigate through the list of events.
# Bulk update monitors in group
Source: https://developers.dnsradar.dev/api-reference/groups/bulk-update-monitors-in-group
https://api.dnsradar.dev/openapi.json patch /groups/{group_id}/monitors
Update all monitors in a group with the same settings.
This endpoint allows you to bulk update settings for all monitors within a specified group in a single request. You can update the active status, notification timing, match type, and expected values for all monitors in the group. Only the fields you provide will be updated; omitted fields remain unchanged.
# Create group
Source: https://developers.dnsradar.dev/api-reference/groups/create-group
https://api.dnsradar.dev/openapi.json post /groups
Create a new group.
You can create multiple groups to organize your monitors effectively. Each group must have a unique slug. You can create unlimited groups on all plans.
# Delete group
Source: https://developers.dnsradar.dev/api-reference/groups/delete-group
https://api.dnsradar.dev/openapi.json delete /groups/{group_id}
Removes a group.
# Get group
Source: https://developers.dnsradar.dev/api-reference/groups/get-group
https://api.dnsradar.dev/openapi.json get /groups/{group_id}
Get details of a specific group.
The group slug is a URL-friendly identifier for the group. You can use this slug to filter monitors by group using the `group` query parameter on the `/monitors` endpoint.
# List groups
Source: https://developers.dnsradar.dev/api-reference/groups/list-groups
https://api.dnsradar.dev/openapi.json get /groups
Get a paginated list of all groups.
Groups help you organize your monitors into logical collections for easier management and reporting. You can filter monitors by group using the `group` query parameter on the `/monitors` endpoint. A default group is automatically created and cannot be removed, but can be renamed. This is required in order to attach a monitor to a group that will be used to send Webhook notifications.
# Update group
Source: https://developers.dnsradar.dev/api-reference/groups/update-group
https://api.dnsradar.dev/openapi.json patch /groups/{group_id}
Update a group's name and/or slug.
You can update a group's name and/or slug. You can pass only the fields you want to update; other fields will remain unchanged.Changing the slug will affect how you reference the group in API calls.
# Create monitor
Source: https://developers.dnsradar.dev/api-reference/monitors/create-monitor
https://api.dnsradar.dev/openapi.json post /monitors
Create a new DNS monitor. Rate limited to 250 requests per minutes.
Please note that the free plan limited to 50 total monitors. If you plan to add many monitors, consider using the bulk endpoint `/monitors/bulk` instead.
# Create multiple monitors
Source: https://developers.dnsradar.dev/api-reference/monitors/create-multiple-monitors
https://api.dnsradar.dev/openapi.json post /monitors/bulk
Create up to 1000 monitors in a single request. Rate limited to 250 requests per minutes.
Useful for initial bulk imports, this allows you to import up to 250 000 monitors per minutes. Please note that the free plan limited to 50 total monitors.
# Delete monitor
Source: https://developers.dnsradar.dev/api-reference/monitors/delete-monitor
https://api.dnsradar.dev/openapi.json delete /monitors/{monitor_id}
Removes a monitor.
# Delete multiple monitors
Source: https://developers.dnsradar.dev/api-reference/monitors/delete-multiple-monitors
https://api.dnsradar.dev/openapi.json delete /monitors/bulk
Delete up to multiple monitors in a single request by providing an array of monitor IDs.
# Disable monitor
Source: https://developers.dnsradar.dev/api-reference/monitors/disable-monitor
https://api.dnsradar.dev/openapi.json post /monitors/{monitor_id}/disable
Pause a monitor.
Disabling a monitor will stop its DNS checks until it is re-enabled. Can be useful if a DNS entry has been temporarily changed or is having issues, to avoid unecessary noise.
# Enable monitor
Source: https://developers.dnsradar.dev/api-reference/monitors/enable-monitor
https://api.dnsradar.dev/openapi.json post /monitors/{monitor_id}/enable
Enable a paused monitor.
Enabling a monitor will resume its DNS checks.
# Get monitor
Source: https://developers.dnsradar.dev/api-reference/monitors/get-monitor
https://api.dnsradar.dev/openapi.json get /monitors/{monitor_id}
Get details of a specific monitor by UUID.
# List monitors
Source: https://developers.dnsradar.dev/api-reference/monitors/list-monitors
https://api.dnsradar.dev/openapi.json get /monitors
Get a paginated list of all DNS monitors for the organization.
You can filter monitors by group, state, domain, subdomain, full\_domain, record\_type and is\_active. For example: ?group=production\&state=invalid\&is\_active=true Note: If full\_domain is provided, it will be split into domain and subdomain, overriding any values set in the domain and subdomain parameters.
# Update monitor
Source: https://developers.dnsradar.dev/api-reference/monitors/update-monitor
https://api.dnsradar.dev/openapi.json patch /monitors/{monitor_id}
Update a monitor's configuration.
Allows you to update a monitor to adjust to your specific needs. You can update one or more fields of the monitor, and fields not included in the request body will remain unchanged.
# Get organization details
Source: https://developers.dnsradar.dev/api-reference/organization/get-organization-details
https://api.dnsradar.dev/openapi.json get /organization
Get details of the organization that manages the API key.
# Create webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/create-webhook
https://api.dnsradar.dev/openapi.json post /webhooks
Create a new webhook for receiving event notifications.
By default, an organization is limited to have 5 webhooks per group. If you need more webhooks, feel free to contact us and explain your needs, and we'll update your limits accordingly
# Delete webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/delete-webhook
https://api.dnsradar.dev/openapi.json delete /webhooks/{webhook_id}
Removes a webhook.
# Disable webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/disable-webhook
https://api.dnsradar.dev/openapi.json post /webhooks/{webhook_id}/disable
Disable a webhook to stop receiving notifications.
Disabling a webhook will stop all notifications from being sent to the specified URL until it is re-enabled. Can be useful if the endpoint is temporarily unavailable or if you want to pause notifications for any reason.
# Enable webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/enable-webhook
https://api.dnsradar.dev/openapi.json post /webhooks/{webhook_id}/enable
Enable a disabled webhook and clear any errors.
Enabling a webhook will resume sending notifications to the specified URL according to its configuration. If the webhook was previously disabled due to errors, enabling it will also clear those errors and allow notifications to be sent again.If a webhook has been automatically disabled due to repeated failures, the next enable attempt will not reset the failure count. If an error occurs again, the failure count will continue where it stopped. So ensure the webhook is working fine before re-enabling it to avoid longer wait.
# Get webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/get-webhook
https://api.dnsradar.dev/openapi.json get /webhooks/{webhook_id}
Get details of a specific webhook.
# List webhook requests
Source: https://developers.dnsradar.dev/api-reference/webhooks/list-webhook-requests
https://api.dnsradar.dev/openapi.json get /webhooks/{webhook_id}/requests
Get a paginated list of webhook execution requests.
# List webhooks
Source: https://developers.dnsradar.dev/api-reference/webhooks/list-webhooks
https://api.dnsradar.dev/openapi.json get /webhooks
Get a paginated list of all webhooks for the organization.
You can filter webhooks by their active status using the `is_active` query parameter. For example: ?is\_active=true
# Retry webhook request
Source: https://developers.dnsradar.dev/api-reference/webhooks/retry-webhook-request
https://api.dnsradar.dev/openapi.json post /webhooks/{webhook_id}/requests/{request_id}/retry
Retry a failed webhook request delivery.
This endpoint allows you to retry the delivery of a specific webhook request that have failed previously. Upon calling this endpoint, the system will attempt to resend the webhook payload to the original URL using the same method and headers as before. This is useful for recovering from temporary issues that may have caused the initial delivery to fail.We only allow to retry once every 30 seconds to avoid any abuses.
# Test webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/test-webhook
https://api.dnsradar.dev/openapi.json post /webhooks/{webhook_id}/test
Send a test payload to the webhook endpoint.
This endpoint allows you to send a test payload to your webhook URL to verify that it is set up correctly and can receive notifications. The test payload simulates a webhook event, allowing you to check the integration without waiting for an actual event to occur. Tests are limited to 5 per minutes, and 50 per hours to avoid any abuses.
# Update webhook
Source: https://developers.dnsradar.dev/api-reference/webhooks/update-webhook
https://api.dnsradar.dev/openapi.json patch /webhooks/{webhook_id}
Update a webhook's configuration.
Allows you to change the webhook's settings to adapt to your needs. You can update one or more fields of the webhook, and fields not included in the request body will remain unchanged.Changing the header field will completely replace the existing headers; it will not merge them.
# Authentication
Source: https://developers.dnsradar.dev/docs/authentication
Learn how to authenticate your API requests with DNSRadar
## API Key Authentication
The DNSRadar API uses API keys to authenticate requests. All API requests must include your secret API key in the request header to identify your account and authorize access.
Your API keys carry significant privileges. Keep them secure and never share them in publicly accessible areas such as GitHub, client-side code, or public repositories.
## Getting Your API Key
You can create and manage your API keys from the [DNSRadar Dashboard](https://dashboard.dnsradar.dev):
1. Log in to your account
2. Navigate to Settings → API Keys
3. Click "Generate New API Key"
4. Copy and securely store your key
API keys have the prefix `sk_` followed by a unique identifier.
## Making Authenticated Requests
Include your API key in the `X-Api-Key` header with every request:
```bash cURL theme={null}
curl https://api.dnsradar.dev/monitors \
-H "X-Api-Key: sk_your_api_key_here"
```
```javascript JavaScript theme={null}
const response = await fetch('https://api.dnsradar.dev/monitors', {
headers: {
'X-Api-Key': 'sk_your_api_key_here'
}
});
```
```python Python theme={null}
import requests
headers = {
'X-Api-Key': 'sk_your_api_key_here'
}
response = requests.get('https://api.dnsradar.dev/monitors', headers=headers)
```
```php PHP theme={null}
$ch = curl_init('https://api.dnsradar.dev/monitors');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Api-Key: sk_your_api_key_here'
]);
$response = curl_exec($ch);
```
## Authentication Errors
If authentication fails, you'll receive one of the following error responses:
| Status Code | Error | Description |
| ----------- | ------------ | --------------------------------------------------- |
| `401` | Unauthorized | No API key was provided in the request header |
| `403` | Forbidden | The API key provided is invalid or has been revoked |
## Best Practices
Generate new API keys periodically and revoke old ones to minimize security risks.
Store API keys in environment variables rather than hardcoding them in your application code.
Track which keys are being used and where to quickly identify and respond to potential security issues.
Always make API requests over HTTPS to prevent your API key from being intercepted.
# Error Codes
Source: https://developers.dnsradar.dev/docs/error-codes
Understanding DNSRadar API error responses and how to handle them
## Overview
The DNSRadar API uses conventional HTTP response codes to indicate the success or failure of an API request. Codes in the `2xx` range indicate success, codes in the `4xx` range indicate an error caused by the provided information, and codes in the `5xx` range indicate an error with DNSRadar's servers.
## Error Response Format
When an error occurs, the API returns a JSON response with the following structure:
```json theme={null}
{
"code": 400,
"error": "Invalid request parameters",
"errors": {
"domain": "Domain name is required",
"record_type": "Must be one of: A, AAAA, CNAME, MX, TXT, NS, PTR"
}
}
```
HTTP status code indicating the error type
Human-readable error message describing what went wrong
Field-specific validation errors (present for 400 Bad Request responses)
## HTTP Status Codes
### Success Codes
| Code | Status | Description |
| ----- | ---------- | -------------------------------------------------------------------------- |
| `200` | OK | Request succeeded. The response body contains the requested data. |
| `204` | No Content | Request succeeded with no response body (typically for DELETE operations). |
### Client Error Codes
Your request is invalid or malformed. This typically means:
* A required parameter is missing
* A parameter has an invalid value
* The request body is not valid JSON
* Validation constraints are not met
**Example:**
```json theme={null}
{
"code": 400,
"errors": {
"expected_value": "Must provide at least one value",
"frequency": "Must be one of: 5, 10, 15, 30, 60, 120"
}
}
```
**How to fix:** Check the `errors` object in the response for specific field-level validation errors.
No API key was provided in the request header.
**Example:**
```json theme={null}
{
"code": 401,
"error": "Unauthorized"
}
```
**How to fix:** Include your API key in the `X-Api-Key` header. See [Authentication](/docs/authentication) for details.
Your request requires a premium subscription or you've reached your plan limits.
**Example:**
```json theme={null}
{
"code": 402,
"error": "Monitor limit reached. Upgrade to create more monitors."
}
```
**How to fix:** Upgrade your plan in the [Dashboard](https://dashboard.dnsradar.dev) or remove existing monitors.
The API key provided is invalid, expired, or has been revoked.
**Example:**
```json theme={null}
{
"code": 403,
"error": "Invalid API key"
}
```
**How to fix:** Verify your API key is correct or generate a new one from the Dashboard.
The requested resource does not exist or you don't have access to it.
**Example:**
```json theme={null}
{
"code": 404,
"error": "Monitor not found"
}
```
**How to fix:** Check that the resource UUID is correct and belongs to your organization.
The HTTP method used is not supported for this endpoint.
**Example:**
```json theme={null}
{
"code": 405,
"error": "Method not allowed"
}
```
**How to fix:** Use the correct HTTP method (GET, POST, PATCH, DELETE) as specified in the API documentation.
You've exceeded the rate limit for API requests.
**Example:**
```json theme={null}
{
"code": 429,
"error": "Rate limit exceeded"
}
```
**How to fix:** Wait for the rate limit to reset (check `X-RateLimit-Reset` header) or implement exponential backoff. See [Rate Limiting](/docs/rate-limit) for details.
### Server Error Codes
An unexpected error occurred on DNSRadar's servers.
**Example:**
```json theme={null}
{
"code": 500,
"error": "Internal server error"
}
```
**How to fix:** This is a server-side issue. Retry your request after a brief wait. If the problem persists, contact [support@dnsradar.dev](mailto:support@dnsradar.dev).
The API is temporarily unavailable, typically due to maintenance.
**How to fix:** Wait a few minutes and retry your request. Check our status page for updates.
## Handling Errors
Here's how to properly handle errors in your code:
```javascript JavaScript theme={null}
try {
const response = await fetch('https://api.dnsradar.dev/monitors', {
headers: { 'X-Api-Key': apiKey }
});
if (!response.ok) {
const error = await response.json();
console.error(`Error ${error.code}: ${error.error}`);
if (error.errors) {
// Handle validation errors
Object.entries(error.errors).forEach(([field, message]) => {
console.error(`${field}: ${message}`);
});
}
}
} catch (err) {
console.error('Network error:', err);
}
```
```python Python theme={null}
import requests
try:
response = requests.get(
'https://api.dnsradar.dev/monitors',
headers={'X-Api-Key': api_key}
)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
error_data = err.response.json()
print(f"Error {error_data['code']}: {error_data['error']}")
if 'errors' in error_data:
for field, message in error_data['errors'].items():
print(f"{field}: {message}")
except requests.exceptions.RequestException as err:
print(f"Request failed: {err}")
```
If you encounter an error not listed here or need assistance, contact us at [support@dnsradar.dev](mailto:support@dnsradar.dev) with the request ID from the response headers.
# OpenAPI Specification
Source: https://developers.dnsradar.dev/docs/openapi
Access the complete OpenAPI specification for the DNSRadar API
## Overview
The DNSRadar API is fully documented using the OpenAPI 3.0 specification (formerly known as Swagger). This machine-readable format allows you to automatically generate client libraries, test your API integration, and import the API into various development tools.
## Download the Specification
You can access our complete OpenAPI specification file here:
Download the latest OpenAPI 3.0 JSON specification
Our OpenAPI specification is automatically updated whenever we release new API features or changes. You can always access the latest version at the URL above.
## What's Included
The OpenAPI specification contains complete details about:
All available API endpoints with their paths, HTTP methods, and descriptions
Query parameters, path parameters, headers, and request body schemas
Detailed response structures for success and error cases
Security schemes and authentication requirements
Complete schema definitions for all data types (Monitors, Events, Webhooks, etc.)
Request and response examples for each endpoint
## Using the Specification
### Generate Client Libraries
Use the OpenAPI specification to automatically generate client libraries in your preferred programming language:
```bash OpenAPI Generator theme={null}
# Install OpenAPI Generator
npm install @openapitools/openapi-generator-cli -g
# Generate a Python client
openapi-generator-cli generate \
-i https://api.dnsradar.dev/openapi.json \
-g python \
-o ./dnsradar-python-client
# Generate a JavaScript/TypeScript client
openapi-generator-cli generate \
-i https://api.dnsradar.dev/openapi.json \
-g typescript-fetch \
-o ./dnsradar-ts-client
```
```bash Swagger Codegen theme={null}
# Using Swagger Codegen
swagger-codegen generate \
-i https://api.dnsradar.dev/openapi.json \
-l ruby \
-o ./dnsradar-ruby-client
```
### Import into Development Tools
The OpenAPI specification can be imported into popular API development tools:
Import the spec into Postman to get a complete collection of all API endpoints
Load the OpenAPI file directly into Insomnia for API testing
Use Swagger UI to create an interactive API documentation interface
Use OpenAPI extensions in VS Code for autocomplete and validation
### Example: Using with Postman
1. Open Postman and click **Import**
2. Select **Link** and paste: `https://api.dnsradar.dev/openapi.json`
3. Click **Import** to create a complete collection
4. Add your API key to the collection variables
5. Start making requests
### Example: Self-Hosting API Documentation
You can host your own version of the API documentation using the OpenAPI specification:
```html theme={null}
DNSRadar API Documentation
```
## Validation and Testing
Use the OpenAPI specification to validate your API requests and responses:
```javascript theme={null}
import { OpenAPIValidator } from 'express-openapi-validator';
// Validate requests against the OpenAPI spec
app.use(
OpenAPIValidator.middleware({
apiSpec: 'https://api.dnsradar.dev/openapi.json',
validateRequests: true,
validateResponses: true,
})
);
```
## Version History
Our API follows semantic versioning. The current version is documented in the OpenAPI specification's `info.version` field:
```json theme={null}
{
"openapi": "3.0.3",
"info": {
"title": "DNSRadar API",
"version": "1.0.0",
"description": "Monitor your DNS records and get notified when they change"
}
}
```
Subscribe to our changelog or follow us on [X (Twitter)](https://x.com/dnsradardev) and [Bluesky](https://bsky.app/@dnsradar.dev) to get notified about API updates and new features.
## Support
If you find any issues with the OpenAPI specification or have suggestions for improvement, please contact us at [support@dnsradar.dev](mailto:support@dnsradar.dev).
# Pagination
Source: https://developers.dnsradar.dev/docs/pagination
Learn how to paginate through large result sets in the DNSRadar API
## Overview
The DNSRadar API uses cursor-based pagination for all list endpoints. This approach provides consistent results even when data is being modified, making it ideal for reliable data synchronization and iteration.
Cursor-based pagination ensures you never miss items or see duplicates, even if data changes between requests.
## Pagination Parameters
All paginated endpoints accept the following query parameters:
Number of items to return per page
**Range:** 1-100 items
**Default:** 20 items
Cursor for fetching the next page of results
Use the `after` value from the previous response to get the next page
Cursor for fetching the previous page of results
Use the `before` value from the previous response to get the previous page
Field to order results by
Available fields depend on the endpoint (e.g., `created`, `domain`, `name`)
Sort direction
**Values:** `asc` (ascending) or `desc` (descending)
**Default:** `asc`
## Response Structure
All paginated responses follow this structure:
```json theme={null}
{
"limit": 20,
"after": "eyJpZCI6MTIzNDU2fQ==",
"before": "eyJpZCI6MTIzNDAwfQ==",
"has_more": true,
"data": [
// Array of items
]
}
```
### Response Fields
The number of items per page requested
Cursor to fetch the next page of results
`null` if there are no more pages
Cursor to fetch the previous page of results
`null` if this is the first page
Indicates whether there are more items after the current page
Use this to determine if you should fetch the next page
Array of items for the current page
## Paginated Endpoints
The following endpoints support pagination:
* `GET /agents` - List team members
* `GET /monitors` - List DNS monitors
* `GET /monitors/{monitor_uuid}/events` - List events for a monitor
* `GET /groups` - List monitor groups
* `GET /groups/{slug}/monitors` - List monitors in a group
* `GET /webhooks` - List webhooks
* `GET /webhooks/{uuid}/requests` - List webhook execution requests
## Basic Pagination
### Fetching the First Page
To get the first page of results, simply call the endpoint without any cursor parameters:
```bash cURL theme={null}
curl "https://api.dnsradar.dev/monitors?limit=20" \
-H "X-Api-Key: sk_your_api_key_here"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://api.dnsradar.dev/monitors?limit=20',
{
headers: {
'X-Api-Key': 'sk_your_api_key_here'
}
}
);
const data = await response.json();
console.log(`Fetched ${data.data.length} monitors`);
console.log(`Has more pages: ${data.has_more}`);
```
```python Python theme={null}
import requests
response = requests.get(
'https://api.dnsradar.dev/monitors',
params={'limit': 20},
headers={'X-Api-Key': 'sk_your_api_key_here'}
)
data = response.json()
print(f"Fetched {len(data['data'])} monitors")
print(f"Has more pages: {data['has_more']}")
```
```go Go theme={null}
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
type PaginatedResponse struct {
Limit int `json:"limit"`
After *string `json:"after"`
Before *string `json:"before"`
HasMore bool `json:"has_more"`
Data []interface{} `json:"data"`
}
func main() {
apiKey := "sk_your_api_key_here"
params := url.Values{}
params.Add("limit", "20")
req, _ := http.NewRequest("GET",
"https://api.dnsradar.dev/monitors?"+params.Encode(),
nil)
req.Header.Set("X-Api-Key", apiKey)
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result PaginatedResponse
json.Unmarshal(body, &result)
fmt.Printf("Fetched %d monitors\n", len(result.Data))
fmt.Printf("Has more pages: %t\n", result.HasMore)
}
```
```php PHP theme={null}
```
### Fetching the Next Page
Use the `after` cursor from the response to fetch the next page:
```bash cURL theme={null}
curl "https://api.dnsradar.dev/monitors?limit=20&after=eyJpZCI6MTIzNDU2fQ==" \
-H "X-Api-Key: sk_your_api_key_here"
```
```javascript JavaScript theme={null}
let allMonitors = [];
let after = null;
do {
const url = new URL('https://api.dnsradar.dev/monitors');
url.searchParams.set('limit', '20');
if (after) {
url.searchParams.set('after', after);
}
const response = await fetch(url, {
headers: {
'X-Api-Key': 'sk_your_api_key_here'
}
});
const data = await response.json();
allMonitors.push(...data.data);
after = data.after;
} while (after !== null);
console.log(`Fetched ${allMonitors.length} monitors total`);
```
```python Python theme={null}
import requests
all_monitors = []
after = None
while True:
params = {'limit': 20}
if after:
params['after'] = after
response = requests.get(
'https://api.dnsradar.dev/monitors',
params=params,
headers={'X-Api-Key': 'sk_your_api_key_here'}
)
data = response.json()
all_monitors.extend(data['data'])
after = data.get('after')
if not after:
break
print(f"Fetched {len(all_monitors)} monitors total")
```
```go Go theme={null}
func fetchAllMonitors(apiKey string) ([]interface{}, error) {
var allMonitors []interface{}
var after *string
for {
params := url.Values{}
params.Add("limit", "20")
if after != nil {
params.Add("after", *after)
}
req, _ := http.NewRequest("GET",
"https://api.dnsradar.dev/monitors?"+params.Encode(),
nil)
req.Header.Set("X-Api-Key", apiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var result PaginatedResponse
json.Unmarshal(body, &result)
allMonitors = append(allMonitors, result.Data...)
if result.After == nil {
break
}
after = result.After
}
return allMonitors, nil
}
```
```php PHP theme={null}
```
## Sorting Results
You can control the sort order of results using `order_by` and `order_way` parameters:
```bash cURL - Newest First theme={null}
curl "https://api.dnsradar.dev/monitors?order_by=created&order_way=desc&limit=20" \
-H "X-Api-Key: sk_your_api_key_here"
```
```bash cURL - Alphabetical theme={null}
curl "https://api.dnsradar.dev/monitors?order_by=domain&order_way=asc&limit=20" \
-H "X-Api-Key: sk_your_api_key_here"
```
```javascript JavaScript theme={null}
// Fetch monitors sorted by creation date (newest first)
const response = await fetch(
'https://api.dnsradar.dev/monitors?order_by=created&order_way=desc&limit=20',
{
headers: {
'X-Api-Key': 'sk_your_api_key_here'
}
}
);
```
```python Python theme={null}
# Fetch monitors sorted alphabetically by domain
response = requests.get(
'https://api.dnsradar.dev/monitors',
params={
'order_by': 'domain',
'order_way': 'asc',
'limit': 20
},
headers={'X-Api-Key': 'sk_your_api_key_here'}
)
```
## Navigating Backwards
Use the `before` cursor to navigate to the previous page:
```javascript theme={null}
// After navigating forward several pages
const response = await fetch(
`https://api.dnsradar.dev/monitors?limit=20&before=${beforeCursor}`,
{
headers: {
'X-Api-Key': 'sk_your_api_key_here'
}
}
);
```
The `before` cursor is useful for implementing "Previous" buttons in pagination UI or for backward navigation in your application.
## Best Practices
Choose page sizes based on your use case:
* **Small pages (10-20):** Good for UI display, faster response times
* **Medium pages (50):** Balanced for most applications
* **Large pages (100):** Efficient for bulk processing, fewer API calls
```javascript theme={null}
// For UI display
const uiResponse = await fetch(
'https://api.dnsradar.dev/monitors?limit=10'
);
// For bulk processing
const bulkResponse = await fetch(
'https://api.dnsradar.dev/monitors?limit=100'
);
```
Always check the `has_more` field to avoid unnecessary requests:
```javascript theme={null}
const data = await fetchPage();
if (data.has_more) {
// Fetch next page
const nextPage = await fetchPage(data.after);
} else {
console.log('Reached the end of results');
}
```
Empty result sets are valid and should be handled gracefully:
```python theme={null}
data = response.json()
if len(data['data']) == 0:
print("No items found")
else:
for item in data['data']:
process_item(item)
```
Save the `after` cursor to resume pagination later:
```javascript theme={null}
// Save progress
localStorage.setItem('lastCursor', data.after);
// Resume later
const lastCursor = localStorage.getItem('lastCursor');
if (lastCursor) {
const response = await fetch(
`https://api.dnsradar.dev/monitors?after=${lastCursor}`
);
}
```
The actual number of items returned may be less than the requested limit, even if more pages exist:
```javascript theme={null}
// Don't do this
if (data.data.length < limit) {
// Wrong assumption: might not be the last page
}
// Do this instead
if (data.has_more) {
// Correctly check for more pages
}
```
When iterating through all pages, respect rate limits by adding delays:
```python theme={null}
import time
after = None
while True:
data = fetch_page(after)
process_data(data['data'])
after = data.get('after')
if not after:
break
# Add delay to respect rate limits
time.sleep(0.5)
```
## Complete Example: Paginated Export
Here's a complete example of exporting all monitors to a CSV file:
```javascript Node.js theme={null}
import fs from 'fs';
async function exportMonitorsToCSV(apiKey) {
const monitors = [];
let after = null;
let pageCount = 0;
console.log('Fetching monitors...');
do {
const url = new URL('https://api.dnsradar.dev/monitors');
url.searchParams.set('limit', '100');
if (after) {
url.searchParams.set('after', after);
}
const response = await fetch(url, {
headers: { 'X-Api-Key': apiKey }
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
monitors.push(...data.data);
pageCount++;
console.log(`Fetched page ${pageCount} (${data.data.length} items)`);
after = data.after;
// Respect rate limits
if (after) {
await new Promise(resolve => setTimeout(resolve, 500));
}
} while (after !== null);
console.log(`\nTotal monitors fetched: ${monitors.length}`);
// Convert to CSV
const csv = [
'UUID,Domain,Subdomain,Type,State,Active',
...monitors.map(m =>
`${m.uuid},${m.domain},${m.subdomain},${m.record_type},${m.state},${m.is_active}`
)
].join('\n');
fs.writeFileSync('monitors.csv', csv);
console.log('Exported to monitors.csv');
}
// Usage
exportMonitorsToCSV('sk_your_api_key_here')
.catch(console.error);
```
```python Python theme={null}
import requests
import csv
import time
def export_monitors_to_csv(api_key, filename='monitors.csv'):
monitors = []
after = None
page_count = 0
print('Fetching monitors...')
while True:
params = {'limit': 100}
if after:
params['after'] = after
response = requests.get(
'https://api.dnsradar.dev/monitors',
params=params,
headers={'X-Api-Key': api_key}
)
if response.status_code != 200:
raise Exception(f"HTTP {response.status_code}: {response.text}")
data = response.json()
monitors.extend(data['data'])
page_count += 1
print(f"Fetched page {page_count} ({len(data['data'])} items)")
after = data.get('after')
if not after:
break
# Respect rate limits
time.sleep(0.5)
print(f"\nTotal monitors fetched: {len(monitors)}")
# Write to CSV
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['UUID', 'Domain', 'Subdomain', 'Type', 'State', 'Active'])
for monitor in monitors:
writer.writerow([
monitor['uuid'],
monitor['domain'],
monitor['subdomain'],
monitor['record_type'],
monitor['state'],
monitor['is_active']
])
print(f"Exported to {filename}")
# Usage
if __name__ == '__main__':
export_monitors_to_csv('sk_your_api_key_here')
```
```go Go theme={null}
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"time"
)
type Monitor struct {
UUID string `json:"uuid"`
Domain string `json:"domain"`
Subdomain string `json:"subdomain"`
RecordType string `json:"record_type"`
State string `json:"state"`
IsActive bool `json:"is_active"`
}
type PaginatedMonitors struct {
Limit int `json:"limit"`
After *string `json:"after"`
Before *string `json:"before"`
HasMore bool `json:"has_more"`
Data []Monitor `json:"data"`
}
func exportMonitorsToCSV(apiKey, filename string) error {
var monitors []Monitor
var after *string
pageCount := 0
fmt.Println("Fetching monitors...")
for {
params := url.Values{}
params.Add("limit", "100")
if after != nil {
params.Add("after", *after)
}
req, _ := http.NewRequest("GET",
"https://api.dnsradar.dev/monitors?"+params.Encode(),
nil)
req.Header.Set("X-Api-Key", apiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
var result PaginatedMonitors
json.Unmarshal(body, &result)
monitors = append(monitors, result.Data...)
pageCount++
fmt.Printf("Fetched page %d (%d items)\n", pageCount, len(result.Data))
if result.After == nil {
break
}
after = result.After
// Respect rate limits
time.Sleep(500 * time.Millisecond)
}
fmt.Printf("\nTotal monitors fetched: %d\n", len(monitors))
// Write to CSV
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
// Header
writer.Write([]string{"UUID", "Domain", "Subdomain", "Type", "State", "Active"})
// Data
for _, m := range monitors {
writer.Write([]string{
m.UUID,
m.Domain,
m.Subdomain,
m.RecordType,
m.State,
fmt.Sprintf("%t", m.IsActive),
})
}
fmt.Printf("Exported to %s\n", filename)
return nil
}
func main() {
if err := exportMonitorsToCSV("sk_your_api_key_here", "monitors.csv"); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
```
## Common Pitfalls
**Don't Manipulate Cursors**: Cursors are opaque tokens. Never try to decode, modify, or construct them manually. Always use the values provided by the API.
**Don't Use Offset-Based Logic**: Unlike offset-based pagination, you cannot jump to arbitrary pages (e.g., "page 5"). You must iterate sequentially using cursors.
**Cursors Can Expire**: Cursors may become invalid after extended periods. If you receive an error, restart pagination from the beginning.
## See Also
* [Rate Limiting](/docs/rate-limit) - Understanding API rate limits when paginating
* [Error Codes](/docs/error-codes) - Handling pagination errors
* [API Reference](/docs/openapi) - Detailed endpoint documentation
# Rate Limiting
Source: https://developers.dnsradar.dev/docs/rate-limit
Understanding API rate limits and how to handle them effectively
## Overview
The DNSRadar API implements rate limiting to ensure fair usage and maintain service quality for all users. Rate limits are applied per API key and reset at fixed intervals.
All rate limits use a sliding window algorithm, meaning limits reset continuously rather than at fixed intervals.
## Rate Limit Tiers
### Standard Endpoints
Most API endpoints follow these rate limits:
**20 requests per minute**
Applies to all `GET` requests
**5 requests per minute**
Applies to `POST`, `PUT`, `PATCH`, and `DELETE` requests
### Bulk Import Endpoints
The following endpoints have higher limits to support bulk operations:
**250 requests per minute**
Applies to:
* `POST /monitors`
* `POST /monitors/bulk`
The `POST /monitors/bulk` endpoint accepts up to 1,000 monitors per request, allowing you to theoretically import **250,000 monitors per minute** when used efficiently.
## Rate Limit Headers
Every API response includes headers that provide information about your current rate limit status:
The maximum number of requests you can make per minute for this endpoint
**Example:** `20`
The number of requests remaining in the current rate limit window
**Example:** `15`
Unix timestamp (in seconds) indicating when the rate limit window resets
**Example:** `1704636000`
### Example Response Headers
```http theme={null}
HTTP/1.1 200 OK
X-RateLimit-Limit: 20
X-RateLimit-Remaining: 15
X-RateLimit-Reset: 1704636000
Content-Type: application/json
```
## Handling Rate Limits
### Rate Limit Exceeded Response
When you exceed the rate limit, you'll receive a `429 Too Many Requests` response:
```json theme={null}
{
"code": 429,
"error": "Rate limit exceeded. Please try again in 45 seconds."
}
```
### Best Practices
Always check the `X-RateLimit-Remaining` header and proactively slow down requests before hitting the limit.
```javascript theme={null}
const remaining = parseInt(response.headers.get('X-RateLimit-Remaining'));
if (remaining < 3) {
console.warn('Approaching rate limit. Slowing down requests...');
await sleep(5000); // Wait 5 seconds
}
```
When you receive a 429 response, wait before retrying with increasing delays between attempts.
```javascript theme={null}
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch(url, options);
if (response.status !== 429) {
return response;
}
const resetTime = parseInt(response.headers.get('X-RateLimit-Reset'));
const waitTime = (resetTime * 1000) - Date.now();
console.log(`Rate limited. Waiting ${waitTime}ms before retry...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
throw new Error('Max retries exceeded');
}
```
When creating multiple monitors, use the `POST /monitors/bulk` endpoint instead of making individual requests.
**Instead of this:**
```javascript theme={null}
// 1000 requests = exceeds rate limit
for (const monitor of monitors) {
await createMonitor(monitor);
}
```
**Do this:**
```javascript theme={null}
// 1 request = efficient
await createMonitorsBulk(monitors); // up to 1000 at once
```
Cache responses from GET requests when appropriate to reduce unnecessary API calls.
```javascript theme={null}
const cache = new Map();
const CACHE_TTL = 60000; // 1 minute
async function getCachedMonitors() {
const cached = cache.get('monitors');
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const data = await fetchMonitors();
cache.set('monitors', { data, timestamp: Date.now() });
return data;
}
```
Instead of sending bursts of requests, distribute them evenly across the rate limit window.
```javascript theme={null}
// Spread 20 requests over 60 seconds (1 per 3 seconds)
const delayBetweenRequests = 60000 / 20; // 3000ms
for (const item of items) {
await processItem(item);
await sleep(delayBetweenRequests);
}
```
## Rate Limit Examples
### Checking Rate Limit Status
```javascript JavaScript theme={null}
const response = await fetch('https://api.dnsradar.dev/monitors', {
headers: { 'X-Api-Key': apiKey }
});
const limit = response.headers.get('X-RateLimit-Limit');
const remaining = response.headers.get('X-RateLimit-Remaining');
const reset = response.headers.get('X-RateLimit-Reset');
console.log(`Rate Limit: ${remaining}/${limit} requests remaining`);
console.log(`Resets at: ${new Date(reset * 1000).toISOString()}`);
```
```python Python theme={null}
import requests
from datetime import datetime
response = requests.get(
'https://api.dnsradar.dev/monitors',
headers={'X-Api-Key': api_key}
)
limit = response.headers.get('X-RateLimit-Limit')
remaining = response.headers.get('X-RateLimit-Remaining')
reset = int(response.headers.get('X-RateLimit-Reset'))
print(f"Rate Limit: {remaining}/{limit} requests remaining")
print(f"Resets at: {datetime.fromtimestamp(reset).isoformat()}")
```
```bash cURL theme={null}
curl -i https://api.dnsradar.dev/monitors \
-H "X-Api-Key: your_api_key"
# Look for these headers in the response:
# X-RateLimit-Limit: 20
# X-RateLimit-Remaining: 15
# X-RateLimit-Reset: 1704636000
```
Need higher rate limits? Contact our [sales team](mailto:support@dnsradar.dev) to discuss enterprise plans with custom rate limits.
# Webhook Events
Source: https://developers.dnsradar.dev/docs/webhooks
Learn how DNSRadar sends webhook events and how to handle them securely
## Overview
DNSRadar sends webhook events to notify your application in real-time when DNS monitoring events occur. When a monitor detects a change in DNS records, we'll send an HTTP POST request to your configured webhook endpoint with details about the event.
Webhooks enable you to build automated workflows and integrations that respond immediately to DNS changes without polling the API.
## Event Payload Structure
When an event occurs, we send a POST request to your webhook URL with the following JSON payload:
```json theme={null}
{
"id": "req_abc123...",
"webhook_id": "whk_abc123...",
"event": {
"id": "evt_abc123...",
"monitor_id": "mon_abc123...",
"occurred": "2023-11-07T05:31:56Z",
"previous_value": [
"192.168.1.1"
],
"current_value": [
"10.0.0.1"
],
"old_state": "MISMATCH",
"new_state": "VALID",
"incidence_count": 0,
"domain": {
"domain": "example.com",
"subdomain": "www",
"record_type": "A",
"expected_value": [
"192.168.1.1"
],
"is_exact_match": false
}
},
"created": "2023-11-07T05:31:56"
}
```
### Payload Fields
Unique identifier for this webhook request
Unique identifier of the webhook configuration
The monitoring event that triggered the webhook
Unique identifier for the event
Unique identifier of the monitor that detected the change
ISO 8601 timestamp when the event occurred
The DNS record values before this event (if available)
The current DNS record values (if available)
The previous state of the monitor (VALID, MISMATCH, ERROR)
The current state of the monitor (VALID, MISMATCH, ERROR)
Number of consecutive times the monitor has been in this state
Domain configuration object for the monitor
The root domain being monitored
The subdomain being monitored (if applicable)
The DNS record type (A, AAAA, CNAME, MX, TXT, etc.)
The expected DNS record values for the monitor
Whether the monitor requires an exact match of DNS values
ISO 8601 timestamp when the webhook request was created
## Retry Logic
DNSRadar implements an automatic retry mechanism to ensure reliable delivery of webhook events. If your endpoint returns a non-2xx status code, we'll retry the request using an incremental backoff strategy.
### Retry Schedule
| Attempt | Delay |
| --------- | ---------- |
| 1st retry | 5 minutes |
| 2nd retry | 10 minutes |
| 3rd retry | 15 minutes |
| 4th retry | 30 minutes |
| 5th retry | 1 hour |
| 6th retry | 2 hours |
| 7th retry | 6 hours |
| 8th retry | 12 hours |
| 9th retry | 24 hours |
After the 9th retry fails, we'll stop attempting to deliver the event and notify you. All events for this webhook will be paused until a successful request is made.
### Webhook Pausing
If a webhook consistently fails, all events attached to that webhook will be automatically paused to prevent further failed attempts. The webhook will resume automatically once a request succeeds.
Monitor your webhook health in the [DNSRadar Dashboard](https://dashboard.dnsradar.dev) to identify and resolve issues before events are paused.
## Security
### Webhook Signatures
Every webhook request includes cryptographic signatures to verify authenticity and prevent unauthorized requests.
#### Signature Headers
HMAC-SHA256 signature of the raw request body, signed with your webhook secret
Unix timestamp (in seconds) when the webhook was sent
### Verifying Signatures
To ensure the webhook request is legitimate and hasn't been tampered with, verify the signature on every request:
```javascript Node.js theme={null}
import crypto from 'crypto';
function verifyWebhookSignature(payload, signature, secret, timestamp) {
// Check timestamp to prevent replay attacks (within 5 minutes)
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - timestamp) > 300) {
throw new Error('Webhook timestamp is too old');
}
// Compute HMAC signature
const hmac = crypto.createHmac('sha256', secret);
hmac.update(payload);
const computedSignature = hmac.digest('hex');
// Compare signatures securely
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(computedSignature))) {
throw new Error('Invalid webhook signature');
}
return true;
}
// Express.js example
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-dnsradar-signature'];
const timestamp = parseInt(req.headers['x-webhook-timestamp']);
const secret = process.env.WEBHOOK_SECRET;
try {
verifyWebhookSignature(req.body, signature, secret, timestamp);
// Parse and process the event
const event = JSON.parse(req.body);
console.log('Received event:', event.event.id);
res.status(200).send('OK');
} catch (error) {
console.error('Webhook verification failed:', error.message);
res.status(401).send('Unauthorized');
}
});
```
```python Python theme={null}
import hmac
import hashlib
import time
from flask import Flask, request, abort
app = Flask(__name__)
def verify_webhook_signature(payload, signature, secret, timestamp):
# Check timestamp to prevent replay attacks (within 5 minutes)
current_time = int(time.time())
if abs(current_time - timestamp) > 300:
raise ValueError('Webhook timestamp is too old')
# Compute HMAC signature
computed_signature = hmac.new(
secret.encode('utf-8'),
payload,
hashlib.sha256
).hexdigest()
# Compare signatures securely
if not hmac.compare_digest(signature, computed_signature):
raise ValueError('Invalid webhook signature')
return True
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('X-DNSRadar-Signature')
timestamp = int(request.headers.get('X-Webhook-Timestamp'))
secret = os.environ.get('WEBHOOK_SECRET')
try:
verify_webhook_signature(request.data, signature, secret, timestamp)
# Parse and process the event
event = request.json
print(f"Received event: {event['event']['id']}")
return 'OK', 200
except ValueError as e:
print(f"Webhook verification failed: {str(e)}")
abort(401)
```
```go Go theme={null}
package main
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
func verifyWebhookSignature(payload []byte, signature, secret string, timestamp int64) error {
// Check timestamp to prevent replay attacks (within 5 minutes)
currentTime := time.Now().Unix()
if abs(currentTime-timestamp) > 300 {
return fmt.Errorf("webhook timestamp is too old")
}
// Compute HMAC signature
h := hmac.New(sha256.New, []byte(secret))
h.Write(payload)
computedSignature := hex.EncodeToString(h.Sum(nil))
// Compare signatures securely
if subtle.ConstantTimeCompare([]byte(signature), []byte(computedSignature)) != 1 {
return fmt.Errorf("invalid webhook signature")
}
return nil
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
signature := r.Header.Get("X-DNSRadar-Signature")
timestampStr := r.Header.Get("X-Webhook-Timestamp")
timestamp, _ := strconv.ParseInt(timestampStr, 10, 64)
secret := os.Getenv("WEBHOOK_SECRET")
// Read body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading body", http.StatusBadRequest)
return
}
// Verify signature
if err := verifyWebhookSignature(body, signature, secret, timestamp); err != nil {
fmt.Printf("Webhook verification failed: %v\n", err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Parse and process event
var event map[string]interface{}
json.Unmarshal(body, &event)
fmt.Printf("Received event: %s\n", event["event"].(map[string]interface{})["id"])
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
func abs(x int64) int64 {
if x < 0 {
return -x
}
return x
}
```
```php PHP theme={null}
300) {
throw new Exception('Webhook timestamp is too old');
}
// Compute HMAC signature
$computedSignature = hash_hmac('sha256', $payload, $secret);
// Compare signatures securely
if (!hash_equals($signature, $computedSignature)) {
throw new Exception('Invalid webhook signature');
}
return true;
}
// Webhook endpoint
$signature = $_SERVER['HTTP_X_DNSTAIL_SIGNATURE'];
$timestamp = intval($_SERVER['HTTP_X_WEBHOOK_TIMESTAMP']);
$secret = getenv('WEBHOOK_SECRET');
$payload = file_get_contents('php://input');
try {
verifyWebhookSignature($payload, $signature, $secret, $timestamp);
// Parse and process the event
$event = json_decode($payload, true);
error_log("Received event: " . $event['event']['id']);
http_response_code(200);
echo 'OK';
} catch (Exception $e) {
error_log("Webhook verification failed: " . $e->getMessage());
http_response_code(401);
echo 'Unauthorized';
}
?>
```
Always verify the timestamp to prevent replay attacks. We recommend rejecting webhooks with timestamps older than 5 minutes.
## Best Practices
Your webhook endpoint should respond with a 2xx status code within 30 seconds. Process events asynchronously if needed.
```javascript theme={null}
app.post('/webhook', async (req, res) => {
// Verify signature first
verifyWebhookSignature(req.body, ...);
// Respond immediately
res.status(200).send('OK');
// Process asynchronously
processWebhookAsync(req.body).catch(console.error);
});
```
Due to retries, you may receive the same event multiple times. Use the `id` field to deduplicate events.
```javascript theme={null}
const processedEvents = new Set();
function handleWebhook(event) {
if (processedEvents.has(event.id)) {
console.log('Duplicate event, skipping');
return;
}
processedEvents.add(event.id);
// Process the event
}
```
Always use HTTPS URLs for your webhook endpoints to ensure data is encrypted in transit.
Track failed webhook attempts in the DNSRadar Dashboard and set up alerts for repeated failures.
Handle errors gracefully and log failures for debugging.
```python theme={null}
@app.route('/webhook', methods=['POST'])
def webhook():
try:
# Verify and process webhook
verify_webhook_signature(...)
process_event(request.json)
return 'OK', 200
except Exception as e:
# Log error but still return 200 if event was received
logger.error(f"Error processing webhook: {e}")
return 'OK', 200 # Prevent retries for processing errors
```
Use the webhook test endpoint to verify your integration before going live.
```bash theme={null}
curl -X POST https://api.dnsradar.dev/webhooks/{id}/test \
-H "X-Api-Key: your_api_key"
```
## Example: Complete Webhook Handler
Here's a complete example of a webhook handler with all best practices:
```javascript Node.js theme={null}
import express from 'express';
import crypto from 'crypto';
const app = express();
const processedEvents = new Set();
// Use raw body parser for signature verification
app.post('/webhook',
express.raw({ type: 'application/json' }),
async (req, res) => {
try {
// Extract headers
const signature = req.headers['x-dnsradar-signature'];
const timestamp = parseInt(req.headers['x-webhook-timestamp']);
const secret = process.env.WEBHOOK_SECRET;
// Verify timestamp (within 5 minutes)
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - timestamp) > 300) {
return res.status(401).send('Timestamp too old');
}
// Verify signature
const hmac = crypto.createHmac('sha256', secret);
hmac.update(req.body);
const computedSignature = hmac.digest('hex');
if (!crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(computedSignature)
)) {
return res.status(401).send('Invalid signature');
}
// Parse event
const webhook = JSON.parse(req.body);
// Check for duplicates
if (processedEvents.has(webhook.id)) {
console.log(`Duplicate event: ${webhook.id}`);
return res.status(200).send('OK');
}
// Mark as processed
processedEvents.add(webhook.id);
// Respond immediately
res.status(200).send('OK');
// Process asynchronously
processEvent(webhook).catch(err => {
console.error('Error processing event:', err);
});
} catch (error) {
console.error('Webhook handler error:', error);
res.status(500).send('Internal error');
}
}
);
async function processEvent(webhook) {
const event = webhook.event;
console.log(`Processing event ${event.id} for ${event.domain}`);
console.log(`State changed: ${event.old_state} → ${event.new_state}`);
// Your custom logic here
if (event.new_state === 'MISMATCH') {
await sendAlert(event);
}
}
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
```
```python Python theme={null}
from flask import Flask, request, abort
import hmac
import hashlib
import time
import json
import logging
from typing import Set
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
processed_events: Set[str] = set()
@app.route('/webhook', methods=['POST'])
def webhook():
try:
# Extract headers
signature = request.headers.get('X-DNSRadar-Signature')
timestamp = int(request.headers.get('X-Webhook-Timestamp', 0))
secret = os.environ.get('WEBHOOK_SECRET')
if not all([signature, timestamp, secret]):
abort(401, 'Missing required headers or configuration')
# Verify timestamp (within 5 minutes)
current_time = int(time.time())
if abs(current_time - timestamp) > 300:
abort(401, 'Timestamp too old')
# Verify signature
computed_signature = hmac.new(
secret.encode('utf-8'),
request.data,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, computed_signature):
abort(401, 'Invalid signature')
# Parse event
webhook_data = request.json
# Check for duplicates
if webhook_data['id'] in processed_events:
logger.info(f"Duplicate event: {webhook_data['id']}")
return 'OK', 200
# Mark as processed
processed_events.add(webhook_data['id'])
# Process event
process_event(webhook_data)
return 'OK', 200
except Exception as e:
logger.error(f"Webhook handler error: {e}")
abort(500, 'Internal error')
def process_event(webhook):
event = webhook['event']
logger.info(f"Processing event {event['id']} for {event['domain']}")
logger.info(f"State changed: {event['old_state']} → {event['new_state']}")
# Your custom logic here
if event['new_state'] == 'MISMATCH':
send_alert(event)
if __name__ == '__main__':
app.run(port=3000)
```
Need help implementing webhooks? Check out our [API Reference](/docs/openapi) or contact [support](mailto:support@dnsradar.dev).
# Introduction
Source: https://developers.dnsradar.dev/index
Monitor your DNS records and get notified when they change
## Welcome to DNSRadar API
DNSRadar is a powerful DNS monitoring service that helps you track changes to your DNS records in real-time. Whether you're managing critical infrastructure, monitoring for security threats, or ensuring DNS propagation, our API provides the tools you need to stay informed.
## What is DNSRadar?
DNSRadar continuously monitors your DNS records and alerts you immediately when changes occur. Track A, AAAA, CNAME, MX, TXT, NS, and other record types with configurable check frequencies from 5 to 120 minutes.
## Key Features
Track DNS records with check frequencies as low as 5 minutes
Get instant notifications when your DNS records change
Access complete history of all DNS changes detected
Integrate with your existing workflows using webhooks
Create and manage up to 1000 monitors at once
Group monitors for better organization and management
## Getting Started
Get up and running with DNSRadar in minutes:
Sign up at [dashboard.dnsradar.dev](https://dashboard.dnsradar.dev) and generate your API key
Include your API key in the `X-Api-Key` header with every request
Set up your first DNS monitor to track changes to your records
Add webhook endpoints to receive notifications when changes occur
## Quick Example
Here's how to create your first DNS monitor:
```bash theme={null}
curl -X POST https://api.dnsradar.dev/monitors \
-H "X-Api-Key: your_api_key" \
-H "Content-Type: application/json" \
-d '{
"domain": "example.com",
"subdomain": "www",
"record_type": "A",
"expected_value": ["192.168.1.1"],
"frequency": 60
}'
```
## Use Cases
* **Security Monitoring**: Detect unauthorized DNS changes that could indicate hijacking attempts
* **Infrastructure Management**: Track DNS propagation and ensure your records are configured correctly
* **Compliance**: Maintain audit trails of all DNS changes for compliance requirements
* **DevOps Integration**: Automate DNS monitoring as part of your deployment pipelines
* **Multi-Team Coordination**: Share monitoring responsibilities across teams with grouped monitors
## API Overview
The DNSRadar API is organized around REST principles with predictable resource-oriented URLs. We use standard HTTP response codes, authentication, and verbs. All API responses are returned in JSON format.
**Base URL**: `https://api.dnsradar.dev`
## Need Help?
Explore all available endpoints and parameters
Learn how to authenticate your API requests
Get help from our support team
Manage your monitors via web interface