NetStacksNetStacks

API Tokens

TeamsEnterprise

Create, manage, and use API tokens for programmatic access to the NetStacks REST API with expiration policies and audit logging.

Overview

API tokens provide programmatic access to the NetStacks Controller REST API. They are designed for automation scripts, CI/CD pipelines, third-party integrations, and any use case where a human is not present to perform interactive login.

Unlike JWT session tokens (which are short-lived and tied to a browser session), API tokens are long-lived bearer tokens that persist until they expire or are revoked. Each token is associated with a user account and inherits that user's role-based permissions, so an API token can only do what its owning user is allowed to do.

  • Long-lived bearer tokens for automation and integrations
  • Shown once on creation — stored as a cryptographic hash in the database
  • Configurable expiration dates
  • Inherits the creating user's role-based permissions
  • Full audit logging for every API call made with the token
  • Instant revocation without affecting other tokens or sessions

How It Works

Token Generation and Storage

When you create an API token, the Controller generates a cryptographically random token string and returns it in the response. The raw token is shown exactly once. The Controller stores only a cryptographic hash (SHA-256) of the token in the database — if the database is compromised, the hashed values cannot be used to reconstruct the original tokens.

Copy your token immediately

The raw token value is displayed only once during creation. If you lose it, you must create a new token. There is no way to retrieve or recover a token after the creation dialog is closed.

Expiration Policies

Every API token has an optional expiration date. When a token expires, all API calls using it will return a 401 Unauthorized response. You can set expiration dates during creation or leave the token as non-expiring (not recommended for production). Best practice is to set an expiration and rotate tokens regularly.

Permissions and Scope

API tokens inherit the role-based permissions of the user who created them. If a user has the "Network Operator" role, their API token can perform the same actions as that user through the UI. When a user's role changes, the permissions of their existing tokens change accordingly.

Rate Limiting

API requests made with tokens are subject to the same rate limits as regular authenticated requests. The Controller tracks request counts per token and returns 429 Too Many Requests when the limit is exceeded. Rate limits reset on a rolling window.

Step-by-Step Guide

Step 1: Create an API Token via the Admin UI

  1. Navigate to Administration → API Tokens
  2. Click Create Token
  3. Enter a descriptive name (e.g., "Config Backup Script — DC1")
  4. Optionally add a description explaining the token's purpose
  5. Click Create
  6. Copy the displayed token immediately — it will not be shown again

Step 2: Set an Expiration Date

  1. During token creation, click Set Expiration
  2. Select an expiration date (e.g., 90 days from now)
  3. The token will automatically stop working after this date
  4. Set a calendar reminder to rotate the token before expiration
Tip

For production automation, set expiration dates of 90 days and rotate tokens quarterly. For temporary integrations or testing, use 7-day or 30-day expirations.

Step 3: Use the Token in API Requests

Include the token in the Authorization header as a Bearer token:

use-token.shbash
curl https://controller.example.net/api/devices \
  -H "Authorization: Bearer ns_tok_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"

Step 4: Revoke a Token

  1. Navigate to Administration → API Tokens
  2. Find the token by name
  3. Click Revoke and confirm
  4. The token is immediately invalidated — all subsequent API calls with it will fail

Step 5: View Token Usage and Audit Logs

  1. Navigate to Administration → Audit Logs
  2. Filter by the token name or the associated user
  3. Review which API endpoints were called, when, and from which IP address
  4. Use this data to verify automation is working as expected

Code Examples

Using an API Token with curl

curl-examples.shbash
# List all devices
curl https://controller.example.net/api/devices \
  -H "Authorization: Bearer ${NETSTACKS_TOKEN}"

# Get a specific device
curl https://controller.example.net/api/devices/f7e8d9c0-b1a2-3456-7890-abcdef123456 \
  -H "Authorization: Bearer ${NETSTACKS_TOKEN}"

# Trigger a config backup for a device
curl -X POST https://controller.example.net/api/devices/f7e8d9c0-b1a2-3456-7890-abcdef123456/backup \
  -H "Authorization: Bearer ${NETSTACKS_TOKEN}"

Using an API Token in Python

netstacks_api.pypython
import requests

CONTROLLER_URL = "https://controller.example.net"
API_TOKEN = "ns_tok_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"

