## Introduction

This guide walks you through how to use the Prisma Postgres Management API, to power experiences like the [`npx create-db`](https://create-db.prisma.io/) command.

You'll learn how to provision a Prisma Postgres database on your workspace as a partner, and how to transfer it to another user's workspace so they can "claim" the database. We'll cover how the process is secured using OAuth2, and by the end, you'll understand the full flow and how to integrate it into your own product experience.

This guide references the actual implementation in the `npx create-db` CLI and Cloudflare Workers as real world examples. The repo for the `npx create-db` is [here](https://github.com/prisma/create-db), which can be used as a reference for how to use the Management API in your own projects.

:::note How does this fit into your app?
The two Cloudflare Workers in this guide are just reference examples. You would typically build this logic into your own backend or serverless functions.

Similarly, the `npx create-db` CLI is a simple demo. In your product, you can trigger the same API calls from your own UI or onboarding flows to create a seamless experience for your users.
:::

## Core concepts

Before diving into implementation, let's clarify the main concepts involved in the Management API integration:

- **Management API**: A set of endpoints that allow you to programmatically provision and manage Prisma Postgres databases.
- **Projects vs Databases**: A project is a container that can hold multiple databases. You can use this to organize databases you create e.g. by user. Projects can then be transferred to users, including all databases they contain.
- **Authentication**: All API requests require authentication. As a partner, you authenticate provisioning calls with a service token for your workspace, and use OAuth 2 to obtain an access token for the user during the claim flow.
- **Tokens**: There are two main types of tokens:
  - **Service token**: Issued to your partner integration, scoped to provision and manage databases on your own workspace.
  - **OAuth 2 access token**: Obtained via OAuth 2 when a user authenticates with your app; it is scoped to the user's workspace and used to transfer project/database ownership to that workspace.
  
## How to become a partner

To use the Prisma Postgres Management API, you first need to set up as a partner:

1. **Request access to the Management API**: Contact the Prisma team from the [Prisma Partners page](https://www.prisma.io/partners) to request access to the Management API. You will be guided through the onboarding process.
2. **Obtain OAuth credentials**: You can obtain your OAuth credentials in the [Prisma Console](https://console.prisma.io). See the [next section](#get-oauth-credentials) for details.

For a complete list of available endpoints and details on request/response formats, see the [Prisma Management API documentation](/postgres/introduction/management-api).

## Get OAuth credentials

To obtain a client ID and client secret, you need go through this flow:

1. Open the [Prisma Console](https://console.prisma.io).
1. Click the 🧩 **Integrations** tab in the sidenav.
1. In the **Published Applications** section, click **New Application** button to start the flow for creating a new OAuth app.
1. Enter a **Name**, **Description** and **Callback URL** for your OAuth app.
1. Click **Continue**.

On the next screen, you can access and save the client ID and client secret for your OAuth app.

## Provisioning a database as a Partner

To provision a new Prisma Postgres database for your users as a partner, follow these steps:

1. **Gather required information**: Prepare the necessary details for provisioning, such as region, database name, and any other options your application requires. This information may come from user input or be determined by your application logic.
2. **Authenticate your integration**: Use your service token to authenticate API requests from your backend. This token authenticates your app as an approved partner.
3. **Send a database provisioning request**: Make a `POST` request to the Management API endpoint to create a new project with a default database. For example:
    ```ts
    const prismaResponse = await fetch('https://api.prisma.io/v1/projects', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer <YOUR_SERVICE_TOKEN>`,
      },
      body: JSON.stringify({ region, name }),
    });
    ```
4. **Handle the response**: If successful, the API will return the new project's details, including database connection strings and a `project_id`. Store these securely and display them to your user as needed.
5. **(Optional) Store project metadata**: You may want to associate the `project_id` with your user in your own database for future reference.

## Database claim flow

Once a database is provisioned, you may want to transfer ownership to your user at a later point so they can manage it in their own Prisma workspace and go beyond the free database usage limits. This is done via the claim flow, which consists of three main steps:

### Overview: How the claim flow works

When a user wants to claim a database, your app will:

1. Trigger the OAuth2 flow, redirecting the user to Prisma Auth. This is necessary, so your app will have the permissions to transfer the database into the user's workspace.
2. The user authenticates and selects a workspace.
3. Your backend receives an authorization code, exchanges it for a user access token, and calls the Management API transfer endpoint with both your integration token and the user's token.

This ensures the transfer is secure and only the intended user can claim the database.

### 1. Triggering the claim flow

When your user wants to take ownership of a database you provisioned for them, they need to transfer it to their own Prisma Postgres workspace. This gives them full control over it.

To initiate this process, provide a button or link in your app (e.g., "Claim Database" or "Transfer to My Workspace"). When clicked, your backend should:

- Generate a secure `state` value to track the session and prevent CSRF attacks.
- Construct an OAuth2 authorization URL with your client ID, redirect URI, and required scopes.
- Redirect the user to this URL to begin the authentication flow.

Example:

```ts
const authParams = new URLSearchParams({
  client_id: YOUR_CLIENT_ID,
  redirect_uri: 'https://your-app.com/auth/callback', // Your callback endpoint
  response_type: 'code',
  scope: 'workspace:admin', // The scope of the OAuth2 authorization
  state: generateState(), // Securely track the session
});
const authUrl = `https://auth.prisma.io/authorize?${authParams.toString()}`;
// Redirect the user to authUrl
```

### 2. Authenticating the user

The user will be prompted to log in (if not already authenticated) and select the workspace where they want to claim the database. After successful authentication and workspace selection, Prisma Auth will redirect back to your callback endpoint with a `code` and `state` (and, in some cases, a `project_id`).

### 3. Finishing the claim flow

Your backend should now:

1. **Exchange the authorization code for a user access token**:

```ts
const tokenResponse = await fetch('https://auth.prisma.io/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: code, // The code received from the callback
    redirect_uri: 'https://your-app.com/auth/callback', // Must match the redirect_uri used in step 1
    client_id: YOUR_CLIENT_ID,
    client_secret: YOUR_CLIENT_SECRET,
  }).toString(),
});
const tokenData = await tokenResponse.json();
```

2. **Call the Management API transfer endpoint** to move the project to the selected workspace. You will need the `project_id` and the user's access token:

```ts
const transferResponse = await fetch(`https://api.prisma.io/v1/projects/${project_id}/transfer`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${PRISMA_SERVICE_TOKEN}`,
  },
  body: JSON.stringify({ recipientAccessToken: tokenData.access_token }),
});
```

If the transfer is successful, the database is now owned by the user's workspace.

## Conclusion

By following this guide, you have learned how to:

- Set up as a Prisma Postgres Partner and obtain the necessary credentials
- Provision a new database for your users using the Management API
- Implement a secure claim flow that allows users to claim ownership of a database in their own workspace using OAuth2

This flow enables you to integrate Prisma Postgres provisioning and transfer seamlessly into your own product, providing a smooth onboarding experience for your users.

For further details, see the [create-db](https://github.com/prisma/create-db) repo for a reference implementation, or consult the [Prisma Management API documentation](/postgres/introduction/management-api).
---

# Set up Supabase with Accelerate Connection Pool