Skip to main content

开始使用 Prisma 管理 API

15 min

概述

¥Overview

本指南将引导你设置一个基本的 TypeScript 项目,该项目使用 Prisma Postgres 管理 API 创建带有 Prisma Postgres 数据库的新 Prisma 控制台项目,并打印出所有连接详细信息。

¥This guide walks you through setting up a basic TypeScript project that uses the Prisma Postgres Management API to create a new Prisma Console project with a Prisma Postgres database, and print out all connection details.

你将通过 服务令牌 进行身份验证,设置环境,并运行脚本与 API 交互。

¥You'll authenticate via a service token, set up your environment, and run a script to interact with the API.

OpenApi

API 参考也可通过 OpenAPI 3.1.spec 获取。

¥The API reference is also available via an OpenAPI 3.1. spec.

先决条件

¥Prerequisites

  • 已安装 Node.js 和 npm

    ¥Node.js and npm installed

  • 账户

    ¥A account

1. 在 Prisma 控制台中创建服务令牌

¥ Create a service token in Prisma Console

首先,你需要创建一个服务令牌才能访问管理 API:

¥First, you need to create a service token to be able to access the Management API:

  1. 打开

    ¥Open the

  2. 导航到工作区的“集成”页面

    ¥Navigate to the Integrations page of your workspace

  3. 点击“生成集成令牌”

    ¥Click Generate integration token

  4. 复制并安全保存生成的服务令牌,你将在步骤 2.2 中使用它。

    ¥Copy and save the generated service token securely, you'll use it in step 2.2.

2. 设置项目目录

¥ Set up your project directory

2.1.创建一个基本的 TypeScript 项目

¥2.1. Create a basic TypeScript project

打开终端并运行以下命令:

¥Open your terminal and run the following commands:

mkdir management-api-demo
cd management-api-demo

接下来,初始化 npm 并安装使用 TypeScript 所需的依赖:

¥Next, initialize npm and install dependencies required for using TypeScript:

npm init -y
npm install tsx typescript @types/node --save-dev
touch index.ts

现在,你已拥有一个可以使用 npx tsx index.ts 执行的 index.ts 文件。它目前为空,你将在步骤 3 中开始编写代码。

¥You now have an index.ts file that you can execute with npx tsx index.ts. It's still empty, you'll start writing code in step 3.

2.2.配置服务令牌环境变量

¥2.2. Configure service token environment variable

创建你的 .env 文件:

¥Create your .env file:

touch .env

接下来,安装 dotenv 库以从 .env 文件加载环境变量:

¥Next, install the dotenv library for loading environment variables from the .env file:

npm install dotenv

最后,将你的服务令牌(来自步骤 1)添加到 .env

¥Finally, add your service token (from step 1.) to .env:

PRISMA_SERVICE_TOKEN="ey..."

2.3.为 HTTP 请求安装 axios

¥2.3. Install the axios library for HTTP request

你将使用 axios 作为 HTTP 客户端与 Management API 交互。按如下方式安装:

¥You're going to use axios as your HTTP client to interact with the Management API. Install it as follows:

npm install axios

一切就绪,让我们编写一些代码来创建项目并配置 Prisma Postgres 数据库!

¥You're all set, let's write some code to create a project and provision a Prisma Postgres database!

3. 使用以下代码以编程方式创建新项目数据库

¥ Programmatically create a new project with a database

将以下代码粘贴到 index.ts 中:

¥Paste the following code into index.ts:

import axios from 'axios';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const API_URL = 'https://api.prisma.io/v1';
const SERVICE_TOKEN = process.env.PRISMA_SERVICE_TOKEN;

if (!SERVICE_TOKEN) {
throw new Error('PRISMA_SERVICE_TOKEN is not set in the environment');
}

// Set HTTP headers to be used in this script
const headers = {
Authorization: `Bearer ${SERVICE_TOKEN}`,
'Content-Type': 'application/json',
};

async function main() {
// Create a new project in your Prisma Console workspace
const projectName = `demo-project-${Date.now()}`;
const region = 'us-east-1';
const createProjectRes = await axios.post(
`${API_URL}/projects`,
{ name: projectName, region },
{ headers }
);
const project = createProjectRes.data;
console.log('Created project: \n', project);

// Log the database details
const apiKeys = project.databases[0].apiKeys || [];
for (const key of apiKeys) {
console.log(`\nDatabase details`);
console.log(`- ID: ${key.id}`);
console.log(`- Created at: ${key.createdAt}`);
console.log(`- API key: ${key.apiKey}`);
console.log(`- Prisma Postgres connection string: ${key.connectionString}`);

if (key.ppgDirectConnection) {
console.log(`- Direct TCP connection: ${key.ppgDirectConnection.host}`);
console.log(` - Host: ${key.ppgDirectConnection.host}`);
console.log(` - Username: ${key.ppgDirectConnection.user}`);
console.log(` - Password: ${key.ppgDirectConnection.pass}`);
}
}
}

main().catch((e) => {
console.error(e.response?.data || e);
process.exit(1);
});

你可以使用以下命令运行脚本:

¥You can run your script with the following command:

npx tsx index.ts
Show CLI results
Created project: 
{
createdAt: '2025-07-09T11:52:15.341Z',
id: 'cmcvwftgs00v5zq0vh3kp7pms',
name: 'demo-project-1752061932800',
databases: [
{
createdAt: '2025-07-09T11:52:15.341Z',
id: 'cmcvwftgs00v1zq0v0qrtrg8t',
name: 'demo-project-1752061932800',
connectionString: 'prisma+postgres://accelerate.prisma-data.net/?api_key=<api_key>',
region: 'us-east-1',
status: 'ready',
apiKeys: [Array],
isDefault: true
}
]
}

Database details
- ID: cmcvwftgs00v2zq0vj3v0104j
- Created at: 2025-07-09T11:52:15.341Z
- API key: ey...<actual_api_key>
- Prisma Postgres connection string: prisma+postgres://accelerate.prisma-data.net/?api_key=ey...<actual_api_key>
- Direct TCP connection: db.prisma.io:5432
- Host: db.prisma.io:5432
- Username: <username>
- Password: <password>

该命令的输出应与上面的输出类似。

¥Your output of the command should look similar to the output above.

结论

¥Conclusion

现在你已设置好一个 TypeScript 项目,该项目可与 Prisma Management API 交互,创建新项目和数据库,并打印出所有连接字符串。你可以扩展此脚本以管理更多资源或使用管理 API 自动执行其他任务。

¥You have now set up a TypeScript project that interacts with the Prisma Management API, creates a new project and database, and prints out all connection strings. You can extend this script to manage more resources or automate other tasks using the Management API.


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!