> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # createRoute() `createRoute()` 関数は、Zod バリデーションを備えた型安全なルートを作成します。サーバーアダプターに `openapiPath` が設定されている場合、指定された Zod スキーマから OpenAPI スキーマエントリを生成します。 ## インポート ```typescript import { createRoute } from '@mastra/server/server-adapter' ``` ## シグネチャ ```typescript function createRoute( config: RouteConfig, ): ServerRoute ``` ## パラメーター **method** (`'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'`): HTTP メソッド **path** (`string`): 省略可能なパラメーターを含むルートパス(例: /api/items/:id) **responseType** (`'json' | 'stream'`): レスポンス形式。内部ルートでは追加の型(datastream-response、mcp-http、mcp-sse)を使用できます。 **handler** (`ServerRouteHandler`): ルートハンドラー関数 **pathParamSchema** (`ZodSchema`): URL パスパラメーターを検証します **queryParamSchema** (`ZodSchema`): クエリ文字列パラメーターを検証します **bodySchema** (`ZodSchema`): リクエストボディを検証します **responseSchema** (`ZodSchema`): OpenAPI 用にレスポンスの構造を記述します **streamFormat** (`'sse' | 'stream'`): ストリーム形式(responseType が 'stream' の場合) **maxBodySize** (`number`): デフォルトのボディサイズ上限をバイト単位で上書きします **summary** (`string`): OpenAPI の概要 **description** (`string`): OpenAPI の説明 **tags** (`string[]`): OpenAPI のタグ **deprecated** (`boolean`): ルートを非推奨としてマークします **onValidationError** (`(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined`): このルート用のカスタムバリデーションエラーハンドラー。サーバーレベルの onValidationError フックを上書きします。レスポンスをカスタマイズするには { status, body } を返し、デフォルトを使用するには undefined を返します。 ## ハンドラーのパラメーター ハンドラーは、検証済みのパラメーターとランタイムコンテキストを受け取ります。 ```typescript 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 } ``` ## 戻り値 アダプターに登録できる `ServerRoute` オブジェクトを返します。 ## 例 ### パスパラメーターを使用する GET ルート ```typescript 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) }, }) ``` ### ボディを使用する POST ルート ```typescript 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 } }, }) ``` ### 型変換を伴うクエリパラメーター ```typescript 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 ルート ```typescript 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 }) }, }) ``` ### カスタムのボディサイズ上限 ```typescript 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 } }, }) ``` ## スキーマパターン ### 拡張性のための Passthrough ```typescript const bodySchema = z .object({ required: z.string(), }) .passthrough() // Allow unknown fields ``` ### 日付の型変換 ```typescript const querySchema = z.object({ fromDate: z.coerce.date().optional(), toDate: z.coerce.date().optional(), }) ``` ### Union 型 ```typescript const bodySchema = z.object({ messages: z.union([z.array(z.any()), z.string()]), }) ``` ## エラー処理 ハンドラーから特定の HTTP ステータスコードを返すには、`status` プロパティを持つエラーをスローします。Hono を使用している場合は、`hono/http-exception` の `HTTPException` を使用できます。 ```typescript 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 またはフレームワークに依存しないコードでは、`status` プロパティを持つエラーをスローします。 ```typescript class HttpError extends Error { constructor( public status: number, message: string, ) { super(message) } } // In handler: throw new HttpError(404, `Agent '${agentId}' not found`) ``` 一般的なステータスコードは次のとおりです。 | コード | 意味 | | --- | --------- | | 400 | 不正なリクエスト | | 401 | 認証が必要 | | 403 | アクセス禁止 | | 404 | 見つかりません | | 500 | サーバー内部エラー | ## 関連項目 - [Server ルート](https://mastra.zisheng.pro/ja/reference/server/routes): Mastra のデフォルトルート - [MastraServer](https://mastra.zisheng.pro/ja/reference/server/mastra-server): Server アダプタークラス - [Server アダプター](https://mastra.zisheng.pro/ja/docs/server/server-adapters): アダプターの使用方法