createRoute()
createRoute() function 會建立具 Zod 驗證的 type-safe route。在 server adapter 設定 openapiPath 後,它會從提供的 Zod schema 產生 OpenAPI schema 項目。
匯入匯入 的直接連結
import { createRoute } from '@mastra/server/server-adapter'
SignatureSignature 的直接連結
function createRoute<TPath, TQuery, TBody, TResponse, TResponseType>(
config: RouteConfig<TPath, TQuery, TBody, TResponse, TResponseType>,
): ServerRoute
參數參數 的直接連結
method:
'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
HTTP method
path:
string
包含可選參數的 route 路徑(例如
/api/items/:id)responseType:
'json' | 'stream'
Response 格式。內部 route 可使用其他類型(
datastream-response、mcp-http、mcp-sse)。handler:
ServerRouteHandler
Route handler function
pathParamSchema?:
ZodSchema
驗證 URL 路徑參數
queryParamSchema?:
ZodSchema
驗證 query string 參數
bodySchema?:
ZodSchema
驗證 request body
responseSchema?:
ZodSchema
記錄 OpenAPI 的 response shape
streamFormat?:
'sse' | 'stream'
Stream 格式(當 responseType 為 'stream' 時)
maxBodySize?:
number
以 byte 為單位覆寫預設 body 大小限制
summary?:
string
OpenAPI summary
description?:
string
OpenAPI description
deprecated?:
boolean
將 route 標記為 deprecated
onValidationError?:
(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined
此 route 的自訂驗證錯誤 handler。會覆寫 server 層級的
onValidationError hook。傳回 { status, body } 可自訂 response,傳回 undefined 則使用預設值。Handler 參數Handler 參數 的直接連結
Handler 會接收已驗證的參數及 runtime context:
handler: async params => {
// From schemas (typed from Zod)
params.id // From pathParamSchema
params.filter // From queryParamSchema
params.name // From bodySchema
// Runtime context (always available)
params.mastra // Mastra instance
params.requestContext // Request-scoped context
params.tools // Available tools
params.abortSignal // Request cancellation signal
params.taskStore // A2A task storage
}
傳回值傳回值 的直接連結
傳回可向 adapter 註冊的 ServerRoute object。
範例範例 的直接連結
包含路徑參數的 GET route包含路徑參數的 GET route 的直接連結
import { createRoute } from '@mastra/server/server-adapter'
import { z } from 'zod'
const getAgent = createRoute({
method: 'GET',
path: '/api/agents/:agentId',
responseType: 'json',
pathParamSchema: z.object({
agentId: z.string(),
}),
responseSchema: z.object({
name: z.string(),
description: z.string().optional(),
}),
summary: 'Get agent by ID',
tags: ['Agents'],
handler: async ({ agentId, mastra }) => {
return mastra.getAgent(agentId)
},
})
包含 body 的 POST route包含 body 的 POST route 的直接連結
const createItem = createRoute({
method: 'POST',
path: '/api/items',
responseType: 'json',
bodySchema: z.object({
name: z.string(),
value: z.number(),
}),
responseSchema: z.object({
id: z.string(),
name: z.string(),
value: z.number(),
}),
handler: async ({ name, value, mastra }) => {
// name and value are typed from bodySchema
return { id: 'new-id', name, value }
},
})
具 coercion 的 query 參數具 coercion 的 query 參數 的直接連結
const listItems = createRoute({
method: 'GET',
path: '/api/items',
responseType: 'json',
queryParamSchema: z.object({
page: z.coerce.number().default(0),
limit: z.coerce.number().default(50),
enabled: z.coerce.boolean().optional(),
}),
handler: async ({ page, limit, enabled, mastra }) => {
// page, limit, enabled are typed and coerced
return { items: [], page, limit }
},
})
Streaming routeStreaming route 的直接連結
const streamAgent = createRoute({
method: 'POST',
path: '/api/agents/:agentId/stream',
responseType: 'stream',
streamFormat: 'sse',
pathParamSchema: z.object({
agentId: z.string(),
}),
bodySchema: z.object({
messages: z.array(z.any()),
}),
handler: async ({ agentId, messages, mastra, abortSignal }) => {
const agent = mastra.getAgent(agentId)
return agent.stream(messages, { abortSignal })
},
})
自訂 body 大小限制自訂 body 大小限制 的直接連結
const uploadRoute = createRoute({
method: 'POST',
path: '/api/upload',
responseType: 'json',
maxBodySize: 50 * 1024 * 1024, // 50MB
bodySchema: z.object({
file: z.string(),
}),
handler: async ({ file }) => {
return { uploaded: true }
},
})
Schema 模式Schema 模式 的直接連結
使用 passthrough 提供擴充能力使用 passthrough 提供擴充能力 的直接連結
const bodySchema = z
.object({
required: z.string(),
})
.passthrough() // Allow unknown fields
日期 coercion日期 coercion 的直接連結
const querySchema = z.object({
fromDate: z.coerce.date().optional(),
toDate: z.coerce.date().optional(),
})
Union 類型Union 類型 的直接連結
const bodySchema = z.object({
messages: z.union([z.array(z.any()), z.string()]),
})
錯誤處理錯誤處理 的直接連結
拋出帶有 status property 的錯誤,可讓 handler 傳回指定的 HTTP status code。如使用 Hono,可以使用 hono/http-exception 的 HTTPException:
import { createRoute } from '@mastra/server/server-adapter'
import { HTTPException } from 'hono/http-exception'
const getAgent = createRoute({
method: 'GET',
path: '/api/agents/:agentId',
responseType: 'json',
pathParamSchema: z.object({ agentId: z.string() }),
handler: async ({ agentId, mastra }) => {
const agent = mastra.getAgent(agentId)
if (!agent) {
throw new HTTPException(404, { message: `Agent '${agentId}' not found` })
}
return agent
},
})
對 Express 或不依賴 framework 的程式碼,請拋出帶有 status property 的錯誤:
class HttpError extends Error {
constructor(
public status: number,
message: string,
) {
super(message)
}
}
// In handler:
throw new HttpError(404, `Agent '${agentId}' not found`)
常見 status code:
| Code | 含義 |
|---|---|
| 400 | 錯誤 request |
| 401 | 未獲授權 |
| 403 | 禁止存取 |
| 404 | 找不到資源 |
| 500 | Server 內部錯誤 |
相關內容相關內容 的直接連結
- Server route:預設 Mastra route
- MastraServer:Server adapter class
- Server adapter:使用 adapter