# Getting started with API

> Step-by-step walkthrough on how to obtain the API tokens for performing various operations with Last9

Source: https://last9.io/docs/getting-started-with-api/

The API provides a programmatic method to access and operate Last9. This exposes a subset of features and actions that can be performed on Last9 as REST APIs. For example, you can send [change events](/docs/change-events/) to Last9 using these APIs or you can [generate alert rules](/docs/alerting-via-iac/).

:::tip
These APIs differ from the instrumentation and configurations required for data ingestion into Last9 clusters. They also differ from querying APIs provided by Last9 to read data from a Last9 cluster.
:::

## Access Requirements

Access to the API Access page and token generation is controlled by [user roles](/docs/users/):

- **Admins** can generate and revoke refresh tokens, and exchange them for access tokens
- **Editors** can exchange existing refresh tokens for access tokens, but cannot generate new refresh tokens
- **Viewers** cannot access the API Access page

If you need API access as an Editor, ask your organization's Admin to generate a refresh token for you.

## Base URL

The base API URL can be obtained from the [API Access](https://app.last9.io/settings/api-access) page. It is in the following format:

```text
https://{domain}/api/{version}/organizations/{org}/{endpoint}
```

The `{org}` parameter is your unique organization slug.

## Tokens

Authentication is performed using Bearer access tokens. The API Access page has two tabs:

:::note
**Editors** will only see the Access Token tab. The Refresh Token tab is only visible to **Admins**.
:::

### Refresh Tokens (Admin Only)

Admins can create named refresh tokens with specific scopes (read, write, or delete). Each refresh token:

- Has a descriptive name for identification
- Is associated with a specific scope
- Can be revoked at any time by an Admin
- Is used to generate short-lived access tokens

To create a refresh token:

1. Navigate to the **Refresh Token** tab
2. Click **New token**
3. Enter a descriptive name and select a scope
4. Click **Create** and securely store the generated token

:::warning
Refresh tokens are shown only once when created. Store them securely as they cannot be retrieved later.
:::

![API Access — Refresh Token tab](../../../../assets/content/docs/developer-tools/getting-started-with-api/api-access-base-url.png)

### Access Tokens

Access tokens are short-lived tokens generated from refresh tokens. Both Admins and Editors can exchange a valid refresh token for an access token:

1. Navigate to the **Access Token** tab
2. Paste your refresh token
3. Click **Generate** to receive an access token

![API Access — Access Token tab](../../../../assets/content/docs/developer-tools/getting-started-with-api/api-access-access-token.png)

### Token Revocation

Admins can revoke refresh tokens at any time from the Refresh Token tab. When a refresh token is revoked:

- The refresh token immediately becomes invalid
- Any access tokens generated from that refresh token will be rejected
- This provides a security mechanism to invalidate compromised credentials

### Audit Trail for Tokens

All token operations are tracked in Last9's audit trail for security and compliance purposes (SOC 2, ISO 27001). Navigate to [Settings > Audit Trail](https://app.last9.io/settings/audit-trail) to view:

![Audit Trail — Token Operations](../../../../assets/content/docs/developer-tools/api-access/audit-trail-tokens.png)

- **Access Token Creation**: Who generated access tokens and when
- **Refresh Token Creation**: When named refresh tokens were created, including token names
- **Token Revocation**: Which tokens were revoked and by whom
- **User Attribution**: Full name and email of the user who performed each action
- **Resource Details**: Token names and identifiers for tracking

**Filtering Token Events:**

Use the left sidebar filters to focus on token-related activities:

1. **Resource Type** filter: Select "Access Token" or "Refresh Token" to show only token operations
2. **User** filter: See token operations by specific team members
3. **Date Range**: Search token activity within custom time windows

The audit trail helps you maintain security compliance, investigate unauthorized access, and track API credential usage across your organization.

### Token Expiry

Access tokens expire in 24 hours. Your application should handle token expiration by using the refresh token to generate a new access token.

The following error is returned when an access token expires:

```json
{ "error": "Authorization token is expired" }
```

To generate a new access token, use the refresh token endpoint:

```text
POST https://app.last9.io/api/v4/oauth/access_token
```

:::warning
The OAuth endpoint does **not** include the organization in the URL. Use the exact URL shown above, not the organization-specific base URL.
:::

Request Body:

```json
{
  "refresh_token": "eyJhbGciOiXXXXXXXXXXXXX.eyJleHXXXXXXXXX.XXXXXXXXXOwuvUNA"
}
```

The response of this endpoint will contain a pair of access tokens and refresh tokens if the refresh token in the request body is valid.

Response

```json
{
  "access_token": "eyJhbGciOiXXXXXXXXXXXXXX.eyJleHXXXXXXXXX.XXXXXXXXXOwuvUNA",
  "expires_at": 1587412870,
  "issued_at": 1587240070,
  "refresh_token": "eyJhbGciOiXXXXXXXXXXXXX.eyJleHXXXXXXXXX.XXXXXXXXXOwuvUNA",
  "type": "Bearer",
  "scopes": ["read", "write", "delete"]
}
```

## Usage

The tokens are specifically separated based on the scopes they are authorized to perform based on the impact they might have on the system's overall behavior.

- **Read Tokens**: Have a minimum impact on the performance of the Last9 application. These are to be specifically used for reading the current state of the data
- **Write Tokens**: Use this token to create or modify data in any supported entity. This could change the behavior of your usage of Last9
- **Delete Tokens**: Use this token judiciously. This could break the processes and cause an irrevocable state through missing data

## Authentication & Authorization

All public API endpoints require a Token to be supplied as an authorization header for all requests. The token is used to identify the user/application and authenticate the requests to API.
The header name must be **X-LAST9-API-TOKEN**.

:::caution
The header value **must** be prefixed with the literal word `Bearer ` (with a trailing space) before the access token. Sending the raw token without the `Bearer` prefix returns `HTTP 400 {"error":"invalid access token"}`, even when the token itself is valid.

Also note: the token goes in the `X-LAST9-API-TOKEN` header, **not** the standard `Authorization` header. Using `Authorization: Bearer <token>` returns `HTTP 401`.

| Example                            | Result                        |
| ---------------------------------- | ----------------------------- |
| `X-LAST9-API-TOKEN: Bearer eyJ...` | ✓ correct                     |
| `X-LAST9-API-TOKEN: eyJ...`        | ✗ 400 — missing Bearer prefix |
| `Authorization: Bearer eyJ...`     | ✗ 401 — wrong header          |

:::

## Making your first API request

Please follow the steps below to create our first API request for a change event.

### Step 1: Generate Tokens

1. Navigate to the [API Access](https://app.last9.io/settings/api-access) page
2. If you're an Admin, create a new refresh token with **write** scope from the Refresh Token tab
3. Exchange the refresh token for an access token from the Access Token tab
4. Copy the generated access token for use in your API request

### Step 2: Base URL

The base URL of your instance can be obtained as specified in the Base URL section above.

### Step 3: Making the API request

The endpoint for creating change events is

```text
PUT /change_events
```

```json
{
  "timestamp": "2024-01-15T17:57:22+05:30",
  "event_name": "new_deployment",
  "event_state": "start",
  "attributes": {
    "env": "production",
    "k8s_cluster": "prod-us-east-1",
    "app": "backend-api"
  }
}
```

The cURL request looks as follows:

```shell
curl --location --request PUT 'https://app.last9.io/api/v4/organizations/{org}/change_events' \
--header 'X-LAST9-API-TOKEN: Bearer <WRITE_ACCESS_TOKEN>' \
--header 'Content-Type: application/json' \
--data '{
  "timestamp": "2024-01-15T17:57:22+05:30",
  "event_name": "new_deployment",
  "event_state": "start",
  "attributes": {
    "env": "production",
    "k8s_cluster": "prod-us-east-1",
    "app": "backend-api"
  }
}'
```

:::tip
If you're using GitHub Actions, use the [Last9 Deployment Marker action](https://github.com/marketplace/actions/last9-deployment-marker) to send change events directly from your workflow without custom `curl` steps.
:::

### Step 4: Verify the response

The API will return the following response in case of success with HTTP status code 200.

```json
{
  "message": "success"
}
```

---

## Troubleshooting

Please get in touch with us on [Discord](https://discord.com/invite/Q3p2EEucx9) or [Email](mailto:support@last9.io) if you have any questions.
