### Install Unkey Go SDK Source: https://unkey.com/docs/libraries/go/overview Instructions for installing the Unkey Go SDK using the go get command. This is the first step to integrate Unkey functionality into your Go projects. ```bash go get github.com/unkeyed/unkey/sdks/golang ``` -------------------------------- ### Express Server Setup Source: https://unkey.com/docs/quickstart/apis/express Installs dependencies and configures package.json scripts for an Express.js server with TypeScript. ```bash mkdir unkey-with-express npm init -y npm install cors dotenv express ts-node npm install -D @types/cors @types/express ts-node-dev typescript ``` -------------------------------- ### Unkey API GET Request Example Source: https://unkey.com/docs/api-reference/v1/overview Example of making a GET request to the Unkey API to retrieve data, using query parameters for filtering and authentication. ```shell curl "https://api.unkey.dev/v1/keys.getKey?keyId=key_123" \ -H "Authorization: Bearer " ``` -------------------------------- ### Example JSON Response for Analytics Source: https://unkey.com/docs/analytics/quickstarts Illustrates the structure of the JSON response received from the Unkey analytics API, detailing verification outcomes per time interval. ```json [ { "time": 1736672400000, "valid": 15125, "notFound": 0, "forbidden": 0, "usageExceeded": 1225, "rateLimited": 0, "unauthorized": 0, "disabled": 0, "insufficientPermissions": 0, "expired": 0, "total": 16350 }, { "time": 1736676000000, "valid": 765, "notFound": 0, "forbidden": 0, "usageExceeded": 0, "rateLimited": 0, "unauthorized": 0, "disabled": 0, "insufficientPermissions": 0, "expired": 0, "total": 765 }, { "time": 1736726400000, "valid": 13, "notFound": 0, "forbidden": 0, "usageExceeded": 0, "rateLimited": 10, "unauthorized": 0, "disabled": 0, "insufficientPermissions": 0, "expired": 0, "total": 23, "keyId": "key_2zeYsLbpULnEUsvYeFGMeJzACp4j" } ] ``` -------------------------------- ### Install Unkey API Package Source: https://unkey.com/docs/quickstart/apis/express Installs the Unkey API client library for Node.js. ```bash npm install @unkey/api@0.35 ``` -------------------------------- ### Install Unkey Python SDK via PIP Source: https://unkey.com/docs/libraries/py/overview Installs the Unkey Python SDK using pip, the default package installer for Python. This command fetches and installs the package from PyPI. ```bash pip install unkey.py ``` -------------------------------- ### Install @unkey/ratelimit Source: https://unkey.com/docs/libraries/ts/ratelimit/ratelimit Install the @unkey/ratelimit library using various package managers like npm, pnpm, yarn, or bun. ```npm npm install @unkey/ratelimit ``` ```pnpm pnpm add @unkey/ratelimit ``` ```yarn yarn add @unkey/ratelimit ``` ```bun bun install @unkey/ratelimit ``` -------------------------------- ### Create Unkey API Example Source: https://unkey.com/docs/libraries/go/overview A Go example demonstrating how to initialize the Unkey SDK client and create a new API. It shows setting up authentication with a bearer token and making the initial API call to create an API resource. ```go package main import ( "context" unkey "github.com/unkeyed/unkey/sdks/golang" "github.com/unkeyed/unkey/sdks/golang/models/components" "github.com/unkeyed/unkey/sdks/golang/models/operations" "log" ) func main() { s := unkey.New( unkey.WithSecurity(""), ) request := operations.CreateAPIRequestBody{ Name: "my-api", } ctx := context.Background() res, err := s.CreateAPI(ctx, request) if err != nil { log.Fatal(err) } if res != nil { // handle response } } ``` -------------------------------- ### Get API Key Response Example Source: https://unkey.com/docs/libraries/ts/sdk/keys/get Example JSON structure for a successful response when retrieving an API key, showing key details like ID, API ID, workspace ID, and status. ```json { "result": { "id": "key_123", "start": "3ZHF3", "apiId": "api_123", "workspaceId": "ws_123", "meta": {}, "createdAt": 1747222842094, "roles": [], "permissions": [], "enabled": true } } ``` -------------------------------- ### Create and Initialize Bun Project Source: https://unkey.com/docs/quickstart/ratelimiting/bun This snippet demonstrates the initial steps to create a new directory for your Bun project and initialize it using the `bun init` command. This sets up the basic project structure and necessary configuration files. ```bash mkdir unkey-with-bun cd unkey-with-bun bun init -y ``` -------------------------------- ### Get API Key Request Example Source: https://unkey.com/docs/libraries/ts/sdk/keys/get Demonstrates how to use the Unkey SDK to retrieve an API key by its ID. Includes error handling for network or bad requests. ```ts const { result, error } = await unkey.keys.get({ keyId: "key_123" }); if (error) { // handle potential network or bad request error // a link to our docs will be in the `error.docs` field console.error(error.message); return; } console.log(result) ``` -------------------------------- ### Initialize Bun Project Source: https://unkey.com/docs/quickstart/apis/bun Steps to create a new Bun project directory and initialize it with `bun init -y`. This sets up the basic project structure for a Bun application. ```bash mkdir unkey-with-bun cd unkey-with-bun bun init -y ``` -------------------------------- ### Get Identity Request Example (TypeScript) Source: https://unkey.com/docs/libraries/ts/sdk/identities/get-identity Demonstrates how to fetch an identity using the Unkey SDK in TypeScript. It shows making the request and handling potential errors, including logging the result or error message. ```ts const { result, error } = await unkey.identities.get({ externalId: "user_123", }); if (error) { // handle potential network or bad request error // a link to our docs will be in the `error.docs` field console.error(error.message); return; } console.log(result); ``` -------------------------------- ### Run the Server Source: https://unkey.com/docs/quickstart/apis/express Command to start the Express server using npm. ```bash npm run start ``` -------------------------------- ### Install Unkey API Package Source: https://unkey.com/docs/quickstart/apis/bun Installs the `@unkey/api` package, which provides the necessary functions to verify API keys with Unkey. It's recommended to use a specific version for stability. ```bash bun install @unkey/api@0.35 ``` -------------------------------- ### Get Verifications Request Example Source: https://unkey.com/docs/libraries/ts/sdk/analytics/get Demonstrates how to retrieve verification usage data using the Unkey SDK. It shows making a request to the `getVerifications` method with an `apiId` and handling potential errors. ```typescript const { result, error } = await unkey.analytics.getVerifications({ apiId: "api_123", }); if (error) { // handle potential network or bad request error // a link to our docs will be in the `error.docs` field console.error(error.message); return; } console.log(result) ``` -------------------------------- ### Start Unkey Elixir SDK GenServer Directly Source: https://unkey.com/docs/libraries/ex/overview Shows how to start the Unkey Elixir SDK GenServer directly using its `start_link` function, passing the token and optional base URL. ```elixir {:ok, _pid} = UnkeyElixirSdk.start_link(%{token: "yourunkeyrootkey", base_url: "https://api.unkey.dev/v1/keys"}) ``` -------------------------------- ### Example Namespace with Two Stores Source: https://unkey.com/docs/libraries/ts/cache/overview Illustrates the setup of a Namespace for 'User' data using both a MemoryStore and a CloudflareStore. This example demonstrates how to configure multiple stores for a tiered caching approach, specifying freshness and staleness intervals. ```ts import { Namespace, DefaultStatefulContext, MemoryStore, CloudflareStore } from "@unkey/cache"; type User = { email: string; } // Assuming 'c.env.CLOUDFLARE_API_KEY' and 'c.env.CLOUDFLARE_ZONE_ID' are available // const memory = new MemoryStore({ // persistentMap: new Map(), // }); // const cloudflare = new CloudflareStore({ // cloudflareApiKey: c.env.CLOUDFLARE_API_KEY, // zoneId: c.env.CLOUDFLARE_ZONE_ID, // domain: "cache.unkey.dev", // }) // const ctx = new DefaultStatefulContext() // const namespace = new Namespace(ctx, { // stores: [memory, cloudflare], // fresh: 60_000, // 1 minute // stale: 900_000, // 15 minutes // }); ``` -------------------------------- ### Retrieve an Identity Source: https://unkey.com/docs/quickstart/identities/shared-ratelimits Shows how to fetch identity details from the Unkey API using a GET request with the identity's ID. ```typescript const getIdentityResponse = await fetch(`https://api.unkey.dev/v1/identities.getIdentity?identityId=${identityId}`, { method: "GET", headers: { Authorization: `Bearer ${rootKey}`, } }); const identity = await getIdentityResponse.json<{ id: string; externalId: string; meta: unknown; ratelimits: Array<{ name: string; limit: number; duration: number }>; }>(); ``` -------------------------------- ### Python Example: Setting Roles with Unkey Source: https://unkey.com/docs/libraries/py/services/keys Demonstrates how to use the unkey-py SDK to set roles for an API key. It shows initialization of the Unkey client and making the set_roles call with sample data. ```python import os from unkey_py import Unkey s = Unkey( bearer_auth=os.getenv("UNKEY_BEARER_AUTH", ""), ) res = s.keys.set_roles(request={ "key_id": "", "roles": [ { "id": "role_123", }, { "name": "dns.record.create", }, { "name": "dns.record.delete", "create": True, }, ], }) if res.response_bodies is not None: # handle response pass ``` -------------------------------- ### Get Verifications Response Example Source: https://unkey.com/docs/libraries/ts/sdk/analytics/get Illustrates the structure of the response when retrieving verification usage data. The result contains an array of objects, each detailing usage metrics like valid, notFound, forbidden, and total counts, along with associated tags and key information. ```json { "result": [ { "time": 123, "valid": 123, "notFound": 123, "forbidden": 123, "usageExceeded": 123, "rateLimited": 123, "unauthorized": 123, "disabled": 123, "insufficientPermissions": 123, "expired": 123, "total": 123, "tag": "path/user_123", "tags": [ "path/user_123", "path/create", "path/delete/" ], "keyId": "key_123", "identity": { "id": "id_123", "externalId": "user_123" } } ] } ``` -------------------------------- ### Run Next.js Development Server Source: https://unkey.com/docs/quickstart/apis/nextjs Commands to start the Next.js development server using different package managers. ```bash bun run dev ``` ```bash pnpm run dev ``` ```bash yarn run dev ``` ```bash npm run dev ``` -------------------------------- ### OpenAPI Spec: GET /v1/liveness Endpoint Source: https://unkey.com/docs/api-reference/v1/liveness/health-check This entry details the OpenAPI specification for the GET /v1/liveness endpoint. It outlines the request structure, successful responses (200 OK) including service status, and common error responses (400 BAD_REQUEST, 401 UNAUTHORIZED) with their respective schemas and examples. ```APIDOC paths: path: /v1/liveness method: get servers: - url: https://api.unkey.dev description: Production request: security: [] parameters: path: {} query: {} header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: status: allOf: - type: string description: The status of the server services: allOf: - type: object properties: metrics: type: string description: The name of the connected metrics service example: AxiomMetrics logger: type: string description: The name of the connected logger service example: AxiomLogger or ConsoleLogger ratelimit: type: string description: The name of the connected ratelimit service usagelimit: type: string description: The name of the connected usagelimit service required: - metrics - logger - ratelimit - usagelimit requiredProperties: - status - services examples: example: value: status: services: metrics: AxiomMetrics logger: AxiomLogger or ConsoleLogger ratelimit: usagelimit: description: The configured services and their status '400': application/json: schemaArray: - type: object properties: error: allOf: - type: object properties: code: type: string enum: - BAD_REQUEST description: A machine readable error code. example: BAD_REQUEST docs: type: string description: >- A link to our documentation with more details about this error code example: >- https://unkey.dev/docs/api-reference/errors/code/BAD_REQUEST message: type: string description: A human readable explanation of what went wrong requestId: type: string description: >- Please always include the requestId in your error report example: req_1234 required: - code - docs - message - requestId refIdentifier: '#/components/schemas/ErrBadRequest' requiredProperties: - error examples: example: value: error: code: BAD_REQUEST docs: https://unkey.dev/docs/api-reference/errors/code/BAD_REQUEST message: requestId: req_1234 description: >- The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). '401': application/json: schemaArray: - type: object properties: error: allOf: - type: object properties: code: type: string enum: - UNAUTHORIZED description: A machine readable error code. example: UNAUTHORIZED docs: type: string description: >- A link to our documentation with more details about this error code example: >- https://unkey.dev/docs/api-reference/errors/code/UNAUTHORIZED message: type: string description: A human readable explanation of what went wrong requestId: type: string description: >- Please always include the requestId in your error report example: req_1234 required: - code - docs - message - requestId refIdentifier: '#/components/schemas/ErrUnauthorized' requiredProperties: - error examples: example: value: error: code: UNAUTHORIZED docs: https://unkey.dev/docs/api-reference/errors/code/UNAUTHORIZED message: requestId: req_1234 description: >- Although the HTTP standard specifies 'unauthorized', the API uses 'unauthorized' to denote that authentication is required and has failed or has not yet been provided. ``` -------------------------------- ### Run Hono Development Server Source: https://unkey.com/docs/quickstart/ratelimiting/hono Commands to start the Hono development server using different package managers. ```bash npm run dev ``` ```bash pnpm run dev ``` ```bash yarn run dev ``` ```bash bun run dev ``` -------------------------------- ### Install Unkey TypeScript Client Source: https://unkey.com/docs/libraries/ts/sdk/overview Instructions for installing the @unkey/api TypeScript client using various package managers like npm, pnpm, yarn, and bun. ```bash npm install @unkey/api ``` ```bash pnpm add @unkey/api ``` ```bash yarn add @unkey/api ``` ```bash bun install @unkey/api ``` -------------------------------- ### API Configuration Response (JSON) Source: https://unkey.com/docs/libraries/ts/sdk/apis/get Example JSON structure for a successful API configuration retrieval response from Unkey, detailing the API's ID, name, and workspace ID. ```json { "result": { "id": "api_123", "name": "My API", "workspaceId": "ws_123" } } ``` -------------------------------- ### Get Top 10 Users by API Usage Source: https://unkey.com/docs/analytics/quickstarts Retrieves the top 10 users based on total API verifications over a specified period. Results are ordered by total verifications in descending order and grouped by identity. ```bash curl 'https://api.unkey.dev/v1/analytics.getVerifications?start=1734168087000&end=1736760087000&orderBy=total&order=desc&limit=10&groupBy=identity&apiId=api_123' \ -H 'Authorization: Bearer unkey_XXX' ``` ```json [ { "identity": { "id": "id_123", "externalId": "user_123"}, "valid": 54, "notFound": 0, "forbidden": 3, "usageExceeded": 6, "rateLimited": 10, "unauthorized": 0, "disabled": 0, "insufficientPermissions": 0, "expired": 0, "total": 73 }, { "identity": { "id": "id_456", "externalId": "user_6dg"}, "valid": 24, "notFound": 0, "forbidden": 1, "usageExceeded": 32, "rateLimited": 10, "unauthorized": 0, "disabled": 0, "insufficientPermissions": 0, "expired": 0, "total": 67 }, ... ] ``` -------------------------------- ### Install Unkey Ratelimit Package Source: https://unkey.com/docs/quickstart/ratelimiting/bun Installs the `@unkey/ratelimit` package, which is essential for integrating Unkey's ratelimiting capabilities into your Bun application. This command uses Bun's package manager. ```bash bun install @unkey/ratelimit ``` -------------------------------- ### Create Next.js App with Package Managers Source: https://unkey.com/docs/quickstart/apis/nextjs Demonstrates commands to initialize a new Next.js project using different package managers like npm, pnpm, yarn, and bun. ```bash npx create-next-app@latest ``` ```bash pnpm create next-app@latest ``` ```bash yarn create-next-app@latest ``` ```bash bunx create-next-app ``` -------------------------------- ### OpenAPI: List Permissions Endpoint Source: https://unkey.com/docs/api-reference/v1/permissions/list-permissions Details the GET request for listing all permissions available in a workspace. It specifies the request method, path, authentication requirements, and the structure of successful and error responses, including detailed schemas and examples. ```APIDOC OpenAPI: /v1/permissions.listPermissions Method: GET Servers: - url: https://api.unkey.dev description: Production Request: Security: - title: bearerAuth parameters: header: Authorization: type: http scheme: bearer Parameters: path: {} query: {} header: {} cookie: {} Body: {} Response: '200': application/json: schemaArray: - type: array items: allOf: - type: object properties: id: type: string description: The id of the permission example: perm_123 name: type: string description: The name of the permission. example: domain.record.manager slug: type: string description: The slug of the permission example: domain-record-manager description: type: string description: >- The description of what this permission does. This is just for your team, your users will not see this. example: Can manage dns records required: - id - name - slug examples: example: value: - id: perm_123 name: domain.record.manager slug: domain-record-manager description: Can manage dns records description: The permissions in your workspace '400': application/json: schemaArray: - type: object properties: error: allOf: - type: object properties: code: type: string enum: - BAD_REQUEST description: A machine readable error code. example: BAD_REQUEST docs: type: string description: >- A link to our documentation with more details about this error code example: >- https://unkey.dev/docs/api-reference/errors/code/BAD_REQUEST message: type: string description: A human readable explanation of what went wrong requestId: type: string description: >- Please always include the requestId in your error report example: req_1234 required: - code - docs - message - requestId refIdentifier: '#/components/schemas/ErrBadRequest' requiredProperties: - error examples: example: value: error: code: BAD_REQUEST docs: https://unkey.dev/docs/api-reference/errors/code/BAD_REQUEST message: requestId: req_1234 description: >- The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). '401': application/json: schemaArray: - type: object properties: error: allOf: - type: object properties: code: type: string enum: - UNAUTHORIZED description: A machine readable error code. example: UNAUTHORIZED docs: type: string description: >- A link to our documentation with more details about this error code example: >- https://unkey.dev/docs/api-reference/errors/code/UNAUTHORIZED message: type: string description: A human readable explanation of what went wrong requestId: type: string description: >- Please always include the requestId in your error report example: req_1234 required: - code - docs - message - requestId refIdentifier: '#/components/schemas/ErrUnauthorized' requiredProperties: - error examples: example: value: error: code: UNAUTHORIZED docs: https://unkey.dev/docs/api-reference/errors/code/UNAUTHORIZED message: Invalid API key requestId: req_1234 description: >- Although the HTTP standard specifies 'unauthorized', Unkey uses this code because all authentication is typically handled by the API key. This error means that the provided API key is invalid or has expired. ```