headers = {
    "Authorization": f"Bearer {API_TOKEN}",
    "Content-Type": "application/json",
}

# List all devices
response = requests.get(f"{CONTROLLER_URL}/api/devices", headers=headers)
devices = response.json()

for device in devices["devices"]:
    print(f"{device['hostname']} - {device['ip_address']} - {device['device_type']}")

# Create a new device
new_device = {
    "hostname": "dist-sw-05.dc2.example.net",
    "ip_address": "10.2.1.5",
    "device_type": "cisco_ios_xe",
    "credential_id": "f7e8d9c0-b1a2-3456-7890-abcdef123456",
    "port": 22,
}
response = requests.post(f"{CONTROLLER_URL}/api/devices", json=new_device, headers=headers)
print(f"Created device: {response.json()['id']}")

Using an API Token in TypeScript

netstacks-client.tstypescript
const CONTROLLER_URL = "https://controller.example.net";
const API_TOKEN = process.env.NETSTACKS_TOKEN;

async function listDevices() {
  const response = await fetch(`${CONTROLLER_URL}/api/devices`, {
    headers: {
      Authorization: `Bearer ${API_TOKEN}`,
    },
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status} ${response.statusText}`);
  }

  const data = await response.json();
  return data.devices;
}

async function backupDevice(deviceId: string) {
  const response = await fetch(
    `${CONTROLLER_URL}/api/devices/${deviceId}/backup`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${API_TOKEN}`,
      },
    }
  );

  return response.json();
}

Questions & Answers

Q: How do I create an API token?
A: Navigate to Administration → API Tokens in the Admin UI, click Create Token, enter a name, and click Create. The token is displayed once — copy it immediately. You can also create tokens via the API if you already have an authenticated session.
Q: How do I use an API token in API calls?
A: Include the token in the Authorization header as a Bearer token: Authorization: Bearer ns_tok_your_token_here. This works with curl, Python requests, TypeScript fetch, or any HTTP client.
Q: What permissions does an API token have?
A: An API token inherits the role-based permissions of the user who created it. If the user is a Network Operator, the token can perform Network Operator actions. If the user's role is changed or revoked, the token's effective permissions change accordingly.
Q: How do I set an expiration on a token?
A: Set an expiration date during token creation. After the expiration date, all API calls using the token will return 401 Unauthorized. Recommended expiration periods are 90 days for production automation and 7–30 days for testing.
Q: What happens when a token expires?
A: The token immediately stops working. All API calls using it will receive a 401 Unauthorized response. Create a new token and update your automation scripts or integrations with the new value.
Q: Can I have multiple API tokens?
A: Yes. Each user can create multiple tokens for different purposes. This is recommended — use separate tokens for separate integrations so you can revoke one without affecting others. For example, use one token for config backup scripts and another for a monitoring integration.

Troubleshooting

Token rejected (401 Unauthorized)

If your API call returns 401:

  • Verify the token has not expired — check the expiration date in the Admin UI
  • Confirm the token has not been revoked
  • Check the Authorization header format: it must be Bearer <token> with a space between "Bearer" and the token value
  • Ensure there are no extra whitespace characters or newlines in the token string
verify-token.shbash
# Verify your token is working
curl -s -o /dev/null -w "%{http_code}" \
  https://controller.example.net/api/health \
  -H "Authorization: Bearer ${NETSTACKS_TOKEN}"
# Expected: 200

Rate limit exceeded (429 Too Many Requests)

If you receive 429 responses, your automation is sending too many requests in a short period:

  • Add delays between API calls in your scripts
  • Check the Retry-After header for when you can retry
  • Batch operations where possible instead of making many individual calls
  • Contact your administrator to adjust rate limits if needed for legitimate automation

Insufficient permissions (403 Forbidden)

If the token returns 403 for a specific endpoint:

  • The token inherits its user's permissions — check the user's role
  • Verify the user has the required role for the action (e.g., admin-level actions require an admin role)
  • Create the token with a user that has the appropriate permissions

Learn more about API access and authentication:

  • API Authentication — Complete guide to REST API authentication methods including JWT and tokens
  • Credential Vault — How all secrets including token hashes are stored securely
  • User Management — Manage users whose roles determine API token permissions
  • Roles & Permissions — Understand the role-based permissions that tokens inherit
  • Audit Logs — Review all API calls made with tokens for compliance tracking