---
title: Lakebase API guide
description: Overview of the Lakebase API for managing projects programmatically using the REST API, Databricks CLI, and Databricks SDKs.
canonical_url: https://docs.databricks.com/gcp/en/oltp/projects/api-usage
---

# Lakebase API guide

This page provides an overview of the Lakebase API, including authentication, available endpoints, and common patterns for working with the REST API, Databricks CLI, and Databricks SDKs (Python, Java, Go).

For the complete list of operations and their parameters, see the [Postgres API reference](https://docs.databricks.com/api/postgres/v1/postgres).

> [!NOTE]
>
> Use the Postgres API (`/api/2.0/postgres/`) for all Lakebase management. The Database Instances API (`/api/2.0/database/`) isn't available.

> [!NOTE]
>
> Some operations remain in [Beta](https://docs.databricks.com/gcp/en/release-notes/release-types.md). The Postgres API reference marks the status of each operation.

## <a id="authentication" />Authentication

The Lakebase API uses **workspace-level OAuth authentication** for managing project infrastructure (creating projects, configuring settings, etc.).

> [!NOTE]
>
> **Two types of connectivity**: This API is for **platform management** (creating projects, branches, computes). For **database access** (connecting to query data):
>
> * **SQL clients** (psql, pgAdmin, DBeaver): Use Lakebase OAuth tokens or Postgres passwords. See [Authentication](https://docs.databricks.com/gcp/en/oltp/projects/authentication.md).
> * **Data API** (RESTful HTTP): Use Lakebase OAuth tokens. See [Data API](https://docs.databricks.com/gcp/en/oltp/projects/data-api.md).
> * **Programming language drivers** (psycopg, SQLAlchemy, JDBC): Use Lakebase OAuth tokens or Postgres passwords. See [Quickstart](https://docs.databricks.com/gcp/en/oltp/projects/connect-overview.md).
>
> For a complete explanation of these two authentication layers, see [Authentication architecture](https://docs.databricks.com/gcp/en/oltp/projects/manage-project-permissions.md#authentication-architecture).

### <a id="setup-auth" />Set up authentication

Authenticate using the Databricks CLI:

```bash
databricks auth login --host https://your-workspace.cloud.databricks.com
```

Follow the browser prompts to log in. The CLI caches your OAuth token at `~/.databricks/token-cache.json`.

Then choose your access method:

#### Python SDK

The SDK uses unified authentication and automatically handles OAuth tokens:

```python
from databricks.sdk import WorkspaceClient

w = WorkspaceClient()
```

#### Java SDK

The SDK uses unified authentication and automatically handles OAuth tokens:

```java
import com.databricks.sdk.WorkspaceClient;

WorkspaceClient w = new WorkspaceClient();
```

#### CLI

Commands automatically use the cached token:

```bash
databricks postgres list-projects
```

#### curl

Generate a token and set your workspace URL for direct API calls. The curl examples throughout the Lakebase docs assume these two environment variables:

```bash
export WORKSPACE="https://your-workspace.cloud.databricks.com"
export DATABRICKS_TOKEN=$(databricks auth token | jq -r .access_token)

curl -X GET "$WORKSPACE/api/2.0/postgres/projects" \
  -H "Authorization: Bearer ${DATABRICKS_TOKEN}"
```

OAuth tokens expire after one hour. Regenerate as needed.

For more details, see [Authorize user access to Databricks with OAuth](https://docs.databricks.com/gcp/en/dev-tools/auth/oauth-u2m.md).

## <a id="available-endpoints" />Available endpoints

The Postgres API uses the base path `/api/2.0/postgres/`. Compute policies and resource permissions use separate API paths.

### Serverless compute policies

> [!NOTE]
> **Preview**
>
> In workspaces enrolled in the serverless compute policy Private Preview:
>
> * Creating a Lakebase project requires `CAN_USE` or `CAN_MANAGE` on a policy that allows Lakebase.
> * Changing compute capacity or scale-to-zero settings requires `CAN_MANAGE` on the Lakebase project and `CAN_USE` or `CAN_MANAGE` on its policy. This applies even if the policy sets no limit for the setting.
> * Changing a Lakebase project's display name requires only `CAN_MANAGE` on the Lakebase project.
> * Replacing the policy requires `CAN_MANAGE` on the Lakebase project and `CAN_USE` or `CAN_MANAGE` on both policies. Clearing `spec.compute_policy_id` assigns the Default Lakebase Policy as the replacement.
>
> Updated settings must satisfy the policy's current constraints and preserve its required tag key-value pairs. See [Permissions for configuration changes](https://docs.databricks.com/gcp/en/admin/compute-policies/serverless.md#configuration-permissions).
>
> To request preview access, contact your Databricks account team.

Policies can limit compute capacity and idle time before scale to zero and enforce tags. Policy management is API-only and uses `/api/2.0/policies/compute`.

Set `spec.compute_policy_id` when creating a Lakebase project to select a compute policy. For policy management and permissions, see [Manage serverless compute policies](https://docs.databricks.com/gcp/en/admin/compute-policies/serverless.md). For Postgres API examples covering Lakebase project operations and compute updates, see [Use a policy with Lakebase projects](https://docs.databricks.com/gcp/en/admin/compute-policies/serverless.md#use-with-lakebase). The separate `spec.budget_policy_id` field selects a [serverless usage policy](https://docs.databricks.com/gcp/en/admin/usage/budget-policies.md) for cost attribution.

To change the attached policy, see [Replace a Lakebase project's policy](https://docs.databricks.com/gcp/en/admin/compute-policies/serverless.md#change-lakebase-policy).

### <a id="project-endpoints" />Projects

| Operation      | Method   | Endpoint                 | Documentation                                                                                           |
| -------------- | -------- | ------------------------ | ------------------------------------------------------------------------------------------------------- |
| Create project | `POST`   | `/projects`              | [Create a project](https://docs.databricks.com/gcp/en/oltp/projects/manage-projects.md#create-projects) |
| Update project | `PATCH`  | `/projects/{project_id}` | [General settings](https://docs.databricks.com/gcp/en/oltp/projects/manage-projects.md#general)         |
| Delete project | `DELETE` | `/projects/{project_id}` | [Delete a project](https://docs.databricks.com/gcp/en/oltp/projects/manage-projects.md#delete-projects) |
| Get project    | `GET`    | `/projects/{project_id}` | [Get project details](https://docs.databricks.com/gcp/en/oltp/projects/manage-projects.md#get-project)  |
| List projects  | `GET`    | `/projects`              | [List projects](https://docs.databricks.com/gcp/en/oltp/projects/manage-projects.md#list-projects)      |

### <a id="branch-endpoints" />Branches

| Operation     | Method   | Endpoint                                      | Documentation                                                                                        |
| ------------- | -------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Create branch | `POST`   | `/projects/{project_id}/branches`             | [Create a branch](https://docs.databricks.com/gcp/en/oltp/projects/manage-branches.md#create)        |
| Update branch | `PATCH`  | `/projects/{project_id}/branches/{branch_id}` | [Update branch settings](https://docs.databricks.com/gcp/en/oltp/projects/manage-branches.md#update) |
| Delete branch | `DELETE` | `/projects/{project_id}/branches/{branch_id}` | [Delete a branch](https://docs.databricks.com/gcp/en/oltp/projects/manage-branches.md#delete)        |
| Get branch    | `GET`    | `/projects/{project_id}/branches/{branch_id}` | [View branches](https://docs.databricks.com/gcp/en/oltp/projects/manage-branches.md#view)            |
| List branches | `GET`    | `/projects/{project_id}/branches`             | [List branches](https://docs.databricks.com/gcp/en/oltp/projects/manage-branches.md#list-api)        |

### <a id="snapshot-endpoints" />Snapshots

| Operation                                      | Method   | Endpoint                                         | Documentation                                                                                             |
| ---------------------------------------------- | -------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| Create snapshot                                | `POST`   | `/projects/{project_id}/snapshots`               | [Create a snapshot](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#create-snapshot)        |
| Delete snapshot                                | `DELETE` | `/projects/{project_id}/snapshots/{snapshot_id}` | [Delete a snapshot](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#delete-snapshot)        |
| Get snapshot                                   | `GET`    | `/projects/{project_id}/snapshots/{snapshot_id}` | [Get and list snapshots](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#get-list)          |
| List snapshots                                 | `GET`    | `/projects/{project_id}/snapshots`               | [Get and list snapshots](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#get-list)          |
| Restore snapshot (create branch from snapshot) | `POST`   | `/projects/{project_id}/branches`                | [Restore from a snapshot](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#restore-snapshot) |

### <a id="endpoint-endpoints" />Endpoints (Computes and Read Replicas)

In the API, a compute is called an **endpoint**. For a conceptual overview, see [Computes and endpoints](https://docs.databricks.com/gcp/en/oltp/projects/computes-and-endpoints.md).

The following table maps UI concepts to their API equivalents:

| UI concept                               | API resource or field                                        | Documentation                                                                                            |
| ---------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| Primary compute                          | Endpoint with `endpoint_type: ENDPOINT_TYPE_READ_WRITE`      | [Manage computes](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md)                   |
| Read replica                             | Endpoint with `endpoint_type: ENDPOINT_TYPE_READ_ONLY`       | [Manage read replicas](https://docs.databricks.com/gcp/en/oltp/projects/manage-read-replicas.md)         |
| High availability                        | `group` field (`EndpointGroupSpec`) on endpoint spec         | [Manage high availability](https://docs.databricks.com/gcp/en/oltp/projects/manage-high-availability.md) |
| Compute identifiers (UID, Resource name) | `uid` and `name` (full resource path) on the Endpoint object | [Compute identifiers](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md#identifiers)   |

#### Available operations

| Operation       | Method   | Endpoint                                                              | Documentation                                                                                                                                                                                                                                                                                                         |
| --------------- | -------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Create endpoint | `POST`   | `/projects/{project_id}/branches/{branch_id}/endpoints`               | [Create a read replica](https://docs.databricks.com/gcp/en/oltp/projects/manage-read-replicas.md#create)                                                                                                                                                                                                              |
| Update endpoint | `PATCH`  | `/projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id}` | [Edit a compute](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md#edit-computes) / [Edit a read replica](https://docs.databricks.com/gcp/en/oltp/projects/manage-read-replicas.md#edit) / [Manage high availability](https://docs.databricks.com/gcp/en/oltp/projects/manage-high-availability.md) |
| Delete endpoint | `DELETE` | `/projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id}` | [Delete a read replica](https://docs.databricks.com/gcp/en/oltp/projects/manage-read-replicas.md#delete)                                                                                                                                                                                                              |
| Get endpoint    | `GET`    | `/projects/{project_id}/branches/{branch_id}/endpoints/{endpoint_id}` | [View computes](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md#view-comp)                                                                                                                                                                                                                        |
| List endpoints  | `GET`    | `/projects/{project_id}/branches/{branch_id}/endpoints`               | [View computes](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md#view-comp)                                                                                                                                                                                                                        |

Read-write endpoints cannot be deleted directly. Delete the parent branch to remove them. To avoid compute costs while keeping the branch, set `spec.disabled` to `true`. See [Disable or enable a compute](https://docs.databricks.com/gcp/en/oltp/projects/manage-computes.md#disable-compute).

### <a id="role-endpoints" />Roles

| Operation   | Method   | Endpoint                                                      | Documentation                                                                                                                                                                                                |
| ----------- | -------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| List roles  | `GET`    | `/projects/{project_id}/branches/{branch_id}/roles`           | [View Postgres roles](https://docs.databricks.com/gcp/en/oltp/projects/postgres-roles.md#view-roles)                                                                                                         |
| Create role | `POST`   | `/projects/{project_id}/branches/{branch_id}/roles`           | [Create an OAuth role](https://docs.databricks.com/gcp/en/oltp/projects/postgres-roles.md#oauth-role) \| [Create a password role](https://docs.databricks.com/gcp/en/oltp/projects/postgres-roles.md#create) |
| Get role    | `GET`    | `/projects/{project_id}/branches/{branch_id}/roles/{role_id}` | [View Postgres roles](https://docs.databricks.com/gcp/en/oltp/projects/postgres-roles.md#view-roles)                                                                                                         |
| Update role | `PATCH`  | `/projects/{project_id}/branches/{branch_id}/roles/{role_id}` | [Update a role](https://docs.databricks.com/gcp/en/oltp/projects/postgres-roles.md#update-role)                                                                                                              |
| Delete role | `DELETE` | `/projects/{project_id}/branches/{branch_id}/roles/{role_id}` | [Delete a role](https://docs.databricks.com/gcp/en/oltp/projects/manage-roles.md#delete)                                                                                                                     |

### <a id="snapshot-schedule-endpoints" />Backup schedule

A root branch has a single backup schedule. Only get and update are available. Update replaces the schedule's full set of cadences.

| Operation              | Method  | Endpoint                                                        | Documentation                                                                                                |
| ---------------------- | ------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Get backup schedule    | `GET`   | `/projects/{project_id}/branches/{branch_id}/snapshot-schedule` | [Create a backup schedule](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#snapshot-schedules) |
| Update backup schedule | `PATCH` | `/projects/{project_id}/branches/{branch_id}/snapshot-schedule` | [Create a backup schedule](https://docs.databricks.com/gcp/en/oltp/projects/snapshots.md#snapshot-schedules) |

> [!NOTE]
>
> Update is a long-running operation. Poll the returned operation until `done: true`. See [Long-running operations](https://docs.databricks.com/gcp/en/oltp/projects/api-usage.md#long-running-operations).

### <a id="catalog-endpoints" />Catalogs

| Operation                            | Method   | Endpoint                 | Documentation                                                                                                          |
| ------------------------------------ | -------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| Register database with Unity Catalog | `POST`   | `/catalogs`              | [Register a database](https://docs.databricks.com/gcp/en/oltp/projects/register-uc.md#register-a-database)             |
| Get catalog registration             | `GET`    | `/catalogs/{catalog_id}` | [Check registration status](https://docs.databricks.com/gcp/en/oltp/projects/register-uc.md#check-registration-status) |
| Delete catalog registration          | `DELETE` | `/catalogs/{catalog_id}` | [Unregister a database](https://docs.databricks.com/gcp/en/oltp/projects/register-uc.md#unregister-a-database)         |

> [!NOTE]
>
> Register and delete are long-running operations. Poll the returned operation until `done: true`. See [Long-running operations](https://docs.databricks.com/gcp/en/oltp/projects/api-usage.md#long-running-operations).
>
> Deleting a catalog registration does not drop the underlying Postgres database.

### <a id="synced-table-endpoints" />Synced Tables

| Operation           | Method   | Endpoint                      | Documentation                                                                                                  |
| ------------------- | -------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Create synced table | `POST`   | `/synced_tables`              | [Create a synced table](https://docs.databricks.com/gcp/en/oltp/projects/sync-tables.md#create-a-synced-table) |
| Get synced table    | `GET`    | `/synced_tables/{table_name}` | [Check sync status](https://docs.databricks.com/gcp/en/oltp/projects/sync-tables.md#check-sync-status)         |
| Delete synced table | `DELETE` | `/synced_tables/{table_name}` | [Delete a synced table](https://docs.databricks.com/gcp/en/oltp/projects/sync-tables.md#delete-a-synced-table) |

> [!NOTE]
>
> The `table_name` in the path uses the format `catalog.schema.table`.
>
> Create and delete are long-running operations. Poll the returned operation until `done: true`. See [Long-running operations](https://docs.databricks.com/gcp/en/oltp/projects/api-usage.md#long-running-operations).
>
> Deleting a synced table removes the Unity Catalog registration only. Drop the Postgres table separately to free up space.

### <a id="cdf-endpoints" />Change Data Feed

[Lakebase Change Data Feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md) (CDF) operations are scoped to a branch. For request and response details, see the CDF operations in the [Postgres API reference](https://docs.databricks.com/api/postgres/v1/postgres).

| Operation                | Method   | Documentation                                                                                                                    |
| ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Create CDF configuration | `POST`   | [Start the change data feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md#step-2-start-the-change-data-feed) |
| Get CDF status           | `GET`    | [Start the change data feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md#step-2-start-the-change-data-feed) |
| List CDF statuses        | `GET`    | [Start the change data feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md#step-2-start-the-change-data-feed) |
| Get CDF configuration    | `GET`    | [Start the change data feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md#step-2-start-the-change-data-feed) |
| Delete CDF configuration | `DELETE` | [Disable Lakebase CDF](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md#disable-lakebase-cdf)                    |

> [!NOTE]
>
> Create a CDF configuration to start a change data feed. You can also start a feed from the Lakebase UI. See [Start the change data feed](https://docs.databricks.com/gcp/en/oltp/projects/lakebase-cdf.md#step-2-start-the-change-data-feed).
>
> Deleting a CDF configuration permanently removes the configuration and its table mappings; the destination Delta tables in Unity Catalog are preserved.

### <a id="migration-endpoints" />Migrations

[Migrations](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md) are in [Beta](https://docs.databricks.com/gcp/en/release-notes/release-types.md). A migration is a workspace-level resource named `migrations/{migration_id}`, so its paths aren't nested under a project.

| Operation                       | Method   | Endpoint                                                                     | Documentation                                                                                                    |
| ------------------------------- | -------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Create migration                | `POST`   | `/migrations`                                                                | [Create a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#create-migration)            |
| Get migration                   | `GET`    | `/migrations/{migration_id}`                                                 | [Monitor a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#monitor-migration)          |
| List migrations                 | `GET`    | `/migrations`                                                                | [Monitor a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#monitor-migration)          |
| Update migration                | `PATCH`  | `/migrations/{migration_id}`                                                 | [Start a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#start-migration)              |
| Delete migration                | `DELETE` | `/migrations/{migration_id}`                                                 | [Delete or restore a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#delete-migration) |
| Undelete migration              | `POST`   | `/migrations/{migration_id}/undelete`                                        | [Delete or restore a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#delete-migration) |
| Assess migration                | `POST`   | `/migrations/{migration_id}/assess`                                          | [Review the assessment](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#review-assessment)        |
| Start migration                 | `POST`   | `/migrations/{migration_id}/start`                                           | [Start a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#start-migration)              |
| Get assessment                  | `GET`    | `/migrations/{migration_id}/assessments/{assessment_id}`                     | [Review the assessment](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#review-assessment)        |
| List assessments                | `GET`    | `/migrations/{migration_id}/assessments`                                     | [Review the assessment](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#review-assessment)        |
| Acknowledge assessment warnings | `POST`   | `/migrations/{migration_id}/assessments/{assessment_id}/acknowledgeWarnings` | [Review the assessment](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#review-assessment)        |

### <a id="credential-endpoints" />Database Credentials

| Operation                    | Method | Endpoint       | Documentation                                                                                                  |
| ---------------------------- | ------ | -------------- | -------------------------------------------------------------------------------------------------------------- |
| Generate database credential | `POST` | `/credentials` | [OAuth token authentication](https://docs.databricks.com/gcp/en/oltp/projects/authentication.md#db-identities) |

### <a id="operation-endpoints" />Operations

| Operation               | Method | Endpoint                                               | Documentation                                                                                            |
| ----------------------- | ------ | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| Get operation           | `GET`  | `/projects/{project_id}/operations/{operation_id}`     | [See example below](https://docs.databricks.com/gcp/en/oltp/projects/api-usage.md#get-operation-example) |
| Get migration operation | `GET`  | `/migrations/{migration_id}/operations/{operation_id}` | [Monitor a migration](https://docs.databricks.com/gcp/en/oltp/projects/migrations.md#monitor-migration)  |

### <a id="permissions-endpoints" />Permissions

Project ACL permissions use the [standard Databricks Permissions API](https://docs.databricks.com/api/workspace/permissions), not the `/api/2.0/postgres/` base path. Set the `request_object_type` to `database-projects` and `request_object_id` to your project ID (for example, `my-app`).

| Operation                   | Method  | Endpoint                                              | Documentation                                                                             |
| --------------------------- | ------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Get project permissions     | `GET`   | `/api/2.0/permissions/database-projects/{project_id}` | [Permissions API reference](https://docs.databricks.com/api/workspace/permissions/get)    |
| Update project permissions  | `PATCH` | `/api/2.0/permissions/database-projects/{project_id}` | [Permissions API reference](https://docs.databricks.com/api/workspace/permissions/update) |
| Replace project permissions | `PUT`   | `/api/2.0/permissions/database-projects/{project_id}` | [Permissions API reference](https://docs.databricks.com/api/workspace/permissions/set)    |

The grantable permission levels for Lakebase projects are `CAN_USE` and `CAN_MANAGE`. `CAN_CREATE` is an inherited level and cannot be set via the API. See [Permission levels](https://docs.databricks.com/gcp/en/oltp/projects/grant-permissions-programmatically.md#permission-levels).

For usage examples and CLI/SDK/Terraform equivalents, see [Grant permissions programmatically](https://docs.databricks.com/gcp/en/oltp/projects/grant-permissions-programmatically.md).

### <a id="get-operation-example" />Get operation

Check the status of a long-running operation by its resource name.

#### Python SDK

```python
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.postgres import Project, ProjectSpec

w = WorkspaceClient()

# Start an operation (example: create project)
operation = w.postgres.create_project(
    project=Project(spec=ProjectSpec(pg_version=17)),
    project_id="my-project",
)
print(f"Operation started: {operation.name()}")

# Wait for completion
result = operation.wait()
print(f"Operation completed: {result.name}")
```

#### Java SDK

```java
import com.databricks.sdk.WorkspaceClient;
import com.databricks.sdk.service.postgres.*;

WorkspaceClient w = new WorkspaceClient();

// Start an operation (example: create project)
CreateProjectOperation operation = w.postgres().createProject(
    new CreateProjectRequest()
        .setProjectId("my-project")
        .setProject(new Project()
            .setSpec(new ProjectSpec()
                .setPgVersion(17L)))
);
System.out.println("Operation started: " + operation.getName());

// Wait for completion
Project result = operation.waitForCompletion();
System.out.println("Operation completed: " + result.getName());
```

#### CLI

The CLI automatically waits for operations to complete by default. Use `--no-wait` to skip polling:

```bash
# Create project without waiting
databricks postgres create-project my-project --no-wait \
  --json '{"spec": {"pg_version": 17}}'

# Later, check the operation status using the operation name from the response
databricks postgres get-operation projects/my-project/operations/<operation-id>
```

#### curl

```bash
# Get operation status
curl -X GET "$WORKSPACE/api/2.0/postgres/projects/my-project/operations/<operation-id>" \
  -H "Authorization: Bearer ${DATABRICKS_TOKEN}" | jq
```

**Response format:**

```json
{
  "name": "projects/my-project/operations/<operation-id>",
  "done": true,
  "response": {
    "@type": "type.googleapis.com/databricks.postgres.v1.Project",
    "name": "projects/my-project",
    ...
  }
}
```

**Fields:**

* `done`: `false` while in progress, `true` when complete
* `response`: Contains the result when `done` is `true`
* `error`: Contains error details if operation failed

## <a id="common-patterns" />Common patterns

### <a id="resource-naming" />Resource naming

Resources follow a hierarchical naming pattern where child resources are scoped to their parent.

Projects use this format:

```
projects/{project_id}
```

Child resources like operations are nested under their parent project:

```
projects/{project_id}/operations/{operation_id}
```

This means you need the parent project ID to access a project's operations or other child resources. Migrations are workspace-level resources, so their operations use the migration ID instead.

**Resource IDs:**

When creating resources, you must provide a resource ID (like `my-app`) for the `project_id`, `branch_id`, or `endpoint_id` parameter. This ID becomes part of the resource path in API calls (such as `projects/my-app/branches/development`).

`role_id` and `database_id` identify API resources. `spec.postgres_role` and `spec.postgres_database` name the corresponding Postgres objects.

You can optionally provide a `display_name` to give your resource a more descriptive label. If you don't specify a display name, the system uses your resource ID as the display name.

> [!TIP]
>
> To locate a project in the Lakebase App, look for its display name in the projects list. If you didn't provide a custom display name when creating the project, search for your `project_id` (such as "my-app").

> [!NOTE]
>
> Resource IDs cannot be changed after creation.

**Requirements:**

* Must be 1-63 characters long
* Lowercase letters, digits, and hyphens only
* Cannot start or end with a hyphen
* Examples: `my-app`, `analytics-db`, `customer-123`

### <a id="long-running-operations" />Long-running operations (LROs)

Create, update, and delete operations return a `databricks.longrunning.Operation` object that provides a completion status.

**Example operation response:**

```json
{
  "name": "projects/my-project/operations/<operation-id>",
  "done": false
}
```

**Poll for completion using GetOperation:**

#### Python SDK

```python
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.postgres import Project, ProjectSpec

w = WorkspaceClient()

# Start an operation
operation = w.postgres.create_project(
    project=Project(spec=ProjectSpec(pg_version=17)),
    project_id="my-project",
)

# Wait for completion
result = operation.wait()
print(f"Operation completed: {result.name}")
```

#### Java SDK

```java
import com.databricks.sdk.WorkspaceClient;
import com.databricks.sdk.service.postgres.*;

WorkspaceClient w = new WorkspaceClient();

// Start an operation
CreateProjectOperation operation = w.postgres().createProject(
    new CreateProjectRequest()
        .setProjectId("my-project")
        .setProject(new Project()
            .setSpec(new ProjectSpec()
                .setPgVersion(17L)))
);

// Wait for completion
Project result = operation.waitForCompletion();
System.out.println("Operation completed: " + result.getName());
```

#### CLI

The CLI automatically waits for operations to complete by default. Use `--no-wait` to return immediately:

```bash
databricks postgres create-project my-project --no-wait \
  --json '{"spec": {"pg_version": 17}}'
```

#### curl

```bash
# Poll the operation
curl "$WORKSPACE/api/2.0/postgres/projects/my-project/operations/<operation-id>" \
  -H "Authorization: Bearer ${DATABRICKS_TOKEN}" | jq '.done'
```

Poll every few seconds until `done` is `true`.

### <a id="update-masks" />Update masks

Update operations require an `update_mask` parameter specifying which fields to modify. This prevents accidentally overwriting unrelated fields.

**Format differences:**

| Method     | Format              | Example                                                   |
| ---------- | ------------------- | --------------------------------------------------------- |
| REST API   | Query parameter     | `?update_mask=spec.display_name`                          |
| Python SDK | FieldMask object    | `update_mask=FieldMask(field_mask=["spec.display_name"])` |
| CLI        | Positional argument | `update-project NAME spec.display_name`                   |

### <a id="error-handling" />Error handling

The Lakebase API returns standard HTTP status codes.

#### <a id="conflicting-operations" />409: Conflicting operations

Lakebase can return a `409 Conflict` error for several reasons:

* An internal maintenance operation is in progress on the project.
* The project has reached its concurrent operations limit.
* Your own API requests overlap. For example, creating a branch before a previous branch creation has finished.

**What it means:**

Lakebase sometimes schedules maintenance operations on projects. If a client request arrives while one of these operations is in progress, Lakebase rejects the new request with a `409 Conflict` error. You may also get that response when the project is at capacity or your API calls overlap.

This is expected behavior. Clients should be prepared to retry requests when this error occurs.

**What to do:**

Retry the request. When the internal operation completes or capacity frees up, Lakebase accepts new requests for the project.

Use exponential backoff for retries: wait a short interval before the first retry, then double the wait on each subsequent attempt. A starting interval of 100 milliseconds with a maximum of 30 seconds is a reasonable default.

##### Python SDK

```python
import time
from databricks.sdk import WorkspaceClient
from databricks.sdk.errors import ResourceConflict
from databricks.sdk.service.postgres import Branch, BranchSpec

w = WorkspaceClient()

def retry_on_conflict(fn, max_attempts=5, base_delay=0.1):
    """Retry a Lakebase API call when a conflicting operation is in progress."""
    for attempt in range(max_attempts):
        try:
            return fn()
        except ResourceConflict:
            if attempt == max_attempts - 1:
                raise
            wait = base_delay * (2 ** attempt)
            print(f"Conflicting operation in progress. Retrying in {wait}s...")
            time.sleep(wait)

# Example: create a branch with retry
branch = retry_on_conflict(
    lambda: w.postgres.create_branch(
        parent="projects/my-project",
        branch=Branch(spec=BranchSpec(no_expiry=True)),
        branch_id="my-branch",
    ).wait()
)
```

##### curl

```bash
# Retry with exponential backoff on 409 responses
retry_on_conflict() {
  local cmd=("$@")
  local max_attempts=5
  local delay=0.1
  local attempt=0

  while [ $attempt -lt $max_attempts ]; do
    response=$(curl -s -w "\n%{http_code}" "${cmd[@]}")
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" -ne 409 ]; then
      echo "$body"
      return 0
    fi

    attempt=$((attempt + 1))
    if [ $attempt -eq $max_attempts ]; then
      echo "Max retries reached. Last response: $body" >&2
      return 1
    fi

    echo "Conflicting operation in progress. Retrying in ${delay}s..." >&2
    sleep "$delay"
    delay=$((delay * 2))
  done
}

# Example: create a branch with retry
retry_on_conflict \
  -X POST "$WORKSPACE/api/2.0/postgres/projects/my-project/branches?branch_id=my-branch" \
  -H "Authorization: Bearer ${DATABRICKS_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"spec": {"no_expiry": true}}'
```

> [!NOTE]
>
> A `409 Conflict` on a Lakebase API request means the request was not accepted, not that it was applied. Always verify the resource state after a successful retry by calling the corresponding `GET` endpoint.

## <a id="resources" /> SDKs and infrastructure-as-code

* [Python SDK](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/postgres/postgres.html)
* [Java SDK](https://javadoc.io/doc/com.databricks/databricks-sdk-java/latest/index.html)
* [Go SDK](https://pkg.go.dev/github.com/databricks/databricks-sdk-go@v0.96.0/service/postgres#PostgresInterface)
* [Declarative Automation Bundles](https://docs.databricks.com/gcp/en/dev-tools/bundles/index.md)
* [Manage Lakebase projects with Bundles](https://docs.databricks.com/gcp/en/oltp/projects/manage-with-bundles.md)
* [Terraform provider](https://registry.terraform.io/providers/databricks/databricks/latest/docs/resources/postgres_project)
* [Get started with Terraform for Lakebase](https://docs.databricks.com/gcp/en/oltp/projects/automate-with-terraform.md)
