# Management API

Create customer keys, manage partner domains and retry Management API writes safely

Source: https://zerocopy.sh/docs/account/management-api

Use the Management API to manage your team's own and customer API keys, read usage and
configure partner domains without a console session. Create a
[management key](/docs/api-keys#management-keys), then send it in
`Authorization: Bearer YOUR_MANAGEMENT_KEY` to the console's origin.
An SWQoS API key cannot authenticate these requests.

The [Management API reference](/docs/reference/management-api) lists exact endpoints,
request fields, response fields and errors. The console also publishes its schema
at [`/api/v1/openapi.json`](https://console.zerocopy.sh/api/v1/openapi.json).

## Scopes [#scopes]

| Scope | Access |
| --- | --- |
| `partner:read` | Read partner settings, tip accounts, domains, customer keys and customer usage |
| `partner:write` | Manage domains and create, update, revoke, pause or resume customer keys |
| `keys:read` | Read your team's own API keys |
| `keys:write` | Create, update and revoke your team's own API keys |
| `usage:read` | Read key statistics, transactions and [metrics](/docs/account/metrics-api) |

Grant the scopes each integration needs. `partner:write` does not grant
`partner:read`. Existing management keys keep their assigned scopes; create a new key
if an integration needs additional access. In the console, all team roles can read
partner details; admins and developers can manage domains.

## Partner operations [#partner-operations]

Partner operations require an enrolled [white label team](/docs/account/white-label).
A nonpartner receives 404. Use the
[partner endpoint reference](/docs/reference/management-api#white-label) for the available
operations.

After enrollment, your own keys keep using company tip accounts. Choose a prefix in
[White label > Tip accounts](/docs/account/white-label#custom-prefix) for exactly eight
vanity accounts, then wait for approval. You can configure domains while waiting.
Customer keys can only be created after all eight accounts are live, when your
team's own and customer keys switch to the vanity set.

`GET /api/v1/partner` reports `tip_account_count` for all assigned accounts and
`live_tip_account_count` for live accounts. `GET /api/v1/partner/tip-accounts`
returns each account's `address` and `status`; pending accounts cannot accept tips.

Before sending transactions, call [`getTipAccounts`](/docs/reference/json-rpc/tip-accounts)
with the key that will send them. Use the returned accounts.

### Customer keys [#customer-keys]

After the vanity accounts are live, [create a customer key](/docs/reference/management-api/create-a-customer-key)
with `partner:write`. Set `KEY_REQUEST_ID` to an idempotency key for this creation
attempt and reuse it with the same body when retrying.

```rust title="src/bin/create_customer_key.rs" tab="Rust" tab-group="language"
use serde_json::{Value, json};
use swqos_examples::swqos::{Result, required};

#[tokio::main]
async fn main() -> Result<()> {
    let response = reqwest::Client::new()
        .post("https://console.zerocopy.sh/api/v1/customer-keys")
        .bearer_auth(required("MANAGEMENT_API_KEY")?)
        .header("Idempotency-Key", required("KEY_REQUEST_ID")?)
        .json(&json!({ "name": "Acme primary", "customer_ref": "acme-123" }))
        .send()
        .await?;
    let status = response.status();
    let body = response.text().await?;
    let reply: Value = serde_json::from_str(&body)
        .map_err(|error| format!("HTTP {status}: {error}; body: {body}"))?;
    if !status.is_success() {
        return Err(format!("HTTP {status}: {reply}").into());
    }
    println!("{}", serde_json::to_string_pretty(&reply)?);
    Ok(())
}
```

```go title="create-customer-key/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"

	swqos "swqos-examples"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	apiKey, err := swqos.Required("MANAGEMENT_API_KEY")
	if err != nil {
		return err
	}
	requestID, err := swqos.Required("KEY_REQUEST_ID")
	if err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodPost, "https://console.zerocopy.sh/api/v1/customer-keys",
		strings.NewReader(`{"name":"Acme primary","customer_ref":"acme-123"}`))
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+apiKey)
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Idempotency-Key", requestID)
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	var reply any
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		return fmt.Errorf("HTTP %d: %w", response.StatusCode, err)
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return fmt.Errorf("HTTP %d: %v", response.StatusCode, reply)
	}
	output, err := json.MarshalIndent(reply, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(output))
	return nil
}
```

```ts title="create-customer-key.ts" tab="TypeScript" tab-group="language"
const apiKey = process.env.MANAGEMENT_API_KEY
const requestID = process.env.KEY_REQUEST_ID
if (!apiKey) throw new Error('set MANAGEMENT_API_KEY')
if (!requestID) throw new Error('set KEY_REQUEST_ID')

const response = await fetch('https://console.zerocopy.sh/api/v1/customer-keys', {
  method: 'POST',
  headers: {
    authorization: `Bearer ${apiKey}`,
    'content-type': 'application/json',
    'idempotency-key': requestID,
  },
  body: JSON.stringify({ name: 'Acme primary', customer_ref: 'acme-123' }),
})
const body = await response.text()
let reply: unknown
try {
  reply = JSON.parse(body)
} catch {
  throw new Error(`HTTP ${response.status}: invalid JSON; body: ${body}`)
}
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${JSON.stringify(reply)}`)
}
console.log(JSON.stringify(reply, null, 2))

export {}
```

```sh title="Create a customer key" tab="cURL" tab-group="language"
curl --fail-with-body -sS 'https://console.zerocopy.sh/api/v1/customer-keys' \
  -H "Authorization: Bearer $MANAGEMENT_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $KEY_REQUEST_ID" \
  --data '{"name":"Acme primary","customer_ref":"acme-123"}'
```

The response has HTTP status `201` and contains `{ "key": ..., "secret": ... }`.
Store the secret from this response; later reads return only the key's fields.
Names are trimmed to 1 to 64 characters. An optional `customer_ref` is trimmed
to 1 to 100 characters, or can be null for an unassigned key.
Creation and updates accept only `name` and `customer_ref`. Products, rules,
expiry and send settings cannot be set through these endpoints.

[List customer keys](/docs/reference/management-api/list-customer-keys) with
`customer_ref=acme-123` to select an exact customer reference. Lists accept
`limit` from 1 to 100, defaulting to 50. Pass the returned `next_cursor` as
`cursor` for the next page; null ends the collection.
Own keys stay on the separate [`/keys` endpoints](/docs/reference/management-api/list-api-keys).

To [rename a key or change its customer reference](/docs/reference/management-api/update-a-customer-key),
PATCH `/api/v1/customer-keys/{id}` with the fields to change. Set `customer_ref`
to null to clear it. Read the key's `ETag` from creation or a
[GET response](/docs/reference/management-api/retrieve-a-customer-key), then send it
as `If-Match` to reject a stale update with `412 precondition_failed`.
The same header works for revocation, pause and resume.

[Pause](/docs/reference/management-api/pause-a-customer-key) and
[resume](/docs/reference/management-api/resume-a-customer-key) use bodyless POST
requests to `/api/v1/customer-keys/{id}/pause` and `/resume`. A paused key keeps
its secret and rejects sending requests with `key_paused`. Use a fresh
`Idempotency-Key` for each state change and reuse it for retries. Repeating a
pause on a paused key, or a resume on an active key, returns `400 invalid_request`
without an idempotent replay.

[Revoke a key](/docs/reference/management-api/revoke-a-customer-key) with DELETE
`/api/v1/customer-keys/{id}` to stop it permanently. The response contains the
revoked key. Repeating the request returns its current state; a revoked key
cannot be resumed.

With `partner:read`, read
[per-key statistics](/docs/reference/management-api/retrieve-customer-key-statistics)
or [usage grouped by customer](/docs/reference/management-api/retrieve-customer-usage).
Both accept `range=24h`, `7d` or `30d`, defaulting to `24h`. For example:

```rust title="src/bin/customer_usage.rs" tab="Rust" tab-group="language"
use serde_json::Value;
use swqos_examples::swqos::{Result, required};

#[tokio::main]
async fn main() -> Result<()> {
    let response = reqwest::Client::new()
        .get("https://console.zerocopy.sh/api/v1/customer-keys/usage?range=7d&customer_ref=acme-123")
        .bearer_auth(required("MANAGEMENT_API_KEY")?)
        .send()
        .await?;
    let status = response.status();
    let body = response.text().await?;
    let reply: Value = serde_json::from_str(&body)
        .map_err(|error| format!("HTTP {status}: {error}; body: {body}"))?;
    if !status.is_success() {
        return Err(format!("HTTP {status}: {reply}").into());
    }
    println!("{}", serde_json::to_string_pretty(&reply)?);
    Ok(())
}
```

```go title="customer-usage/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	swqos "swqos-examples"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	apiKey, err := swqos.Required("MANAGEMENT_API_KEY")
	if err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodGet,
		"https://console.zerocopy.sh/api/v1/customer-keys/usage?range=7d&customer_ref=acme-123", nil)
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+apiKey)
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	var reply any
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		return fmt.Errorf("HTTP %d: %w", response.StatusCode, err)
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return fmt.Errorf("HTTP %d: %v", response.StatusCode, reply)
	}
	output, err := json.MarshalIndent(reply, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(output))
	return nil
}
```

```ts title="customer-usage.ts" tab="TypeScript" tab-group="language"
const apiKey = process.env.MANAGEMENT_API_KEY
if (!apiKey) throw new Error('set MANAGEMENT_API_KEY')

