package main
import (
"context"
"fmt"
"log"
"os"
"github.com/AhaSend/ahasend-go/api"
"github.com/AhaSend/ahasend-go/models/requests"
"github.com/google/uuid"
)
func main() {
client := api.NewAPIClient(api.WithAPIKey(os.Getenv("AHASEND_API_KEY")))
accountID := uuid.MustParse(os.Getenv("AHASEND_ACCOUNT_ID"))
ctx := context.Background()
subAccountID := uuid.MustParse("7d3c9f5e-2a41-4b8e-9c6d-0f1e2a3b4c5d")
// Bootstrap an API key for the sub account.
//
// The SDK sends a fresh Idempotency-Key with this POST and reuses it on
// its own retries, so a retried request is not applied twice.
response, _, err := client.SubAccountsAPI.CreateSubAccountAPIKey(ctx, accountID, subAccountID, requests.CreateAPIKeyRequest{
Label: "Bootstrap key",
Scopes: []string{"messages:send:all", "domains:read"},
// Optional: restrict the key to specific source IPs.
IPAllowList: []string{"203.0.113.0/24"},
})
if err != nil {
log.Fatalf("Error creating sub-account API key: %v", err)
}
// response.SecretKey is returned only on create (and on an idempotent
// replay of it): put it in your secret store now, and never log it.
fmt.Printf("Created API key %s (%s)\n", response.ID, response.Label)
}
PARENT_ACCOUNT_ID="9d0cf9d0-4f5e-4674-bcf1-8ec39968b6e1"
PARENT_SECRET="aha-sk-parent-64-character-key"
curl -sS -X POST "https://api.ahasend.com/v2/accounts/${PARENT_ACCOUNT_ID}/sub-accounts" \
-H "Authorization: Bearer ${PARENT_SECRET}" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: subacct-20240101-acme" \
-d '{"name":"Acme Subsidiary","website":"acme.example.com"}' \
> sub-account.json
CHILD_ACCOUNT_ID="$(jq -r '.id' sub-account.json)"
curl -sS -X POST "https://api.ahasend.com/v2/accounts/${PARENT_ACCOUNT_ID}/sub-accounts/${CHILD_ACCOUNT_ID}/api-keys" \
-H "Authorization: Bearer ${PARENT_SECRET}" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: child-bootstrap-key-20240101-acme" \
-d '{"label":"Bootstrap key","scopes":["messages:send:all","domains:read"]}' \
> child-api-key.json
CHILD_SECRET="$(jq -r '.secret_key' child-api-key.json)"
printf 'Store this one-time child secret securely: %s\n' "${CHILD_SECRET}"
curl -sS "https://api.ahasend.com/v2/accounts/${CHILD_ACCOUNT_ID}/domains" \
-H "Authorization: Bearer ${CHILD_SECRET}"
import { AhaSendClient } from "@ahasend/sdk";
const client = AhaSendClient.fromEnv();
const subAccountId = "00000000-0000-4000-8000-000000000004";
// The SDK sends a fresh Idempotency-Key automatically and reuses it on its own retries.
const apiKey = await client.subAccounts.apiKeys.create(subAccountId, {
label: "Bootstrap key",
scopes: ["messages:send:all"],
});
console.log("Sub-account API key created.", { id: apiKey.id, label: apiKey.label });
import requests
url = "https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys"
payload = {
"label": "Bootstrap key",
"scopes": ["messages:send:all", "domains:read"]
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'label' => 'Bootstrap key',
'scopes' => [
'messages:send:all',
'domains:read'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}HttpResponse<String> response = Unirest.post("https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"label\": \"Bootstrap key\",\n \"scopes\": [\n \"messages:send:all\",\n \"domains:read\"\n ]\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"label\": \"Bootstrap key\",\n \"scopes\": [\n \"messages:send:all\",\n \"domains:read\"\n ]\n}"
response = http.request(request)
puts response.read_body{
"object": "api_key",
"id": "13b3aa8e-78d3-48a1-92d2-4b8b1228c2dd",
"created_at": "2024-01-01T00:05:00Z",
"updated_at": "2024-01-01T00:05:00Z",
"last_used_at": null,
"account_id": "2f3c5d2a-9ef8-4c91-a5f4-79990c8c1d3a",
"label": "Bootstrap key",
"public_key": "aha-pk-child-public-key",
"secret_key": "aha-sk-child-secret-key",
"scopes": [
{
"id": "c574470d-76ef-4f74-9b24-70a583a17e03",
"created_at": "2024-01-01T00:05:00Z",
"updated_at": "2024-01-01T00:05:00Z",
"api_key_id": "13b3aa8e-78d3-48a1-92d2-4b8b1228c2dd",
"scope": "messages:send:all",
"domain_id": null
}
],
"ip_allow_list": []
}{
"message": "Error message"
}{
"message": "Error message"
}{
"message": "Error message"
}{
"message": "Error message"
}{
"message": "A request with this idempotency key is already in progress"
}{
"message": "idempotency key was already used with a different request payload"
}{
"message": "Error message"
}Create a Sub-Account API Key via the API
Issue an API key that authenticates as an AhaSend sub-account, using parent credentials with sub-account-api-keys:write. The secret_key is shown only once.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/AhaSend/ahasend-go/api"
"github.com/AhaSend/ahasend-go/models/requests"
"github.com/google/uuid"
)
func main() {
client := api.NewAPIClient(api.WithAPIKey(os.Getenv("AHASEND_API_KEY")))
accountID := uuid.MustParse(os.Getenv("AHASEND_ACCOUNT_ID"))
ctx := context.Background()
subAccountID := uuid.MustParse("7d3c9f5e-2a41-4b8e-9c6d-0f1e2a3b4c5d")
// Bootstrap an API key for the sub account.
//
// The SDK sends a fresh Idempotency-Key with this POST and reuses it on
// its own retries, so a retried request is not applied twice.
response, _, err := client.SubAccountsAPI.CreateSubAccountAPIKey(ctx, accountID, subAccountID, requests.CreateAPIKeyRequest{
Label: "Bootstrap key",
Scopes: []string{"messages:send:all", "domains:read"},
// Optional: restrict the key to specific source IPs.
IPAllowList: []string{"203.0.113.0/24"},
})
if err != nil {
log.Fatalf("Error creating sub-account API key: %v", err)
}
// response.SecretKey is returned only on create (and on an idempotent
// replay of it): put it in your secret store now, and never log it.
fmt.Printf("Created API key %s (%s)\n", response.ID, response.Label)
}
PARENT_ACCOUNT_ID="9d0cf9d0-4f5e-4674-bcf1-8ec39968b6e1"
PARENT_SECRET="aha-sk-parent-64-character-key"
curl -sS -X POST "https://api.ahasend.com/v2/accounts/${PARENT_ACCOUNT_ID}/sub-accounts" \
-H "Authorization: Bearer ${PARENT_SECRET}" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: subacct-20240101-acme" \
-d '{"name":"Acme Subsidiary","website":"acme.example.com"}' \
> sub-account.json
CHILD_ACCOUNT_ID="$(jq -r '.id' sub-account.json)"
curl -sS -X POST "https://api.ahasend.com/v2/accounts/${PARENT_ACCOUNT_ID}/sub-accounts/${CHILD_ACCOUNT_ID}/api-keys" \
-H "Authorization: Bearer ${PARENT_SECRET}" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: child-bootstrap-key-20240101-acme" \
-d '{"label":"Bootstrap key","scopes":["messages:send:all","domains:read"]}' \
> child-api-key.json
CHILD_SECRET="$(jq -r '.secret_key' child-api-key.json)"
printf 'Store this one-time child secret securely: %s\n' "${CHILD_SECRET}"
curl -sS "https://api.ahasend.com/v2/accounts/${CHILD_ACCOUNT_ID}/domains" \
-H "Authorization: Bearer ${CHILD_SECRET}"
import { AhaSendClient } from "@ahasend/sdk";
const client = AhaSendClient.fromEnv();
const subAccountId = "00000000-0000-4000-8000-000000000004";
// The SDK sends a fresh Idempotency-Key automatically and reuses it on its own retries.
const apiKey = await client.subAccounts.apiKeys.create(subAccountId, {
label: "Bootstrap key",
scopes: ["messages:send:all"],
});
console.log("Sub-account API key created.", { id: apiKey.id, label: apiKey.label });
import requests
url = "https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys"
payload = {
"label": "Bootstrap key",
"scopes": ["messages:send:all", "domains:read"]
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'label' => 'Bootstrap key',
'scopes' => [
'messages:send:all',
'domains:read'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}HttpResponse<String> response = Unirest.post("https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"label\": \"Bootstrap key\",\n \"scopes\": [\n \"messages:send:all\",\n \"domains:read\"\n ]\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.ahasend.com/v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"label\": \"Bootstrap key\",\n \"scopes\": [\n \"messages:send:all\",\n \"domains:read\"\n ]\n}"
response = http.request(request)
puts response.read_body{
"object": "api_key",
"id": "13b3aa8e-78d3-48a1-92d2-4b8b1228c2dd",
"created_at": "2024-01-01T00:05:00Z",
"updated_at": "2024-01-01T00:05:00Z",
"last_used_at": null,
"account_id": "2f3c5d2a-9ef8-4c91-a5f4-79990c8c1d3a",
"label": "Bootstrap key",
"public_key": "aha-pk-child-public-key",
"secret_key": "aha-sk-child-secret-key",
"scopes": [
{
"id": "c574470d-76ef-4f74-9b24-70a583a17e03",
"created_at": "2024-01-01T00:05:00Z",
"updated_at": "2024-01-01T00:05:00Z",
"api_key_id": "13b3aa8e-78d3-48a1-92d2-4b8b1228c2dd",
"scope": "messages:send:all",
"domain_id": null
}
],
"ip_allow_list": []
}{
"message": "Error message"
}{
"message": "Error message"
}{
"message": "Error message"
}{
"message": "Error message"
}{
"message": "A request with this idempotency key is already in progress"
}{
"message": "idempotency key was already used with a different request payload"
}{
"message": "Error message"
}sub-account-api-keys:write; sub-account credentials cannot manage nested API keys. The returned secret_key authenticates as the child account and should be stored immediately.
Bootstrap example:
- Create the sub-account with
POST /v2/accounts/{account_id}/sub-accountsand a uniqueIdempotency-Key. - Create the bootstrap child API key with this endpoint and a different unique
Idempotency-Key. - Store the one-time
secret_keyfrom the201response. Exact idempotent replays within 5 minutes return the samesecret_key. - Use that child secret with the child
sub_account_idas theaccount_idon ordinary v2 routes.
Related guides
- API authentication, Permission scopes, Sub-account setup.
- Sub-account API rules, Sub-account CLI, Idempotency rules.
- API errors, API rate limits, Plans and limits.
Authorizations
Headers
Optional idempotency key for safe request retries. Must be a unique string for each logical request.
A request with a key does its operation at most one time during the life of the key, so a retry with the
same key and the same request is safe after a 5xx, a timeout or a lost answer. An identical request with a
completed stored outcome returns the original status and body. An in-progress execution returns 409, and a
changed method/path/body returns 422. A key lives 24 hours from the first request that uses it. API-key create
responses include a one-time secret_key, so on those operations a key and its encrypted replay response
live 5 minutes.
255Path Parameters
Body
Optional list of source IPs allowed to authenticate with this key. Each entry is a CIDR block (e.g. 203.0.113.0/24) or a bare IPv4/IPv6 address (stored as a /32 or /128). Entries are canonicalized (host bits are masked) and de-duplicated. The allow-all prefixes 0.0.0.0/0 and ::/0 are rejected, and at most 100 entries are allowed after de-duplication. Omit the field or pass an empty array to leave the key usable from any IP.
Response
Sub-account API key created successfully
Source IPs allowed to authenticate with this API key, as canonical CIDR blocks (a bare address is stored as a /32 for IPv4 or /128 for IPv6). Always present; an empty array means the key may be used from any source IP. When non-empty, an authenticated request whose client IP is not covered by an entry is rejected with HTTP 403 on every v2 endpoint, regardless of the key's scopes.

