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

# Authenticate with Nexenergie: Bearer Tokens and API Keys

> Learn to obtain a Bearer token or API key for Nexenergie, handle token expiry, and correctly format credentials in every API request you send.

Nexenergie uses Bearer token authentication for all API requests. Every call you make must include an `Authorization: Bearer <token>` header — requests without a valid credential are rejected before they reach any forecast data. You can authenticate with either a short-lived session token obtained by exchanging your username and password, or a long-lived API key generated from the dashboard.

## Obtaining a Token

Exchange your Nexenergie username (email address) and password for an access token by calling `POST /auth/token`. The request body must be sent as `application/x-www-form-urlencoded`.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://app.nexenergie.ai/api/v1/auth/token" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "username=you@example.com&password=your_password"
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://app.nexenergie.ai/api/v1/auth/token",
      data={
          "username": "you@example.com",
          "password": "your_password",
      },
  )
  response.raise_for_status()
  token_data = response.json()
  access_token = token_data["access_token"]
  print(access_token)
  ```

  ```javascript JavaScript theme={null}
  const params = new URLSearchParams();
  params.append("username", "you@example.com");
  params.append("password", "your_password");

  const response = await fetch(
    "https://app.nexenergie.ai/api/v1/auth/token",
    {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: params,
    }
  );

  const tokenData = await response.json();
  const accessToken = tokenData.access_token;
  console.log(accessToken);
  ```
</CodeGroup>

A successful response returns HTTP `200` with the following JSON body:

```json Response theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ5b3VAZXhhbXBsZS5jb20iLCJleHAiOjE3NTI2MDgwMDB9.abc123xyz",
  "token_type": "bearer",
  "expires_in": 86400
}
```

<ResponseField name="access_token" type="string">
  The Bearer token to include in the `Authorization` header of every subsequent API request.
</ResponseField>

<ResponseField name="token_type" type="string">
  Always `"bearer"`.
</ResponseField>

<ResponseField name="expires_in" type="integer">
  Number of seconds until the token expires. Session tokens are valid for **86 400 seconds (24 hours)**.
</ResponseField>

## Using Your Token

Pass the token in the `Authorization` header as `Bearer <token>` on every request to the Nexenergie API.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://app.nexenergie.ai/api/v1/forecasts/day-ahead?date=2025-07-14" \
    -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
    -H "Accept: application/json"
  ```

  ```python Python theme={null}
  import os
  import requests

  token = os.environ["NEXENERGIE_API_KEY"]

  response = requests.get(
      "https://app.nexenergie.ai/api/v1/forecasts/day-ahead",
      params={"date": "2025-07-14"},
      headers={"Authorization": f"Bearer {token}"},
  )
  response.raise_for_status()
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const token = process.env.NEXENERGIE_API_KEY;

  const response = await fetch(
    "https://app.nexenergie.ai/api/v1/forecasts/day-ahead?date=2025-07-14",
    {
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/json",
      },
    }
  );

  const data = await response.json();
  console.log(data);
  ```
</CodeGroup>

## API Keys

For production applications and automated pipelines, use a long-lived API key instead of a session token. API keys do not expire automatically and are easier to rotate on a schedule you control.

To generate an API key:

1. Log in to the [Nexenergie dashboard](https://app.nexenergie.ai).
2. Navigate to **Account → API Keys** (or go to [app.nexenergie.ai/account/api-keys](https://app.nexenergie.ai/account/api-keys)).
3. Click **Generate New Key**, enter a descriptive label, and click **Create**.
4. Copy the key immediately — it is displayed in full only once.

Use an API key exactly like a session token: pass it in the `Authorization: Bearer <api-key>` header. There is no difference in the request format between the two credential types.

<Warning>
  Never commit tokens or API keys to source control, share them in Slack or email, or include them in client-side code that is shipped to end users. If a credential is compromised, revoke it immediately from **Account → API Keys** in the dashboard and generate a replacement.
</Warning>

## Token Expiry

Session tokens obtained via `POST /auth/token` expire after **24 hours** (`expires_in: 86400`). After expiry, any request using that token returns `401 Unauthorized`. Re-authenticate by calling `POST /auth/token` again with your credentials to obtain a fresh token.

<Tip>
  Store the `expires_in` value alongside your token and proactively refresh it a few minutes before expiry to avoid failed requests during active sessions.
</Tip>

Long-lived API keys do not have an automatic expiry. You can revoke and replace them at any time from the dashboard.

## Authentication Errors

The table below lists the HTTP error codes you may receive when authentication fails.

| Status Code                | Error                | Cause                                                                                                                  | Resolution                                                                                                                                    |
| -------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `401 Unauthorized`         | `invalid_token`      | The token or API key is missing, malformed, or has expired.                                                            | Check that the `Authorization` header is present and correctly formatted as `Bearer <token>`. Re-authenticate if the token has expired.       |
| `403 Forbidden`            | `insufficient_scope` | The token is valid but your account does not have permission to access the requested resource.                         | Contact your Nexenergie account administrator to review your access level, or check that you are requesting data within your subscribed plan. |
| `422 Unprocessable Entity` | `validation_error`   | The request body sent to `POST /auth/token` is malformed — for example, the `username` or `password` field is missing. | Ensure the body is `application/x-www-form-urlencoded` and includes both `username` and `password` fields.                                    |
