跳到主要内容

registerApiRoute()

registerApiRoute() 函数可创建与 Mastra 服务器集成的自定义 HTTP 路由。路由可包含 OpenAPI 元数据,以显示在 Swagger UI 文档中。

导入
导入的直接链接

import { registerApiRoute } from '@mastra/core/server'

参数
参数的直接链接

path
path的直接链接

路由的 URL 路径。支持使用 :param 语法定义路径参数。

registerApiRoute("/items/:itemId", { ... })

自定义路由路径不能以服务器配置的 apiPrefix(默认值为 /api)开头,因为该前缀保留给内置的 Mastra 路由。若设置了自定义 apiPrefix,则仅该前缀会被保留。例如,当 apiPrefix: '/mastra/api' 时,允许使用 /api/my-endpoint 这样的路径。

注意

默认的 auth 配置会保护 /api/*,并将 /api/api/auth/* 视为公开路径。更改 apiPrefix 后,这些默认值将不再匹配,内置路由也会落在受保护模式之外。请更新 server.auth.protectedserver.auth.public 以引用新前缀,并更新所有访问 /api/* 的客户端代码(包括 MastraClientapiPrefix)。

选项
选项的直接链接

method:

'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
路由的 HTTP 方法

handler?:

Handler
接收 Hono Context 的路由处理函数。请使用 handlercreateHandler 中的一个,不能同时使用。

createHandler?:

({ mastra }: { mastra: Mastra }) => Promise<ApiRouteHandler>
接收 Mastra 实例并返回路由处理函数的异步工厂。它会在服务器启动时运行一次,因此可执行一次性设置。请使用 handlercreateHandler 中的一个,不能同时使用。

middleware?:

MiddlewareHandler | MiddlewareHandler[]
路由专用的中间件函数

cors?:

CorsOptions
路由专用的 CORS 配置。当某个自定义路由需要与 server.cors 不同的跨域策略时使用此项。

openapi?:

DescribeRouteOptions
用于 Swagger UI 文档的 OpenAPI 元数据

OpenAPI 选项
OpenAPI 选项的直接链接

openapi 属性接受来自 hono-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 对象,可通过它访问:

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 路由
基本 GET 路由的直接链接

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' })
},
}),
],
},
})

带路径参数的路由
带路径参数的路由的直接链接

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 路由
带正文的 POST 路由的直接链接

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)
},
})

带中间件的路由
带中间件的路由的直接链接

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 策略时,请使用路由专用的 CORS。

registerApiRoute('/customer-webhook', {
method: 'POST',
cors: {
origin: ['https://customer-saas.example'],
credentials: true,
},
handler: async c => {
return c.json({ ok: true })
},
})

带 OpenAPI 文档的路由
带 OpenAPI 文档的路由的直接链接

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()
using-createhandler的直接链接

对于需要异步初始化的路由:

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 抛出带状态码的错误:

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)
},
})