Skip to content

Commit 44f03b7

Browse files
docs: update Management API SDK documentation to match latest README (#7382)
1 parent f0ecc9f commit 44f03b7

File tree

1 file changed

+158
-92
lines changed

1 file changed

+158
-92
lines changed

content/250-postgres/100-introduction/235-management-api-sdk.mdx

Lines changed: 158 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,101 @@
11
---
22
title: 'Management API SDK'
33
metaTitle: 'Prisma Postgres: Management API SDK'
4-
metaDescription: 'A TypeScript SDK for the Prisma Data Platform Management API with built-in OAuth authentication and automatic token refresh.'
4+
metaDescription: 'A TypeScript SDK for the Prisma Data Platform Management API. Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh.'
55
---
66

77
## Overview
88

9-
The [`@prisma/management-api-sdk`](https://www.npmjs.com/package/@prisma/management-api-sdk) is a TypeScript SDK for the [Prisma Data Platform Management API](/postgres/introduction/management-api) with built-in OAuth authentication and automatic token refresh.
9+
The [`@prisma/management-api-sdk`](https://www.npmjs.com/package/@prisma/management-api-sdk) is a TypeScript SDK for the [Prisma Data Platform Management API](/postgres/introduction/management-api). Use the simple client for direct API access, or the full SDK with built-in OAuth authentication and automatic token refresh.
10+
11+
Based on the [public OpenAPI 3.1 specification](https://api.prisma.io/v1/swagger-editor).
1012

1113
## Installation
1214

1315
```terminal
1416
npm install @prisma/management-api-sdk
1517
```
1618

17-
## Quick start
19+
## Basic usage
20+
21+
For usage with an existing access or [service token](/postgres/introduction/management-api#service-tokens).
22+
23+
### Making API calls
24+
25+
The client provides fully typed methods for all API endpoints:
26+
27+
```typescript
28+
import { createManagementApiClient } from '@prisma/management-api-sdk'
29+
30+
const client = createManagementApiClient({
31+
token: 'your-access-token',
32+
})
33+
34+
// List workspaces
35+
const { data: workspaces, error } = await client.GET('/v1/workspaces')
36+
37+
// Get a specific project
38+
const { data: project } = await client.GET('/v1/projects/{id}', {
39+
params: { path: { id: 'project-id' } },
40+
})
41+
42+
// Create a new project
43+
const { data: newProject } = await client.POST('/v1/workspaces/{workspaceId}/projects', {
44+
params: { path: { workspaceId: 'workspace-id' } },
45+
body: { name: 'My New Project' },
46+
})
47+
48+
// Create a new database
49+
const { data: newDatabase } = await client.POST('/v1/projects/{projectId}/databases', {
50+
params: { path: { projectId: 'project-id' } },
51+
body: {
52+
name: 'my-new-db-instance',
53+
region: 'us-east-1',
54+
isDefault: true,
55+
},
56+
})
57+
58+
// Delete a database
59+
const { error: deleteError } = await client.DELETE('/v1/databases/{databaseId}', {
60+
params: { path: { databaseId: 'database-id' } },
61+
})
62+
```
63+
64+
### Customizing the client
65+
66+
You can override any `ClientOptions` from `openapi-fetch`, including `baseUrl`, `headers`, and other fetch options:
67+
68+
```typescript
69+
import { createManagementApiClient } from '@prisma/management-api-sdk'
70+
71+
// Override baseUrl and add custom headers
72+
const client = createManagementApiClient({
73+
token: 'your-access-token',
74+
baseUrl: 'https://api.example.com',
75+
headers: {
76+
'X-Custom-Header': 'value',
77+
},
78+
})
79+
```
80+
81+
:::note
82+
83+
If you provide both `token` and `headers.Authorization`, the `headers.Authorization` takes precedence. The `baseUrl` defaults to `https://api.prisma.io` if not provided.
84+
85+
:::
86+
87+
## Advanced usage
88+
89+
For applications that need [OAuth authentication](/postgres/introduction/management-api#oauth-20-authentication), automatic token refresh, and token storage management, use the full SDK.
90+
91+
### OAuth authentication flow
92+
93+
The SDK uses OAuth 2.0 with PKCE for secure authentication. The flow is stateless - you're responsible for storing the `state` and `verifier` between the login URL generation and callback handling.
94+
95+
#### 1. Create the SDK instance
1896

1997
```typescript
20-
import { createManagementAPI, type TokenStorage } from '@prisma/management-api-sdk'
98+
import { createManagementApiSdk, type TokenStorage } from '@prisma/management-api-sdk'
2199

22100
// Implement token storage for your environment
23101
const tokenStorage: TokenStorage = {
@@ -33,22 +111,15 @@ const tokenStorage: TokenStorage = {
33111
},
34112
}
35113

36-
// Create the API instance
37-
const api = createManagementAPI({
114+
// Create the SDK instance
115+
const api = createManagementApiSdk({
38116
clientId: 'your-oauth-client-id',
39117
redirectUri: 'https://your-app.com/auth/callback',
40118
tokenStorage,
41119
})
42-
43-
// Use the typed API client
44-
const { data, error } = await api.client.GET('/v1/workspaces')
45120
```
46121

47-
## Authentication flow
48-
49-
The SDK uses OAuth 2.0 with PKCE for secure authentication. The flow is stateless - you're responsible for storing the state and verifier between the login URL generation and callback handling.
50-
51-
### 1. Initiate login
122+
#### 2. Initiate login
52123

53124
Generate the OAuth login URL. The returned `state` and `verifier` must be stored (e.g., in a session or cookie) for use when handling the callback:
54125

@@ -69,9 +140,9 @@ sessionStorage.setItem('oauth-verifier', verifier)
69140
window.location.href = url
70141
```
71142

72-
### 2. Handle the callback
143+
#### 3. Handle the callback
73144

74-
When the user is redirected back to your app, retrieve the stored state and verifier and pass them to `handleCallback`. On success, tokens are automatically stored via your `tokenStorage` implementation:
145+
When the user is redirected back to your app, retrieve the stored `state` and `verifier` and pass them to `handleCallback`. On success, tokens are automatically stored via your `tokenStorage` implementation:
75146

76147
```typescript
77148
// In your callback route handler
@@ -101,7 +172,7 @@ try {
101172
}
102173
```
103174

104-
### 3. Make API calls
175+
#### 4. Make API calls
105176

106177
The client automatically includes authentication headers and refreshes tokens when they expire:
107178

@@ -119,71 +190,27 @@ const { data: newProject } = await api.client.POST('/v1/workspaces/{workspaceId}
119190
params: { path: { workspaceId: 'workspace-id' } },
120191
body: { name: 'My Project' },
121192
})
122-
```
123-
124-
### 4. Logout
125-
126-
```typescript
127-
await api.logout() // Clears stored tokens
128-
```
129-
130-
## API reference
131-
132-
### `createManagementAPI(config)`
133193

134-
Creates a Management API instance with authentication handling.
135-
136-
```typescript
137-
import { createManagementAPI } from '@prisma/management-api-sdk'
138-
139-
const api = createManagementAPI({
140-
clientId: 'your-oauth-client-id',
141-
redirectUri: 'https://your-app.com/auth/callback',
142-
tokenStorage,
143-
apiBaseUrl: 'https://api.prisma.io', // optional
144-
authBaseUrl: 'https://auth.prisma.io', // optional
145-
})
146-
```
147-
148-
Returns an object with:
149-
150-
| Property | Description |
151-
|----------|-------------|
152-
| `client` | The typed API client for making requests |
153-
| `getLoginUrl(options)` | Generate OAuth login URL with specified scope |
154-
| `handleCallback(options)` | Handle OAuth callback and store tokens via tokenStorage |
155-
| `logout()` | Clear stored tokens |
156-
157-
### `createManagementAPIClient(options)`
158-
159-
Creates a raw API client without authentication handling. Useful if you want to manage authentication yourself.
160-
161-
```typescript
162-
import { createManagementAPIClient } from '@prisma/management-api-sdk'
163-
164-
const client = createManagementAPIClient({
165-
baseUrl: 'https://api.prisma.io',
166-
headers: {
167-
Authorization: `Bearer ${myToken}`,
194+
// Create a new database
195+
const { data: newDatabase } = await api.client.POST('/v1/projects/{projectId}/databases', {
196+
params: { path: { projectId: 'project-id' } },
197+
body: {
198+
name: 'production',
199+
region: 'us-east-1',
200+
isDefault: true,
168201
},
169202
})
170203

171-
const { data } = await client.GET('/v1/workspaces')
204+
// Delete a database
205+
const { error: deleteError } = await api.client.DELETE('/v1/databases/{databaseId}', {
206+
params: { path: { databaseId: 'database-id' } },
207+
})
172208
```
173209

174-
### Configuration options
210+
#### 5. Logout
175211

176212
```typescript
177-
type ManagementAPIClientConfig = {
178-
// Required
179-
clientId: string // OAuth client ID
180-
redirectUri: string // OAuth redirect URI
181-
tokenStorage: TokenStorage
182-
183-
// Optional (with defaults)
184-
apiBaseUrl?: string // Default: 'https://api.prisma.io'
185-
authBaseUrl?: string // Default: 'https://auth.prisma.io'
186-
}
213+
await api.logout() // Clears stored tokens
187214
```
188215

189216
### Token storage interface
@@ -210,9 +237,7 @@ type Tokens = {
210237
}
211238
```
212239
213-
## Examples
214-
215-
### VS Code extension
240+
#### Example: VS Code Extension
216241
217242
```typescript
218243
const tokenStorage: TokenStorage = {
@@ -240,7 +265,7 @@ const tokenStorage: TokenStorage = {
240265
}
241266
```
242267

243-
### Node.js CLI
268+
#### Example: Node.js CLI
244269

245270
```typescript
246271
import { readFile, writeFile, unlink } from 'node:fs/promises'
@@ -267,7 +292,7 @@ const tokenStorage: TokenStorage = {
267292
}
268293
```
269294

270-
### Stateless web server
295+
#### Example: Stateless Web Server
271296

272297
For stateless web servers (serverless, load-balanced), store the PKCE state in an encrypted cookie or database:
273298

@@ -301,18 +326,56 @@ app.get('/callback', async (req, res) => {
301326
})
302327
```
303328

304-
## TypeScript types
329+
### Automatic token refresh
305330

306-
The SDK exports all API types generated from the OpenAPI spec:
331+
The SDK automatically handles token refresh when a refresh token is available (requires `offline_access` scope):
332+
333+
- When a request returns 401, the SDK refreshes the access token using the refresh token
334+
- Concurrent requests during refresh are queued and resolved once refresh completes
335+
- If refresh fails due to an invalid refresh token, tokens are cleared and `AuthError` is thrown with `refreshTokenInvalid: true`
336+
- If no refresh token is available, an `AuthError` is thrown with the message "No refresh token available. Please log in again."
337+
338+
## API reference
339+
340+
### `createManagementApiClient(options)`
341+
342+
Creates a raw API client without authentication handling. Useful if you want to manage authentication yourself or use a service token.
343+
344+
**Parameters:**
345+
346+
- `options.token?: string` - Access token (automatically converted to `Authorization: Bearer ${token}` header)
347+
- `options.baseUrl?: string` - Base URL for API requests (defaults to `https://api.prisma.io`)
348+
- `options.headers?: Record<string, string>` - Additional headers
349+
- Other `ClientOptions` from `openapi-fetch` are also supported
350+
351+
**Returns:** A typed API client for making requests.
352+
353+
### `createManagementApiSdk(config)`
354+
355+
Creates a Management API SDK instance with OAuth authentication and automatic token refresh.
356+
357+
**Parameters:**
307358

308359
```typescript
309-
import type { paths, components } from '@prisma/management-api-sdk'
360+
type ManagementApiClientConfig = {
361+
// Required
362+
clientId: string // OAuth client ID
363+
redirectUri: string // OAuth redirect URI
364+
tokenStorage: TokenStorage
310365

311-
// Access response types
312-
type Workspace = components['schemas']['Workspace']
313-
type Project = components['schemas']['Project']
366+
// Optional (with defaults)
367+
apiBaseUrl?: string // Default: 'https://api.prisma.io'
368+
authBaseUrl?: string // Default: 'https://auth.prisma.io'
369+
}
314370
```
315371
372+
**Returns:** An object with:
373+
374+
- `client` - The typed API client for making requests
375+
- `getLoginUrl(options)` - Generate OAuth login URL with specified scope
376+
- `handleCallback(options)` - Handle OAuth callback and store tokens via `tokenStorage`
377+
- `logout()` - Clear stored tokens
378+
316379
## Error handling
317380
318381
The SDK exports two error classes:
@@ -352,7 +415,7 @@ Thrown for network-related errors. Includes the original error as `cause` for de
352415
import { FetchError } from '@prisma/management-api-sdk'
353416

354417
try {
355-
const { data } = await api.client.GET('/v1/workspaces')
418+
const { data } = await client.GET('/v1/workspaces')
356419
} catch (error) {
357420
if (error instanceof FetchError) {
358421
console.error('Network error:', error.message)
@@ -361,11 +424,14 @@ try {
361424
}
362425
```
363426

364-
## Automatic token refresh
427+
## TypeScript types
365428

366-
The SDK automatically handles token refresh when a refresh token is available (requires `offline_access` scope):
429+
The SDK exports all API types generated from the OpenAPI spec:
367430

368-
- When a request returns `401`, the SDK refreshes the access token using the refresh token
369-
- Concurrent requests during refresh are queued and resolved once refresh completes
370-
- If refresh fails due to an invalid refresh token, tokens are cleared and `AuthError` is thrown with `refreshTokenInvalid: true`
371-
- If no refresh token is available, an `AuthError` is thrown with the message `"No refresh token available. Please log in again."`
431+
```typescript
432+
import type { paths, components } from '@prisma/management-api-sdk'
433+
434+
// Access response types
435+
type Workspace = components['schemas']['Workspace']
436+
type Project = components['schemas']['Project']
437+
```

0 commit comments

Comments
 (0)