registerApiRoute()
registerApiRoute() function 會建立與 Mastra server 整合的自訂 HTTP route。Route 可包含 OpenAPI metadata,以顯示於 Swagger UI 文件。
匯入匯入 的直接連結
import { registerApiRoute } from '@mastra/core/server'
參數參數 的直接連結
pathpath 的直接連結
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.protected 及 server.auth.public 以引用新前綴,亦要更新所有存取 /api/* 的 client 程式碼(包括 MastraClient 的 apiPrefix)。
optionsoptions 的直接連結
method:
handler?:
handler 或 createHandler 其中一項,不可同時使用。createHandler?:
handler 或 createHandler 其中一項,不可同時使用。middleware?:
cors?:
server.cors 不同的跨來源政策時使用。openapi?:
OpenAPI 選項OpenAPI 選項 的直接連結
openapi property 接受 hono-openapi 的標準 OpenAPI 3.1 operation field。沒有 openapi property 的 route 不會包含在 Swagger UI 內。
summary?:
description?:
deprecated?:
parameters?:
requestBody?:
responses?:
security?:
傳回值傳回值 的直接連結
傳回 ApiRoute object,以傳遞至 Mastra 設定中的 server.apiRoutes。
Handler contextHandler 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)
},
})
相關內容相關內容 的直接連結
- 自訂 API route 指南:包含範例的使用指南
- Server middleware:全域 middleware 設定
- createRoute():為 server adapter 建立 type-safe route
- Server route:Mastra 內置 server route