跳至主要內容

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[]
路由專用的 middleware 函式

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

包含 middleware 的路由
「包含 middleware 的路由」的直接連結

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