> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agribackup.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate a New API Key for Your Organization

> Create a scoped API key for your AgriBackup enterprise organization. The raw key value is returned exactly once — store it securely immediately.

Use this endpoint to generate a new API key that your integrations can use to authenticate against the AgriBackup Enterprise API. You assign the key a name and one or more permission scopes at creation time. The `rawApiKey` field in the response contains the full key value — this is the **only** time it will ever be returned. AgriBackup stores only a cryptographic hash of the key after generation, so you must copy and store it securely before closing the response. If the key is lost, you will need to rotate it to obtain a new value.

**`POST /api/v1/enterprise/api-keys`**

## Request Body

<ParamField body="name" type="string" required>
  A descriptive label for the key that identifies its intended purpose or owning integration (for example, `"Production ERP Integration"` or `"CI/CD Pipeline Key"`). This name is displayed in audit logs and the key listing.

  **Example:** `"Default Sandbox Key"`
</ParamField>

<ParamField body="scopes" type="array of strings" required>
  An array of permission scope strings that govern which endpoints this key may call. Use `["*"]` to grant unrestricted access to all enterprise endpoints. For tighter access control, specify individual scopes such as `["risk:read", "suppliers:write"]`.

  **Example:** `["*"]`
</ParamField>

## Code Examples

<CodeGroup>
  ```python Python theme={null}
  import agribackup
  from agribackup.rest import ApiException

  configuration = agribackup.Configuration(host="https://live.agribackup.com/api/v1")
  configuration.api_key["ApiKeyAuth"] = "sk_live_YOUR_API_KEY"

  payload = {
      "name": "Production ERP Integration",
      "scopes": ["*"]
  }

  with agribackup.ApiClient(configuration) as api_client:
      try:
          api_instance = agribackup.EnterpriseAPIKeysApi(api_client)
          response = api_instance.create_api_key(body=payload)
          # Store response.raw_api_key securely — it will not be shown again
          print(response)
      except ApiException as e:
          print("Exception when calling API: %s\n" % e)
  ```

  ```javascript Node.js theme={null}
  import { AgriBackupClient } from "@agribackup/sdk";

  const client = new AgriBackupClient({
    apiKey: "sk_live_YOUR_API_KEY",
    baseUrl: "https://live.agribackup.com/api/v1",
  });

  async function generateApiKey() {
    try {
      const response = await client.keys.createApiKey({
        name: "Production ERP Integration",
        scopes: ["*"],
      });
      // Store response.rawApiKey securely — it will not be shown again
      console.log(response);
    } catch (error) {
      console.error(error);
    }
  }

  generateApiKey();
  ```

  ```bash cURL theme={null}
  curl --request POST \
    --url https://live.agribackup.com/api/v1/enterprise/api-keys \
    --header "Authorization: Bearer sk_live_YOUR_API_KEY" \
    --header "Content-Type: application/json" \
    --data '{
      "name": "Production ERP Integration",
      "scopes": ["*"]
    }'
  ```
</CodeGroup>

## Response

A `201 Created` response confirms the key was generated. The `rawApiKey` field contains the plaintext key — copy it immediately.

```json theme={null}
{
  "id": "key_a1b2c3d4e5f6",
  "name": "Production ERP Integration",
  "rawApiKey": "sk_live_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890",
  "scopes": ["*"],
  "createdAt": "2026-06-01T10:00:00Z"
}
```

<ResponseField name="id" type="string">
  The unique identifier assigned to this API key. Use this as the `keyId` path parameter when rotating or deleting the key.
</ResponseField>

<ResponseField name="name" type="string">
  The descriptive label you provided in the request, confirmed in the response.
</ResponseField>

<ResponseField name="rawApiKey" type="string">
  The plaintext API key value. This string is returned **exactly once** at generation time. AgriBackup does not store this value after the response is sent. Store it in a secrets manager (e.g., HashiCorp Vault, AWS Secrets Manager) immediately.
</ResponseField>

<ResponseField name="scopes" type="array of strings">
  The permission scopes assigned to the key, as provided in the request.
</ResponseField>

<ResponseField name="createdAt" type="string (ISO 8601)">
  The UTC timestamp at which the key was generated.
</ResponseField>

## Error Responses

| HTTP Status             | Error Code          | Description                                                                                      |
| ----------------------- | ------------------- | ------------------------------------------------------------------------------------------------ |
| `400 Bad Request`       | `VALIDATION_FAILED` | The request body is missing required fields (`name` or `scopes`), or `scopes` is an empty array. |
| `401 Unauthorized`      | `UNAUTHORIZED`      | The `Authorization` header is absent or the bearer token is invalid.                             |
| `403 Forbidden`         | `FORBIDDEN`         | The authenticated identity does not have permission to create API keys for this organization.    |
| `429 Too Many Requests` | `RATE_LIMITED`      | You have exceeded the hourly rate limit. Check `X-RateLimit-Reset` for your reset time.          |

```json theme={null}
{
  "code": "VALIDATION_FAILED",
  "message": "Request validation failed",
  "details": [
    {
      "code": "REQUIRED_FIELD_MISSING",
      "field": "scopes",
      "issue": "scopes must be a non-empty array of strings"
    }
  ]
}
```
