v2

package module
v2.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2025 License: MIT Imports: 16 Imported by: 0

README

github.com/unkeyed/sdks/go/api

Developer-friendly & type-safe Go SDK specifically catered to leverage github.com/unkeyed/sdks/go/api API.

Summary

Unkey API: Unkey's API provides programmatic access for all resources within our platform.

Authentication

This API uses HTTP Bearer authentication with root keys. Most endpoints require specific permissions associated with your root key. When making requests, include your root key in the Authorization header:

Authorization: Bearer unkey_xxxxxxxxxxx

All responses follow a consistent envelope structure that separates operational metadata from actual data. This design provides several benefits:

  • Debugging: Every response includes a unique requestId for tracing issues
  • Consistency: Predictable response format across all endpoints
  • Extensibility: Easy to add new metadata without breaking existing integrations
  • Error Handling: Unified error format with actionable information
Success Response Format:
{
  "meta": {
    "requestId": "req_123456"
  },
  "data": {
    // Actual response data here
  }
}

The meta object contains operational information:

  • requestId: Unique identifier for this request (essential for support)

The data object contains the actual response data specific to each endpoint.

Paginated Response Format:
{
  "meta": {
    "requestId": "req_123456"
  },
  "data": [
    // Array of results
  ],
  "pagination": {
    "cursor": "next_page_token",
    "hasMore": true
  }
}

The pagination object appears on list endpoints and contains:

  • cursor: Token for requesting the next page
  • hasMore: Whether more results are available
Error Response Format:
{
  "meta": {
    "requestId": "req_2c9a0jf23l4k567"
  },
  "error": {
    "detail": "The resource you are attempting to modify is protected and cannot be changed",
    "status": 403,
    "title": "Forbidden",
    "type": "https://unkey.com/docs/errors/unkey/application/protected_resource"
  }
}

Error responses include comprehensive diagnostic information:

  • title: Human-readable error summary
  • detail: Specific description of what went wrong
  • status: HTTP status code
  • type: Link to error documentation
  • errors: Array of validation errors (for 400 responses)

This structure ensures you always have the context needed to debug issues and take corrective action.

Table of Contents

SDK Installation

To add the SDK as a dependency to your project:

go get github.com/unkeyed/sdks/api/go/v2

SDK Example Usage

Example
package main

