跳至主要內容

registerApiRoute()

registerApiRoute() function 會建立與 Mastra server 整合的自訂 HTTP route。Route 可包含 OpenAPI metadata,以顯示於 Swagger UI 文件。

匯入
匯入 的直接連結

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

參數
參數 的直接連結

path
path 的直接連結

Route 的 URL 路徑。支援使用 :param syntax 的路徑參數。

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

自訂 route 路徑不可使用 server 已設定的 apiPrefix(預設為 /api)作開頭,因為該前綴保留給 Mastra 內置 route。如設定自訂 apiPrefix,則只會保留該前綴。例如使用 apiPrefix: '/mastra/api' 時,可以使用 /api/my-endpoint 等路徑。

注意

預設 auth 設定會保護 /api/*,並將 /api/api/auth/* 視為公開。更改 apiPrefix 後,這些預設值將不再匹配,內置 route 亦會落在受保護模式以外。請更新 server.auth.protectedserver.auth.public 以引用新前綴,亦要更新所有存取 /api/* 的 client 程式碼(包括 MastraClientapiPrefix)。

options
options 的直接連結

method:

'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
Route 的 HTTP method

handler?:

Handler
接收 Hono Context 的 route handler function。只可使用 handlercreateHandler 其中一項,不可同時使用。

createHandler?:

({ mastra }: { mastra: Mastra }) => Promise<ApiRouteHandler>
接收 Mastra instance 並傳回 route handler 的非同步 factory。它會在 server 啟動時運行一次,因此可執行一次性設定。只可使用 handlercreateHandler 其中一項,不可同時使用。

middleware?:

MiddlewareHandler | MiddlewareHandler[]
Route 專用的 middleware function

cors?:

CorsOptions
Route 專用的 CORS 設定。當某個自訂 route 需要與 server.cors 不同的跨來源政策時使用。

openapi?:

DescribeRouteOptions
Swagger UI 文件的 OpenAPI metadata

OpenAPI 選項
OpenAPI 選項 的直接連結

openapi property 接受 hono-openapi 的標準 OpenAPI 3.1 operation field。沒有 openapi property 的 route 不會包含在 Swagger UI 內。

summary?:

string
Operation 的簡短摘要

description?:

string
Operation 的詳細說明

tags?:

string[]
在 Swagger UI 中分組使用的 tag。如未指定,預設為 ['custom']。

deprecated?:

boolean
將 operation 標記為 deprecated

parameters?:

ParameterObject[]
Path、query 及 header 參數

requestBody?:

RequestBodyObject
Request body 規格

responses?:

ResponsesObject
按 status code 劃分的 response 規格

security?:

SecurityRequirementObject[]
Operation 的安全要求

傳回值
傳回值 的直接連結

傳回 ApiRoute object,以傳遞至 Mastra 設定中的 server.apiRoutes

Handler context
Handler context 的直接連結

Handler 會接收 Hono Context object,並可存取:

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 route
基本 GET route 的直接連結

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

包含路徑參數的 route
包含路徑參數的 route 的直接連結

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

包含 body 的 POST route
包含 body 的 POST route 的直接連結

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

包含 middleware 的 route
包含 middleware 的 route 的直接連結

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 的 route
包含 CORS 的 route 的直接連結

當某個自訂 route 需要跨來源 credential,但 server 其他部分應維持全域 CORS 政策時,請使用 route 專用 CORS。

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

包含 OpenAPI 文件的 route
包含 OpenAPI 文件的 route 的直接連結

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 的直接連結

對於需要非同步初始化的 route:

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 拋出包含 status code 的錯誤:

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