> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # registerApiRoute() `registerApiRoute()` 函数可创建与 Mastra 服务器集成的自定义 HTTP 路由。路由可包含 OpenAPI 元数据,以显示在 Swagger UI 文档中。 ## 导入 ```typescript import { registerApiRoute } from '@mastra/core/server' ``` ## 参数 ### path 路由的 URL 路径。支持使用 `:param` 语法定义路径参数。 ```typescript registerApiRoute("/items/:itemId", { ... }) ``` 自定义路由路径不能以服务器配置的 `apiPrefix`(默认值为 `/api`)开头,因为该前缀保留给内置的 Mastra 路由。若设置了自定义 `apiPrefix`,则仅该前缀会被保留。例如,当 `apiPrefix: '/mastra/api'` 时,允许使用 `/api/my-endpoint` 这样的路径。 > **注意:** 默认的 auth 配置会保护 `/api/*`,并将 `/api`、`/api/auth/*` 视为公开路径。更改 `apiPrefix` 后,这些默认值将不再匹配,内置路由也会落在受保护模式之外。请更新 `server.auth.protected` 和 `server.auth.public` 以引用新前缀,并更新所有访问 `/api/*` 的客户端代码(包括 `MastraClient` 的 `apiPrefix`)。 ### 选项 **method** (`'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'`): 路由的 HTTP 方法 **handler** (`Handler`): 接收 Hono Context 的路由处理函数。请使用 handler 或 createHandler 中的一个,不能同时使用。 **createHandler** (`({ mastra }: { mastra: Mastra }) => Promise`): 接收 Mastra 实例并返回路由处理函数的异步工厂。它会在服务器启动时运行一次,因此可执行一次性设置。请使用 handler 或 createHandler 中的一个,不能同时使用。 **middleware** (`MiddlewareHandler | MiddlewareHandler[]`): 路由专用的中间件函数 **cors** (`CorsOptions`): 路由专用的 CORS 配置。当某个自定义路由需要与 server.cors 不同的跨域策略时使用此项。 **openapi** (`DescribeRouteOptions`): 用于 Swagger UI 文档的 OpenAPI 元数据 ## OpenAPI 选项 `openapi` 属性接受来自 [hono-openapi](https://github.com/honojs/middleware/tree/main/packages/openapi) 的标准 OpenAPI 3.1 操作字段。没有 `openapi` 属性的路由不会包含在 Swagger UI 中。 **summary** (`string`): 操作的简短摘要 **description** (`string`): 操作的详细描述 **tags** (`string[]`): 用于在 Swagger UI 中分组的标签。未指定时默认为 \['custom']。 **deprecated** (`boolean`): 将操作标记为已弃用 **parameters** (`ParameterObject[]`): 路径、查询和请求头参数 **requestBody** (`RequestBodyObject`): 请求正文规范 **responses** (`ResponsesObject`): 按状态码定义的响应规范 **security** (`SecurityRequirementObject[]`): 操作的安全要求 ## 返回值 返回一个 `ApiRoute` 对象,用于传递给 Mastra 配置中的 `server.apiRoutes`。 ## 处理函数上下文 处理函数会接收一个 Hono `Context` 对象,可通过它访问: ```typescript handler: async c => { // Get the Mastra instance const mastra = c.get('mastra') // Get request context const requestContext = c.get('requestContext') // Access path parameters const itemId = c.req.param('itemId') // Access query parameters const filter = c.req.query('filter') // Access request body const body = await c.req.json() // Return JSON response return c.json({ data: 'value' }) } ``` ## 示例 ### 基本 GET 路由 ```typescript import { Mastra } from '@mastra/core' import { registerApiRoute } from '@mastra/core/server' export const mastra = new Mastra({ server: { apiRoutes: [ registerApiRoute('/health-check', { method: 'GET', handler: async c => { return c.json({ status: 'ok' }) }, }), ], }, }) ``` ### 带路径参数的路由 ```typescript registerApiRoute('/users/:userId/posts/:postId', { method: 'GET', handler: async c => { const userId = c.req.param('userId') const postId = c.req.param('postId') return c.json({ userId, postId }) }, }) ``` ### 带正文的 POST 路由 ```typescript registerApiRoute('/items', { method: 'POST', handler: async c => { const body = await c.req.json() const mastra = c.get('mastra') // Process the request... return c.json({ id: 'new-id', ...body }, 201) }, }) ``` ### 带中间件的路由 ```typescript registerApiRoute('/protected', { method: 'GET', middleware: [ async (c, next) => { const token = c.req.header('Authorization') if (!token) { return c.json({ error: 'Unauthorized' }, 401) } await next() }, ], handler: async c => { return c.json({ data: 'protected content' }) }, }) ``` ### 带 CORS 的路由 当某个自定义路由需要跨域凭据,而服务器其余部分应保留全局 CORS 策略时,请使用路由专用的 CORS。 ```typescript registerApiRoute('/customer-webhook', { method: 'POST', cors: { origin: ['https://customer-saas.example'], credentials: true, }, handler: async c => { return c.json({ ok: true }) }, }) ``` ### 带 OpenAPI 文档的路由 ```typescript import { z } from 'zod' const ItemSchema = z.object({ id: z.string(), name: z.string(), price: z.number(), }) registerApiRoute('/items/:itemId', { method: 'GET', openapi: { summary: 'Get item by ID', description: 'Retrieves a single item by its unique identifier', tags: ['Items'], parameters: [ { name: 'itemId', in: 'path', required: true, description: 'The item ID', schema: { type: 'string' }, }, ], responses: { 200: { description: 'Item found', content: { 'application/json': { schema: ItemSchema, // Zod schemas are converted to JSON Schema during OpenAPI generation }, }, }, 404: { description: 'Item not found', }, }, }, handler: async c => { const itemId = c.req.param('itemId') return c.json({ id: itemId, name: 'Example', price: 9.99 }) }, }) ``` ### 使用 `createHandler()` 对于需要异步初始化的路由: ```typescript registerApiRoute('/dynamic', { method: 'GET', createHandler: async ({ mastra }) => { // Perform one-time async setup const config = await loadConfig() const agent = mastra.getAgent('weatherAgent') return async c => { return c.json({ config, agent: agent.name }) } }, }) ``` ## 错误处理 使用 Hono 的 `HTTPException` 抛出带状态码的错误: ```typescript import { HTTPException } from 'hono/http-exception' registerApiRoute('/items/:itemId', { method: 'GET', handler: async c => { const itemId = c.req.param('itemId') const item = await findItem(itemId) if (!item) { throw new HTTPException(404, { message: 'Item not found' }) } return c.json(item) }, }) ``` ## 相关内容 - [自定义 API 路由指南](https://mastra.zisheng.pro/docs/server/custom-api-routes):包含示例的使用指南 - [服务器中间件](https://mastra.zisheng.pro/docs/server/middleware):全局中间件配置 - [createRoute()](https://mastra.zisheng.pro/reference/server/create-route):为服务器适配器创建类型安全路由 - [服务器路由](https://mastra.zisheng.pro/reference/server/routes):内置 Mastra 服务器路由