const response = await fetch(
  'https://console.zerocopy.sh/api/v1/customer-keys/usage?range=7d&customer_ref=acme-123',
  { headers: { authorization: `Bearer ${apiKey}` } },
)
const body = await response.text()
let reply: unknown
try {
  reply = JSON.parse(body)
} catch {
  throw new Error(`HTTP ${response.status}: invalid JSON; body: ${body}`)
}
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${JSON.stringify(reply)}`)
}
console.log(JSON.stringify(reply, null, 2))

export {}
```

```sh title="Read one customer's weekly usage" tab="cURL" tab-group="language"
curl --fail-with-body -sS \
  'https://console.zerocopy.sh/api/v1/customer-keys/usage?range=7d&customer_ref=acme-123' \
  -H "Authorization: Bearer $MANAGEMENT_API_KEY"
```

Usage returns `{ "window": "7d", "data": [...] }`. Omit `customer_ref` to include
all customer groups; keys without a reference share a null group. `live_keys`
counts currently active keys. Landed rate is a percentage and tips are integer
lamports. `last_seen_at` can precede the selected window.

### Add a domain [#add-domain]

Create a domain using the [domain creation endpoint](/docs/reference/management-api/add-a-domain)
with this JSON body:

```json title="Domain request"
{
  "hostname": "send.partner.example",
  "target": "sol"
}
```