import (
	"context"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Apis.CreateAPI(ctx, components.V2ApisCreateAPIRequestBody{
		Name: "payment-service-production",
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.V2ApisCreateAPIResponseBody != nil {
		// handle response
	}
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
RootKey http HTTP Bearer UNKEY_ROOT_KEY

You can configure it using the WithSecurity option when initializing the SDK client instance. For example:

package main

import (
	"context"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Apis.CreateAPI(ctx, components.V2ApisCreateAPIRequestBody{
		Name: "payment-service-production",
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.V2ApisCreateAPIResponseBody != nil {
		// handle response
	}
}

Available Resources and Operations

Available methods
Apis
Identities
Keys
Permissions
Ratelimit

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a Next method that can be called to pull down the next group of results. If the return value of Next is nil, then there are no more pages to be fetched.

Here's an example of one such pagination call:

package main

import (
	"context"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Identities.ListIdentities(ctx, components.V2IdentitiesListIdentitiesRequestBody{
		Limit: unkey.Pointer[int64](50),
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.V2IdentitiesListIdentitiesResponseBody != nil {
		for {
			// handle items

			res, err = res.Next()

			if err != nil {
				// handle error
			}

			if res == nil {
				break
			}
		}
	}
}

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retry.Config object to the call by using the WithRetries option:

package main

import (
	"context"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"github.com/unkeyed/sdks/api/go/v2/retry"
	"log"
	"models/operations"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Apis.CreateAPI(ctx, components.V2ApisCreateAPIRequestBody{
		Name: "payment-service-production",
	}, operations.WithRetries(
		retry.Config{
			Strategy: "backoff",
			Backoff: &retry.BackoffStrategy{
				InitialInterval: 1,
				MaxInterval:     50,
				Exponent:        1.1,
				MaxElapsedTime:  100,
			},
			RetryConnectionErrors: false,
		}))
	if err != nil {
		log.Fatal(err)
	}
	if res.V2ApisCreateAPIResponseBody != nil {
		// handle response
	}
}

If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:

package main

import (
	"context"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"github.com/unkeyed/sdks/api/go/v2/retry"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithRetryConfig(
			retry.Config{
				Strategy: "backoff",
				Backoff: &retry.BackoffStrategy{
					InitialInterval: 1,
					MaxInterval:     50,
					Exponent:        1.1,
					MaxElapsedTime:  100,
				},
				RetryConnectionErrors: false,
			}),
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Apis.CreateAPI(ctx, components.V2ApisCreateAPIRequestBody{
		Name: "payment-service-production",
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.V2ApisCreateAPIResponseBody != nil {
		// handle response
	}
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.

By Default, an API error will return apierrors.APIError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.

For example, the CreateAPI function may return the following errors:

Error Type Status Code Content Type
apierrors.BadRequestErrorResponse 400 application/json
apierrors.UnauthorizedErrorResponse 401 application/json
apierrors.ForbiddenErrorResponse 403 application/json
apierrors.InternalServerErrorResponse 500 application/json
apierrors.APIError 4XX, 5XX */*
Example
package main

import (
	"context"
	"errors"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/apierrors"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Apis.CreateAPI(ctx, components.V2ApisCreateAPIRequestBody{
		Name: "payment-service-production",
	})
	if err != nil {

		var e *apierrors.BadRequestErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.UnauthorizedErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.ForbiddenErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.InternalServerErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.APIError
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}
	}
}

Server Selection

Override Server URL Per-Client

The default server can be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:

package main

import (
	"context"
	unkey "github.com/unkeyed/sdks/api/go/v2"
	"github.com/unkeyed/sdks/api/go/v2/models/components"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := unkey.New(
		unkey.WithServerURL("https://api.unkey.com"),
		unkey.WithSecurity(os.Getenv("UNKEY_ROOT_KEY")),
	)

	res, err := s.Apis.CreateAPI(ctx, components.V2ApisCreateAPIRequestBody{
		Name: "payment-service-production",
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.V2ApisCreateAPIResponseBody != nil {
		// handle response
	}
}

Custom HTTP Client

The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.

import (
	"net/http"
	"time"

	"github.com/unkeyed/sdks/api/go/v2"
)

var (
	httpClient = &http.Client{Timeout: 30 * time.Second}
	sdkClient  = unkey.New(unkey.WithClient(httpClient))
)

This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerList = []string{
	"https://api.unkey.com",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func Pointer

func Pointer[T any](v T) *T

Pointer provides a helper function to return a pointer to a type

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type Apis

type Apis struct {
	// contains filtered or unexported fields
}

Apis - API management operations

func (*Apis) CreateAPI

CreateAPI - Create API namespace Create an API namespace for organizing keys by environment, service, or product.

Use this to separate production from development keys, isolate different services, or manage multiple products. Each API gets a unique identifier and dedicated infrastructure for secure key operations.

**Important**: API names must be unique within your workspace and cannot be changed after creation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.create_api` (to create APIs in any workspace)

func (*Apis) DeleteAPI

DeleteAPI - Delete API namespace Permanently delete an API namespace and immediately invalidate all associated keys.

Use this for cleaning up development environments, retiring deprecated services, or removing unused resources. All keys in the namespace are immediately marked as deleted and will fail verification with `code=NOT_FOUND`.

**Important**: This operation is immediate and permanent. Verify you have the correct API ID before deletion. If delete protection is enabled, disable it first through the dashboard or API configuration.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.delete_api` (to delete any API) - `api.<api_id>.delete_api` (to delete a specific API)

func (*Apis) GetAPI

GetAPI - Get API namespace Retrieve basic information about an API namespace including its ID and name.

Use this to verify an API exists before performing operations, get the human-readable name when you only have the API ID, or confirm access to a specific namespace. For detailed key information, use the `listKeys` endpoint instead.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.read_api` (to read any API) - `api.<api_id>.read_api` (to read a specific API)

func (*Apis) ListKeys

ListKeys - List API keys Retrieve a paginated list of API keys for dashboard and administrative interfaces.

Use this to build key management dashboards, filter keys by user with `externalId`, or retrieve key details for administrative purposes. Each key includes status, metadata, permissions, and usage limits.

**Important**: Set `decrypt: true` only in secure contexts to retrieve plaintext key values from recoverable keys.

**Required Permissions**

Your root key must have one of the following permissions for basic key listing: - `api.*.read_key` (to read keys from any API) - `api.<api_id>.read_key` (to read keys from a specific API)

Additionally, you need read access to the API itself: - `api.*.read_api` or `api.<api_id>.read_api`

Additional permission required for decrypt functionality: - `api.*.decrypt_key` or `api.<api_id>.decrypt_key`

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for supplying the SDK with a custom HTTP client

type Identities

type Identities struct {
	// contains filtered or unexported fields
}

Identities - Identity management operations

func (*Identities) CreateIdentity

CreateIdentity - Create Identity Create an identity to group multiple API keys under a single entity. Identities enable shared rate limits and metadata across all associated keys.

Perfect for users with multiple devices, organizations with multiple API keys, or when you need unified rate limiting across different services.

**Important** Requires `identity.*.create_identity` permission

func (*Identities) DeleteIdentity

DeleteIdentity - Delete Identity Permanently delete an identity. This operation cannot be undone.

Use this for data cleanup, compliance requirements, or when removing entities from your system.

> **Important** > Requires `identity.*.delete_identity` permission > Associated API keys remain functional but lose shared resources > External ID becomes available for reuse immediately

func (*Identities) GetIdentity

GetIdentity - Get Identity Retrieve an identity by external ID. Returns metadata, rate limits, and other associated data.

Use this to check if an identity exists, view configurations, or build management dashboards.

> **Important** > Requires `identity.*.read_identity` permission

func (*Identities) ListIdentities

ListIdentities - List Identities Get a paginated list of all identities in your workspace. Returns metadata and rate limit configurations.

Perfect for building management dashboards, auditing configurations, or browsing your identities.

> **Important** > Requires `identity.*.read_identity` permission

func (*Identities) UpdateIdentity

UpdateIdentity - Update Identity Update an identity's metadata and rate limits. Only specified fields are modified - others remain unchanged.

Perfect for subscription changes, plan upgrades, or updating user information. Changes take effect immediately.

> **Important** > Requires `identity.*.update_identity` permission > Rate limit changes propagate within 30 seconds

type Keys

type Keys struct {
	// contains filtered or unexported fields
}

Keys - API key management operations

func (*Keys) AddPermissions

AddPermissions - Add key permissions Add permissions to a key without affecting existing permissions.

Use this for privilege upgrades, enabling new features, or plan changes that grant additional capabilities. Permissions granted through roles remain unchanged.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes permissions available for verification within 30 seconds across all regions.

func (*Keys) AddRoles

AddRoles - Add key roles Add roles to a key without affecting existing roles or permissions.

Use this for privilege upgrades, enabling new feature sets, or subscription changes that grant additional role-based capabilities. Direct permissions remain unchanged.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes role assignments available for verification within 30 seconds across all regions.

func (*Keys) CreateKey

CreateKey - Create API key Create a new API key for user authentication and authorization.

Use this endpoint when users sign up, upgrade subscription tiers, or need additional keys. Keys are cryptographically secure and unique to the specified API namespace.

**Important**: The key is returned only once. Store it immediately and provide it to your user, as it cannot be retrieved later.

**Common use cases:** - Generate keys for new user registrations - Create additional keys for different applications - Issue keys with specific permissions or limits

**Required Permissions**

Your root key needs one of: - `api.*.create_key` (create keys in any API) - `api.<api_id>.create_key` (create keys in specific API)

func (*Keys) DeleteKey

DeleteKey - Delete API keys Delete API keys permanently from user accounts or for cleanup purposes.

Use this for user-requested key deletion, account deletion workflows, or cleaning up unused keys. Keys are immediately invalidated. Two modes: soft delete (default, preserves audit records) and permanent delete.

**Important**: For temporary access control, use `updateKey` with `enabled: false` instead of deletion.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.delete_key` (to delete keys in any API) - `api.<api_id>.delete_key` (to delete keys in a specific API)

func (*Keys) GetKey

GetKey - Get API key Retrieve detailed key information for dashboard interfaces and administrative purposes.

Use this to build key management dashboards showing users their key details, status, permissions, and usage data. You can identify keys by `keyId` or the actual key string.

**Important**: Set `decrypt: true` only in secure contexts to retrieve plaintext key values from recoverable keys.

**Required Permissions**

Your root key must have one of the following permissions for basic key information: - `api.*.read_key` (to read keys from any API) - `api.<api_id>.read_key` (to read keys from a specific API)

Additional permission required for decrypt functionality: - `api.*.decrypt_key` or `api.<api_id>.decrypt_key`

func (*Keys) RemovePermissions

RemovePermissions - Remove key permissions Remove permissions from a key without affecting existing roles or other permissions.

Use this for privilege downgrades, removing temporary access, or plan changes that revoke specific capabilities. Permissions granted through roles remain unchanged.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes permission changes available for verification within 30 seconds across all regions.

func (*Keys) RemoveRoles

RemoveRoles - Remove key roles Remove roles from a key without affecting direct permissions or other roles.

Use this for privilege downgrades, removing temporary access, or subscription changes that revoke specific role-based capabilities. Direct permissions remain unchanged.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes role changes available for verification within 30 seconds across all regions.

func (*Keys) RerollKey added in v2.0.2

RerollKey - Reroll Key Generate a new API key while preserving the configuration from an existing key.

This operation creates a fresh key with a new token while maintaining all settings from the original key: - Permissions and roles - Custom metadata - Rate limit configurations - Identity associations - Remaining credits - Recovery settings

**Key Generation:** - The system attempts to extract the prefix from the original key - If prefix extraction fails, the default API prefix is used - Key length follows the API's default byte configuration (or 16 bytes if not specified)

**Original Key Handling:** - The original key will be revoked after the duration specified in `expiration` - Set `expiration` to 0 to revoke immediately - This allows for graceful key rotation with an overlap period

Common use cases include: - Rotating keys for security compliance - Issuing replacement keys for compromised credentials - Creating backup keys with identical permissions

**Important:** Analytics and usage metrics are tracked at both the key level AND identity level. If the original key has an identity, the new key will inherit it, allowing you to track usage across both individual keys and the overall identity.

**Required Permissions**

Your root key must have:
- `api.*.create_key` or `api.<api_id>.create_key`
- `api.*.encrypt_key` or `api.<api_id>.encrypt_key` (only when the original key is recoverable)

func (*Keys) SetPermissions

SetPermissions - Set key permissions Replace all permissions on a key with the specified set in a single atomic operation.

Use this to synchronize with external systems, reset permissions to a known state, or apply standardized permission templates. Permissions granted through roles remain unchanged.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes permission changes available for verification within 30 seconds across all regions.

func (*Keys) SetRoles

SetRoles - Set key roles Replace all roles on a key with the specified set in a single atomic operation.

Use this to synchronize with external systems, reset roles to a known state, or apply standardized role templates. Direct permissions are never affected.

**Important**: Changes take effect immediately with up to 30-second edge propagation.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Invalidates the key cache for immediate effect, and makes role changes available for verification within 30 seconds across all regions.

func (*Keys) UpdateCredits

UpdateCredits - Update key credits Update credit quotas in response to plan changes, billing cycles, or usage purchases.

Use this for user upgrades/downgrades, monthly quota resets, credit purchases, or promotional bonuses. Supports three operations: set, increment, or decrement credits. Set to null for unlimited usage.

**Important**: Setting unlimited credits automatically clears existing refill configurations.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

Credit updates remove the key from cache immediately. Setting credits to unlimited automatically clears any existing refill settings. Changes take effect instantly but may take up to 30 seconds to propagate to all edge regions.

func (*Keys) UpdateKey

UpdateKey - Update key settings Update key properties in response to plan changes, subscription updates, or account status changes.

Use this for user upgrades/downgrades, role modifications, or administrative changes. Supports partial updates - only specify fields you want to change. Set fields to null to clear them.

**Important**: Permissions and roles are replaced entirely. Use dedicated add/remove endpoints for incremental changes.

**Required Permissions**

Your root key must have one of the following permissions: - `api.*.update_key` (to update keys in any API) - `api.<api_id>.update_key` (to update keys in a specific API)

**Side Effects**

If you specify an `externalId` that doesn't exist, a new identity will be automatically created and linked to the key. Permission updates will auto-create any permissions that don't exist in your workspace. Changes take effect immediately but may take up to 30 seconds to propagate to all edge regions due to cache invalidation.

func (*Keys) VerifyKey

VerifyKey - Verify API key Verify an API key's validity and permissions for request authentication.

Use this endpoint on every incoming request to your protected resources. It checks key validity, permissions, rate limits, and usage quotas in a single call.

**Important**: Always returns HTTP 200. Check the `valid` field in response data to determine if the key is authorized.

**Common use cases:** - Authenticate API requests before processing - Enforce permission-based access control - Track usage and apply rate limits

**Required Permissions**

Your root key needs one of: - `api.*.verify_key` (verify keys in any API) - `api.<api_id>.verify_key` (verify keys in specific API)

If you are getting a NOT_FOUND error, ensure your root key has the required verify key permissions.

func (*Keys) Whoami

Whoami - Get API key by hash Find out what key this is.

**Required Permissions**

Your root key must have one of the following permissions for basic key information: - `api.*.read_key` (to read keys from any API) - `api.<api_id>.read_key` (to read keys from a specific API)

If your rootkey lacks permissions but the key exists, we may return a 404 status here to prevent leaking the existance of a key to unauthorized clients. If you believe that a key should exist, but receive a 404, please double check your root key has the correct permissions.

type Permissions

type Permissions struct {
	// contains filtered or unexported fields
}

Permissions - Permission and role management operations

func (*Permissions) CreatePermission

CreatePermission - Create permission Create a new permission to define specific actions or capabilities in your RBAC system. Permissions can be assigned directly to API keys or included in roles.

Use hierarchical naming patterns like `documents.read`, `admin.users.delete`, or `billing.invoices.create` for clear organization.

**Important:** Permission names must be unique within the workspace. Once created, permissions are immediately available for assignment.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.create_permission`

func (*Permissions) CreateRole

CreateRole - Create role Create a new role to group related permissions for easier management. Roles enable consistent permission assignment across multiple API keys.

**Important:** Role names must be unique within the workspace. Once created, roles are immediately available for assignment.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.create_role`

func (*Permissions) DeletePermission

DeletePermission - Delete permission Remove a permission from your workspace. This also removes the permission from all API keys and roles.

**Important:** This operation cannot be undone and immediately affects all API keys and roles that had this permission assigned.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.delete_permission`

func (*Permissions) DeleteRole

DeleteRole - Delete role Remove a role from your workspace. This also removes the role from all assigned API keys.

**Important:** This operation cannot be undone and immediately affects all API keys that had this role assigned.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.delete_role`

func (*Permissions) GetPermission

GetPermission - Get permission Retrieve details about a specific permission including its name, description, and metadata.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.read_permission`

func (*Permissions) GetRole

GetRole - Get role Retrieve details about a specific role including its assigned permissions.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.read_role`

func (*Permissions) ListPermissions

ListPermissions - List permissions Retrieve all permissions in your workspace. Results are paginated and sorted by their id.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.read_permission`

func (*Permissions) ListRoles

ListRoles - List roles Retrieve all roles in your workspace including their assigned permissions. Results are paginated and sorted by their id.

**Required Permissions**

Your root key must have the following permission: - `rbac.*.read_role`

type Ratelimit

type Ratelimit struct {
	// contains filtered or unexported fields
}

Ratelimit - Rate limiting operations

func (*Ratelimit) DeleteOverride

DeleteOverride - Delete ratelimit override Permanently remove a rate limit override. Affected identifiers immediately revert to the namespace default.

Use this to remove temporary overrides, reset identifiers to standard limits, or clean up outdated rules.

**Important:** Deletion is immediate and permanent. The override cannot be recovered and must be recreated if needed again.

**Permissions:** Requires `ratelimit.*.delete_override` or `ratelimit.<namespace_id>.delete_override`

func (*Ratelimit) GetOverride

GetOverride - Get ratelimit override Retrieve the configuration of a specific rate limit override by its identifier.

Use this to inspect override configurations, audit rate limiting policies, or debug rate limiting behavior.

**Important:** The identifier must match exactly as specified when creating the override, including wildcard patterns.

**Permissions:** Requires `ratelimit.*.read_override` or `ratelimit.<namespace_id>.read_override`

func (*Ratelimit) Limit

Limit - Apply rate limiting Check and enforce rate limits for any identifier (user ID, IP address, API client, etc.).

Use this for rate limiting beyond API keys - limit users by ID, IPs by address, or any custom identifier. Supports namespace organization, variable costs, and custom overrides.

**Response Codes**: Rate limit checks return HTTP 200 regardless of whether the limit is exceeded - check the `success` field in the response to determine if the request should be allowed. 4xx responses indicate auth, namespace existence/deletion, or validation errors (e.g., 410 Gone for deleted namespaces). 5xx responses indicate server errors.

**Required Permissions**

Your root key must have one of the following permissions: - `ratelimit.*.limit` (to check limits in any namespace) - `ratelimit.<namespace_id>.limit` (to check limits in a specific namespace)

**Side Effects**

Records rate limit metrics for analytics and monitoring, updates rate limit counters with sliding window algorithm, and optionally triggers override matching for custom limits.

func (*Ratelimit) ListOverrides

ListOverrides - List ratelimit overrides Retrieve a paginated list of all rate limit overrides in a namespace.

Use this to audit rate limiting policies, build admin dashboards, or manage override configurations.

**Important:** Results are paginated. Use the cursor parameter to retrieve additional pages when more results are available.

**Permissions:** Requires `ratelimit.*.read_override` or `ratelimit.<namespace_id>.read_override`

func (*Ratelimit) SetOverride

SetOverride - Set ratelimit override Create or update a custom rate limit for specific identifiers, bypassing the namespace default.

Use this to create premium tiers with higher limits, apply stricter limits to specific users, or implement emergency throttling.

**Important:** Overrides take effect immediately and completely replace the default limit for matching identifiers. Use wildcard patterns (e.g., `premium_*`) to match multiple identifiers.

**Permissions:** Requires `ratelimit.*.set_override` or `ratelimit.<namespace_id>.set_override`

type SDKOption

type SDKOption func(*Unkey)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithRetryConfig

func WithRetryConfig(retryConfig retry.Config) SDKOption

func WithSecurity

func WithSecurity(rootKey string) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource

func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServerIndex

func WithServerIndex(serverIndex int) SDKOption

WithServerIndex allows the overriding of the default server by index

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows the overriding of the default server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

func WithTimeout

func WithTimeout(timeout time.Duration) SDKOption

WithTimeout Optional request timeout applied to each operation

type Unkey

type Unkey struct {
	SDKVersion string
	// API management operations
	Apis *Apis
	// Identity management operations
	Identities *Identities
	// API key management operations
	Keys *Keys
	// Permission and role management operations
	Permissions *Permissions
	// Rate limiting operations
	Ratelimit *Ratelimit
	// contains filtered or unexported fields
}

Unkey API: Unkey's API provides programmatic access for all resources within our platform.

### Authentication # This API uses HTTP Bearer authentication with root keys. Most endpoints require specific permissions associated with your root key. When making requests, include your root key in the `Authorization` header: ``` Authorization: Bearer unkey_xxxxxxxxxxx ```

All responses follow a consistent envelope structure that separates operational metadata from actual data. This design provides several benefits: - Debugging: Every response includes a unique requestId for tracing issues - Consistency: Predictable response format across all endpoints - Extensibility: Easy to add new metadata without breaking existing integrations - Error Handling: Unified error format with actionable information

### Success Response Format: ```json

{
  "meta": {
    "requestId": "req_123456"
  },
  "data": {
    // Actual response data here
  }
}

```

The meta object contains operational information: - `requestId`: Unique identifier for this request (essential for support)

The data object contains the actual response data specific to each endpoint.

### Paginated Response Format: ```json

{
  "meta": {
    "requestId": "req_123456"
  },
  "data": [
    // Array of results
  ],
  "pagination": {
    "cursor": "next_page_token",
    "hasMore": true
  }
}

```

The pagination object appears on list endpoints and contains: - `cursor`: Token for requesting the next page - `hasMore`: Whether more results are available

### Error Response Format: ```json

{
  "meta": {
    "requestId": "req_2c9a0jf23l4k567"
  },
  "error": {
    "detail": "The resource you are attempting to modify is protected and cannot be changed",
    "status": 403,
    "title": "Forbidden",
    "type": "https://unkey.com/docs/errors/unkey/application/protected_resource"
  }
}

```

Error responses include comprehensive diagnostic information: - `title`: Human-readable error summary - `detail`: Specific description of what went wrong - `status`: HTTP status code - `type`: Link to error documentation - `errors`: Array of validation errors (for 400 responses)

This structure ensures you always have the context needed to debug issues and take corrective action.

func New

func New(opts ...SDKOption) *Unkey

New creates a new instance of the SDK with the provided options

Directories

Path Synopsis
internal
models

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL