> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.instabase.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.instabase.com/_mcp/server.

# Using the API and SDK

> Get started using the AI Hub API and SDK.

With the AI Hub API and SDK, you can integrate AI Hub functionality into your own workflows and tooling by controlling AI Hub programmatically.

The API accepts RESTful HTTP requests made from a variety of tools or almost any programming language.

The SDK wraps API calls in Python classes and methods, providing a convenient way to interact with AI Hub programmatically.

> **Tip**
>
> Both the API and SDK cover the major use cases of AI Hub. However, their feature set isn't identical.
>
> * The API can access most, but not all, of the same features as the graphical user interface.
>
> * The SDK can access all the same features as the API.

## Prerequisites

Before using the API or SDK, you must complete several prerequisites.

* You must have an AI Hub account. See [Account setup](/overview/account-setup/) to learn how to create or join an organization.

* You must have an API token. AI Hub supports both AI Hub-managed tokens and, for Enterprise-tier organizations with [OAuth providers configured](/admin/security/oauth-providers/), externally managed tokens. If supported by your organization, you can [create your own AI Hub-managed tokens](/api-sdk/authorization#oauth-tokens) from the **APIs** settings page. If you don't see the option to create a token, contact your organization admin for next steps.

* You must have your organization ID or user ID to use in the `IB-Context` header that's included with every API or SDK call. Read the [context identification](/api-sdk/authorization#ib-context-header) documentation to understand how to use the `IB-Context` header, including where to find your organization or user ID.

## Using the API

You can call API endpoints with any of these techniques.

* Use the `curl` command.

* Use code in any language that makes HTTP requests.

* Use the AI Hub Postman collection.

* Use the playground feature in the API reference documentation.

> **Warning**
>
> The API only supports requests via the `https` protocol. Using the `http` protocol produces unpredictable responses.

### curl

The `curl` command line tool makes HTTP requests, including calls to API endpoints. The documentation for every AI Hub API operation includes sample code for calling the API with `curl`.

For example, running this command in a terminal sends a `POST` verb to the batches endpoint, to create a resource called a batch.

```bash
curl -X POST "${API_ROOT}/v2/batches" \
-H "Authorization: Bearer ${API_TOKEN}" \
-H "IB-Context: ${IB_CONTEXT}"\
-H "Content-Type: application/json" \
-d '{"name": "test"}'
```

Before calling the API with `curl`, set these environment variables:

| Variable     | Value                                                                                                                                                                                                                                                                                                                                          |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `API_ROOT`   | The root API URL. Combine the base URL of your AI Hub instance and `/api`.   For **organization accounts**  • If your organization has a custom AI Hub domain, include it in the URL, such as `https://my-organization.instabase.com/api`.  • If your organization doesn't have a custom AI Hub domain, use `https://aihub.instabase.com/api`. |
| `API_TOKEN`  | Your API token.                                                                                                                                                                                                                                                                                                                                |
| `IB_CONTEXT` | The value to use for the `IB-Context` header.  • To use your **organization account**, use your organization ID.                                                                                                                                                                                                                               |

With the environment variables defined, the previous create batch command returns a JSON object with the ID of the new batch and no errors.

### Code

Most languages can make HTTP requests. To call an API endpoint using code, submit an HTTP request with the appropriate HTTP verb and parameters.

These snippets of code send the `POST` verb with a `{ "name": "test" }` JSON payload to the batches endpoint in different languages.

#### Go

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	jsonData, _ := json.Marshal(map[string]string{"name": "test"})
	apiRootUrl := os.Getenv("API_ROOT")
	req, _ := http.NewRequest(
		"POST",
		apiRootUrl+"/v2/batches",
		bytes.NewBuffer(jsonData))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("API_TOKEN"))
	req.Header.Set("IB-Context", os.Getenv("IB_CONTEXT"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, _ := client.Do(req)
	defer resp.Body.Close()

	bodyBytes, _ := io.ReadAll(resp.Body)
	fmt.Println(string(bodyBytes))
}
```

#### Java

```java
import java.net.URI;
import java.net.http.*;

class ApiClient {

    public static void main(String[] args) throws Exception {
        String apiRootUrl = System.getenv("API_ROOT");
        String apiToken = System.getenv("API_TOKEN");
        String ibContext = System.getenv("IB_CONTEXT");
        String jsonData = "{\"name\": \"test\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiRootUrl + "/v2/batches"))
                .header("Authorization", "Bearer " + apiToken)
                .header("IB-Context", ibContext)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonData))
                .build();
        HttpResponse<String> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
```

#### Node

```javascript
async function makeRequest() {
    const response = await fetch(
        `${process.env.API_ROOT}/v2/batches`,
        {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${process.env.API_TOKEN}`,
                'IB-Context': process.env.IB_CONTEXT,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: 'test' })
        }
    );
    const data = await response.json();
    console.log(data);
}
makeRequest();
```

#### Python

```python
import json
import os
import requests  # a third-party library

url = os.getenv('API_ROOT') + '/v2/batches'
data = {'name': 'test'}
headers = {'Authorization': 'Bearer ' + os.getenv('API_TOKEN'),
           'IB-Context': os.getenv('IB_CONTEXT'),
           'Content-Type': 'application/json'}
response = requests.post(url,
                         data=json.dumps(data),
                         headers=headers)
print(response.json())
```

Before making API calls from code, set the environment variables `API_ROOT`, `API_TOKEN`, and `IB_CONTEXT`.

| Variable     | Value                                                                                                                                                                                                                                                                                                                                          |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `API_ROOT`   | The root API URL. Combine the base URL of your AI Hub instance and `/api`.   For **organization accounts**  • If your organization has a custom AI Hub domain, include it in the URL, such as `https://my-organization.instabase.com/api`.  • If your organization doesn't have a custom AI Hub domain, use `https://aihub.instabase.com/api`. |
| `API_TOKEN`  | Your API token.                                                                                                                                                                                                                                                                                                                                |
| `IB_CONTEXT` | The value to use for the `IB-Context` header.  • To use your **organization account**, use your organization ID.                                                                                                                                                                                                                               |

If you set these environment variables and run any of the code snippets, the API returns the ID of the newly created batch and no errors.

> **Tip**
>
> The documentation page for each API operation includes sample code for calling the API in Python. The [playground](#playground) available on each API operation page includes sample code in Typescript.

### Postman

An AI Hub API collection is available in Postman, a platform for building and using APIs. The AI Hub collection includes automation, so responses from one API call are automatically populated in later calls.

#### Configure Postman

To get started, click **Run in Postman** and fork or import the collection. If given the option, enable notifications for any changes to the collection.

[![button to run postman](https://run.pstmn.io/button.svg)](https://app.getpostman.com/run-collection/1498156-4049b657-0929-472d-95b7-70dba22b45c4?action=collection%2Ffork\&collection-url=entityId%3D1498156-4049b657-0929-472d-95b7-70dba22b45c4%26entityType%3Dcollection)

After making a copy of the collection, set up your [authorization and context identification](/api-sdk/authorization/) variables.

1. In Postman, in the left sidebar, click **Instabase AI Hub**.

2. Click the **Variables** tab.

![The Variables tab of a Postman collection, viewed in Postman's desktop app](/_fern-img/47d3c8e5ce21b94cb7ffc1fcdf87a01be8f94b66aacdddb7c967b5df15dbf529.webp)

3. Update the **Current value** column for the following variables.

| Variable          | Value                                                                                                                                                                                                                                                                                                    |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `API_ROOT`        | Your AI Hub root URL.   For **organization accounts**  • If your organization has a custom AI Hub domain, use your organization's root API URL, such as `https://my-organization.instabase.com/api`.  • If your organization doesn't have a custom AI Hub domain, use `https://aihub.instabase.com/api`. |
| `API_KEY`         | Your API token.                                                                                                                                                                                                                                                                                          |
| `CONTEXT`         | The value for the `IB-Context` header. To use your **organization account**, enter `{{ORGANIZATION_ID}}`                                                                                                                                                                                                 |
| `USER_ID`         | Your user ID.                                                                                                                                                                                                                                                                                            |
| `ORGANIZATION_ID` | Your organization ID.                                                                                                                                                                                                                                                                                    |

4. Click **Save** to complete Postman configuration. It's now ready to call the AI Hub API.

> **Info**
>
> Instructions for using Postman are beyond the scope of this page. Refer to [Postman documentation](https://learning.postman.com/docs/introduction/overview/) for more information.

To test your Postman configuration, make an API call to create a batch.

1. Navigate to the **App Run** > **Create batch** endpoint.

2. Click **Send**.

The **Body** tab shows a JSON object with an `id` key and an integer value.

### Playground

> **Info**
>
> The playground is a feature of the AI Hub documentation, not the AI Hub app.

Every page in the **API reference** section of the AI Hub documentation includes an interactive playground that lets you build and send requests. The playground isn't suitable for production use, but is a convenient way to learn about the API.

For example, use the navigation pane to visit the **API reference** > **Runs** > **Run deployment** page and click **Try it** in the sample code frame.

![Request sample frame with the API playground Try it button highlighted](/_fern-img/cbdf293ee7e4d3c7f6caeb9a5a90b6c9568d890a785c9fa1ff8d4da7cb594dcc.webp)

To see the playground in action, use it to make an API call to create a batch.

1. Navigate to the [create batch](/api-sdk/api-reference/batches/create-batch/) endpoint documentation page.

2. In the sample code frame, click **Try it** to open the playground.

3. Enter an API key. Click **Enter your bearer token**, enter your API token, then click **Close**.

4. (Optional) If your organization uses a custom AI Hub domain, edit the root API URL. Double-click the request URL at the top of the playground page and edit the root URL from `https://aihub.instabase.com/api` to `https://<YOUR-DOMAIN>.instabase.com/api`.

5. In the **Body Parameters** section, enter `test` as the value of the `name` parameter.

6. Click **Send Request**.

The **RESPONSE** box shows a JSON object with an `id` key and an integer value.

> **Tip**
>
> The playground shows sample code for making direct API calls with `curl`, Typescript, or Python, based on the selector in the top right. The **copy** icon above the sample code lets you paste sample code into your own scripts.

## Using the SDK

> **Info**
>
> The SDK requires Python 3.7 or higher. No other languages are supported.

### Install the SDK

The SDK is published to the Python Package Index (PyPI). This command installs the SDK if it's not installed, upgrades the SDK if an earlier version is installed, and does nothing if the latest version is installed.

```bash
pip install --upgrade instabase-aihub
```

> **Tip**
>
> If you're new to installing Python packages, see the Python Packaging User Guide [tutorial for installing packages](https://packaging.python.org/en/latest/tutorials/installing-packages/). The tutorial covers getting started topics such as installation requirements and creating a virtual environment.

### Initialize the SDK

The first step in using the SDK is initializing a `client` object with custom `api_root`, `api_key`, and `ib_context` values. The client handles [authorization and context identification](/api-sdk/authorization/) and provides methods for making API calls.

To initialize the SDK, start a Python script with this code.

```python
from aihub import AIHub

client = AIHub(api_root=<API-ROOT>,
               api_key=<API-TOKEN>,
               ib_context=<IB-CONTEXT>)
```

#### Parameter reference

| Parameter    | Type | Required            | Description                                                                                                                                                                                                                                                                                   |
| ------------ | ---- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api_root`   | str  | No                  | The root URL of your AI Hub API.    For **organization accounts**  • If your organization has a custom AI Hub domain, use your organization's root API URL, such as `https://my-org.instabase.com/api`.  • If your organization doesn't have a custom AI Hub domain, omit setting `api_root`. |
| `api_key`    | str  | Yes                 | Your API token.                                                                                                                                                                                                                                                                               |
| `ib_context` | str  | No, but recommended | The value for the `IB-Context` header that the SDK includes with all API requests. Set to your organization ID.                                                                                                                                                                               |

With the SDK installed and initialized, you can use any SDK sample code provided in the API or SDK documentation pages.

![Selecting Python from the API code sample language dropdown](/_fern-img/0187110cf6d621cb57f31a37a7f73458f489c6a99eb81e68fee14e910e447e86.webp)
SDK sample code from an API documentation page

### Test the SDK

Confirm that the SDK is installed and initialized by adding this line under your initialization code and running the whole script.

```python
batch = client.batches.create(name='test-batch')
print(batch)
```

If the output includes `id=<INTEGER>` and no errors, the SDK is working as expected.

## Next steps

With your setup complete and tested, you're ready to interact with the AI Hub API by making direct calls or by using the SDK.

Here are some things you can try next.

* Run an automation app [using the SDK](/api-sdk/apps-sdk).

* Learn about API endpoints with the [API reference documentation](/api-sdk/api-reference/batches/create-batch).
  > **Info**
  >
  > If you prefer to make API calls using the SDK, look for SDK examples in the documentation for supported endpoints.

* Learn how to [track consumption unit usage](/admin/usage/) for AI Hub operations.

* Learn about [service accounts](/admin/service-accounts), which let your organization make API or SDK calls that aren't tied to a particular user.

* Review AI Hub [release notes](/release-notes), which include API and SDK changes.