Choose a domain you control and use `sol` for the nearest metro or a supported
[named metro](/docs/swqos/endpoints#regions). See the
[request constraints](/docs/reference/management-api/add-a-domain) for exact domain rules
and target values.

Set `MANAGEMENT_API_KEY` to your management key and `DOMAIN_REQUEST_ID` to an
idempotency key for this creation attempt. Reuse that request ID when retrying.
Rust and Go use the [example project](/docs/reference/json-rpc#example-project);
TypeScript uses `fetch`.

```rust title="src/bin/create_partner_domain.rs" tab="Rust" tab-group="language"
use serde_json::{Value, json};
use swqos_examples::swqos::{Result, required};

#[tokio::main]
async fn main() -> Result<()> {
    let response = reqwest::Client::new()
        .post("https://console.zerocopy.sh/api/v1/domains")
        .bearer_auth(required("MANAGEMENT_API_KEY")?)
        .header("Idempotency-Key", required("DOMAIN_REQUEST_ID")?)
        .json(&json!({ "hostname": "send.partner.example", "target": "sol" }))
        .send()
        .await?;
    let status = response.status();
    let body = response.text().await?;
    let reply: Value = serde_json::from_str(&body)
        .map_err(|error| format!("HTTP {status}: {error}; body: {body}"))?;
    if !status.is_success() {
        return Err(format!("HTTP {status}: {reply}").into());
    }
    println!("{}", serde_json::to_string_pretty(&reply)?);
    Ok(())
}
```

```go title="create-partner-domain/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strings"

	swqos "swqos-examples"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	apiKey, err := swqos.Required("MANAGEMENT_API_KEY")
	if err != nil {
		return err
	}
	requestID, err := swqos.Required("DOMAIN_REQUEST_ID")
	if err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodPost, "https://console.zerocopy.sh/api/v1/domains",
		strings.NewReader(`{"hostname":"send.partner.example","target":"sol"}`))
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+apiKey)
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Idempotency-Key", requestID)
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	var reply any
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		return fmt.Errorf("HTTP %d: %w", response.StatusCode, err)
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return fmt.Errorf("HTTP %d: %v", response.StatusCode, reply)
	}
	output, err := json.MarshalIndent(reply, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(output))
	return nil
}
```

```ts title="create-partner-domain.ts" tab="TypeScript" tab-group="language"
const apiKey = process.env.MANAGEMENT_API_KEY
const requestID = process.env.DOMAIN_REQUEST_ID
if (!apiKey) throw new Error('set MANAGEMENT_API_KEY')
if (!requestID) throw new Error('set DOMAIN_REQUEST_ID')

const response = await fetch('https://console.zerocopy.sh/api/v1/domains', {
  method: 'POST',
  headers: {
    authorization: `Bearer ${apiKey}`,
    'content-type': 'application/json',
    'idempotency-key': requestID,
  },
  body: JSON.stringify({ hostname: 'send.partner.example', target: 'sol' }),
})
const body = await response.text()
let reply: unknown
try {
  reply = JSON.parse(body)
} catch {
  throw new Error(`HTTP ${response.status}: invalid JSON; body: ${body}`)
}
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${JSON.stringify(reply)}`)
}
console.log(JSON.stringify(reply, null, 2))

