# DNS records

Read and update the DNS host records on a domain that uses the registrar's DNS management.

Read and update the DNS host records on a domain that uses the registrar's DNS management.

<Note>
  DNS management depends on the registrar module backing your account. The current sandbox registrar returns a `501` "Function not supported by the registrar module" for both DNS calls. The request and response shapes below describe the intended behavior on a registrar that supports DNS management; see the observed sandbox response at the end of each section.
</Note>

## Get DNS records

Return the DNS host records for a domain.

`GET /domains/{domain}/dns`

### Parameters

<ParamField path="domain" type="text" required>
  The domain to read, for example `example.com`.
</ParamField>

### Request

<CodeGroup>
```bash cURL
API_KEY="your-api-key"
EMAIL="you@example.com"
ENDPOINT="https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php"
TS=$(date -u +"%y-%m-%d %H")
TOKEN=$(printf '%s' "$API_KEY" \
  | openssl dgst -sha256 -hmac "$EMAIL:$TS" -hex \
  | sed 's/^.*= //' | tr -d '\n' | base64 -w0)
curl -s "$ENDPOINT/domains/example.com/dns" \
  -H "username: $EMAIL" \
  -H "token: $TOKEN"
```

```php PHP
<?php
$apiKey   = "your-api-key";
$email    = "you@example.com";
$endpoint = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php";

$token = base64_encode(hash_hmac("sha256", $apiKey, "{$email}:" . gmdate("y-m-d H")));

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$endpoint}/domains/example.com/dns");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "username: {$email}",
    "token: {$token}",
]);
echo curl_exec($curl);
curl_close($curl);
```

```python Python
from datetime import datetime, timezone

API_KEY  = "your-api-key"
EMAIL    = "you@example.com"
ENDPOINT = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php"

def token() -> str:
    ts = datetime.now(timezone.utc).strftime("%y-%m-%d %H")
    digest = hmac.new(f"{EMAIL}:{ts}".encode(), API_KEY.encode(), hashlib.sha256).hexdigest()
    return base64.b64encode(digest.encode()).decode()

resp = requests.get(f"{ENDPOINT}/domains/example.com/dns",
                    headers={"username": EMAIL, "token": token()})
print(resp.status_code, resp.json())
```

```javascript Node.js

const API_KEY  = "your-api-key";
const EMAIL    = "you@example.com";
const ENDPOINT = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php";

function token() {
  const ts = new Date().toISOString().slice(2, 13).replace("T", " "); // "yy-mm-dd HH" UTC
  const digest = crypto.createHmac("sha256", `${EMAIL}:${ts}`).update(API_KEY).digest("hex");
  return Buffer.from(digest, "utf8").toString("base64");
}

const res = await fetch(`${ENDPOINT}/domains/example.com/dns`, {
  headers: { username: EMAIL, token: token() },
});
console.log(res.status, await res.json());
```

```go Go
package main

	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"time"
)

const (
	apiKey   = "your-api-key"
	email    = "you@example.com"
	endpoint = "https://portal.hostraha.com/modules/addons/DomainsReseller/api/index.php"
)

func token() string {
	ts := time.Now().UTC().Format("06-01-02 15") // yy-mm-dd HH
	mac := hmac.New(sha256.New, []byte(email+":"+ts))
	mac.Write([]byte(apiKey))
	return base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(mac.Sum(nil))))
}

func main() {
	req, _ := http.NewRequest("GET", endpoint+"/domains/example.com/dns", nil)
	req.Header.Set("username", email)
	req.Header.Set("token", token())
	resp, _ := http.DefaultClient.Do(req)
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}
```
</CodeGroup>

### Response

On a registrar that supports DNS management, this returns the current host records as an array of [DNS record](/api-reference/models) objects. On the sandbox registrar it returns:

```json
{"error":"Function not supported by the registrar module"}
```

## Save DNS records

Replace the DNS host records on a domain. Send the full set you want stored; records omitted from the request are removed.

`POST /domains/{domain}/dns`

### Parameters

<ParamField path="domain" type="text" required>
  The domain to update, for example `example.com`.
</ParamField>
<ParamField body="dnsrecords" type="array" required>
  The full set of host records, indexed from `0`. Each record is a [DNS record](/api-reference/models) object with `hostname`, `type`, `address`, `priority`, and an optional `recid` on existing records.
</ParamField>

Encode each record with indexed bracket notation, for example `dnsrecords[0][hostname]=@`.

### Request

<CodeGroup>
```bash cURL
curl -s "$ENDPOINT/domains/example.com/dns" \
  -H "username: $EMAIL" \
  -H "token: $TOKEN" \
  --data "dnsrecords[0][hostname]=@" \
  --data "dnsrecords[0][type]=A" \
  --data "dnsrecords[0][address]=192.0.2.1" \
  --data "dnsrecords[0][priority]=0" \
  --data "dnsrecords[1][hostname]=www" \
  --data "dnsrecords[1][type]=CNAME" \
  --data "dnsrecords[1][address]=example.com" \
  --data "dnsrecords[1][priority]=0"
```

```php PHP
<?php
// Reuse the auth setup from the get example above.
$fields = http_build_query([
    "dnsrecords" => [
        ["hostname" => "@",   "type" => "A",     "address" => "192.0.2.1",   "priority" => 0],
        ["hostname" => "www", "type" => "CNAME", "address" => "example.com", "priority" => 0],
    ],
]);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$endpoint}/domains/example.com/dns");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "username: {$email}",
    "token: {$token}",
]);
echo curl_exec($curl);
curl_close($curl);
```

```python Python
records = [
    {"hostname": "@",   "type": "A",     "address": "192.0.2.1",   "priority": 0},
    {"hostname": "www", "type": "CNAME", "address": "example.com", "priority": 0},
]
data = {
    f"dnsrecords[{i}][{key}]": value
    for i, record in enumerate(records)
    for key, value in record.items()
}

resp = requests.post(f"{ENDPOINT}/domains/example.com/dns",
                     headers={"username": EMAIL, "token": token()},
                     data=data)
print(resp.status_code, resp.json())
```

```javascript Node.js
const records = [
  { hostname: "@",   type: "A",     address: "192.0.2.1",   priority: 0 },
  { hostname: "www", type: "CNAME", address: "example.com", priority: 0 },
];

const body = new URLSearchParams();
records.forEach((record, i) => {
  for (const [key, value] of Object.entries(record)) {
    body.append(`dnsrecords[${i}][${key}]`, String(value));
  }
});

const res = await fetch(`${ENDPOINT}/domains/example.com/dns`, {
  method: "POST",
  headers: { username: EMAIL, token: token() },
  body,
});
console.log(res.status, await res.json());
```

```go Go
// Add "net/url" and "strings" to the imports.
records := []map[string]string{
	{"hostname": "@", "type": "A", "address": "192.0.2.1", "priority": "0"},
	{"hostname": "www", "type": "CNAME", "address": "example.com", "priority": "0"},
}
form := url.Values{}
for i, record := range records {
	for key, value := range record {
		form.Set(fmt.Sprintf("dnsrecords[%d][%s]", i, key), value)
	}
}

req, _ := http.NewRequest("POST", endpoint+"/domains/example.com/dns", strings.NewReader(form.Encode()))
req.Header.Set("username", email)
req.Header.Set("token", token())
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
```
</CodeGroup>

### Response

On a registrar that supports DNS management, this returns a success status once the records are stored. On the sandbox registrar it returns:

```json
{"error":"Function not supported by the registrar module"}
```