export {}
```

```sh title="Create a partner domain" tab="cURL" tab-group="language"
curl --fail-with-body -sS 'https://console.zerocopy.sh/api/v1/domains' \
  -H "Authorization: Bearer $MANAGEMENT_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $DOMAIN_REQUEST_ID" \
  --data '{"hostname":"send.partner.example","target":"sol"}'
```

The domain starts in `pending`. [Read its status](/docs/reference/management-api/retrieve-a-domain)
until the DNS challenge is available, then publish the
[two CNAME records](/docs/account/white-label#domains). Keep both records in place for renewal.

```rust title="src/bin/read_domain_setup.rs" tab="Rust" tab-group="language"
use serde_json::Value;
use swqos_examples::swqos::{Result, required};

#[tokio::main]
async fn main() -> Result<()> {
    let response = reqwest::Client::new()
        .get("https://console.zerocopy.sh/api/v1/domains/send.partner.example")
        .bearer_auth(required("MANAGEMENT_API_KEY")?)
        .send()
        .await?;
    let status = response.status();
    let body = response.text().await?;
    let reply: Value = serde_json::from_str(&body)
        .map_err(|error| format!("HTTP {status}: {error}; body: {body}"))?;
    if !status.is_success() {
        return Err(format!("HTTP {status}: {reply}").into());
    }
    println!("{}", serde_json::to_string_pretty(&reply)?);
    Ok(())
}
```

```go title="read-domain-setup/main.go" tab="Go" tab-group="language"
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	swqos "swqos-examples"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	apiKey, err := swqos.Required("MANAGEMENT_API_KEY")
	if err != nil {
		return err
	}
	request, err := http.NewRequest(http.MethodGet,
		"https://console.zerocopy.sh/api/v1/domains/send.partner.example", nil)
	if err != nil {
		return err
	}
	request.Header.Set("Authorization", "Bearer "+apiKey)
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	var reply any
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		return fmt.Errorf("HTTP %d: %w", response.StatusCode, err)
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		return fmt.Errorf("HTTP %d: %v", response.StatusCode, reply)
	}
	output, err := json.MarshalIndent(reply, "", "  ")
	if err != nil {
		return err
	}
	fmt.Println(string(output))
	return nil
}
```

```ts title="read-domain-setup.ts" tab="TypeScript" tab-group="language"
const apiKey = process.env.MANAGEMENT_API_KEY
if (!apiKey) throw new Error('set MANAGEMENT_API_KEY')

const response = await fetch(
  'https://console.zerocopy.sh/api/v1/domains/send.partner.example',
  { headers: { authorization: `Bearer ${apiKey}` } },
)
const body = await response.text()
let reply: unknown
try {
  reply = JSON.parse(body)
} catch {
  throw new Error(`HTTP ${response.status}: invalid JSON; body: ${body}`)
}
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${JSON.stringify(reply)}`)
}
console.log(JSON.stringify(reply, null, 2))

export {}
```

```sh title="Read domain setup" tab="cURL" tab-group="language"
curl --fail-with-body -sS 'https://console.zerocopy.sh/api/v1/domains/send.partner.example' \
  -H "Authorization: Bearer $MANAGEMENT_API_KEY"
```

Check `last_error` when setup or renewal fails and `not_after` for certificate expiry.
Update clients before [removing a domain](/docs/reference/management-api/remove-a-domain).
Adding it again starts a new setup and assigns a new challenge CNAME.

## Idempotent writes [#idempotency]

Send `Idempotency-Key` with customer-key creation, pause, resume and domain creation
requests, then reuse it if you retry after a timeout. Use 1 to 255 printable ASCII
characters. For 24 hours, the same management key, idempotency key and request
return the saved successful response with `Idempotent-Replayed: true`. Refusals are
not saved. A concurrent request or a different request with the same key returns 409.

If the API returns `409 idempotency_unavailable`,
[read the domain](/docs/reference/management-api/retrieve-a-domain) before making a new request.
A saved response can be unavailable even though the original creation succeeded.

For a customer-key request, [list the keys](/docs/reference/management-api/list-customer-keys)
or [read the target key](/docs/reference/management-api/retrieve-a-customer-key) before
starting another operation. If creation succeeded and you cannot recover its
secret, revoke that key before creating a replacement.

## Handling failures [#failures]

Keep the response's `Request-Id` when reporting a failed request on
[Discord](https://discord.gg/zerocopy). Use the stable error `code` rather than matching
message text. See the [response and error reference](/docs/reference/management-api#errors) for
the exact JSON shapes and status codes.
