> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # registerApiRoute() `registerApiRoute()` 関数は、Mastra サーバーと統合されるカスタム HTTP ルートを作成します。ルートに OpenAPI メタデータを含めると、Swagger UI ドキュメントに表示できます。 ## インポート ```typescript import { registerApiRoute } from '@mastra/core/server' ``` ## パラメーター ### path ルートの URL パスです。`:param` 構文によるパスパラメーターをサポートします。 ```typescript registerApiRoute("/items/:itemId", { ... }) ``` カスタムルートのパスは、組み込みの Mastra ルート用に予約されているため、サーバーに設定された `apiPrefix`(デフォルト:`/api`)で始めることはできません。カスタムの `apiPrefix` を設定した場合、予約されるのはそのプレフィックスだけです。たとえば `apiPrefix: '/mastra/api'` の場合、`/api/my-endpoint` のようなパスを使用できます。 > **警告:** デフォルトの認証設定では `/api/*` が保護され、`/api` と `/api/auth/*` は公開として扱われます。`apiPrefix` を変更すると、これらのデフォルト設定は一致しなくなり、組み込みルートが保護対象のパターンから外れます。新しいプレフィックスを参照するように `server.auth.protected` と `server.auth.public` を更新し、`/api/*` にアクセスするクライアントコード(`MastraClient` の `apiPrefix` を含む)も更新してください。 ### options **method** (`'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'`): ルートの HTTP メソッド **handler** (`Handler`): Hono Context を受け取るルートハンドラー関数。handler と createHandler のいずれか一方を使用し、両方は使用しないでください。 **createHandler** (`({ mastra }: { mastra: Mastra }) => Promise`): Mastra インスタンスを受け取り、ルートハンドラーを返す非同期ファクトリ。サーバー起動時に一度だけ実行されるため、初期設定を実行できます。handler と createHandler のいずれか一方を使用し、両方は使用しないでください。 **middleware** (`MiddlewareHandler | MiddlewareHandler[]`): ルート固有のミドルウェア関数 **cors** (`CorsOptions`): ルート固有の CORS 設定。あるカスタムルートだけに server.cors と異なるクロスオリジンポリシーが必要な場合に使用します。 **openapi** (`DescribeRouteOptions`): Swagger UI ドキュメント用の OpenAPI メタデータ ## OpenAPI オプション `openapi` プロパティは、[hono-openapi](https://github.com/honojs/middleware/tree/main/packages/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[]`): オペレーションのセキュリティ要件 ## 戻り値 Mastra 設定の `server.apiRoutes` に渡す `ApiRoute` オブジェクトを返します。 ## ハンドラーコンテキスト ハンドラーは、以下にアクセスできる Hono の `Context` オブジェクトを受け取ります。 ```typescript 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 ルート ```typescript 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' }) }, }), ], }, }) ``` ### パスパラメーターを持つルート ```typescript 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 ルート ```typescript 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) }, }) ``` ### ミドルウェアを持つルート ```typescript 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 を使用します。 ```typescript registerApiRoute('/customer-webhook', { method: 'POST', cors: { origin: ['https://customer-saas.example'], credentials: true, }, handler: async c => { return c.json({ ok: true }) }, }) ``` ### OpenAPI ドキュメントを持つルート ```typescript 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()` の使用 非同期の初期化が必要なルートでは、次のようにします。 ```typescript 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` を使用して、ステータスコード付きのエラーをスローします。 ```typescript 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 ルートガイド](https://mastra.zisheng.pro/ja/docs/server/custom-api-routes):使用例を含むガイド - [サーバーミドルウェア](https://mastra.zisheng.pro/ja/docs/server/middleware):グローバルミドルウェアの設定 - [createRoute()](https://mastra.zisheng.pro/ja/reference/server/create-route):サーバーアダプター向けの型安全なルート作成 - [サーバールート](https://mastra.zisheng.pro/ja/reference/server/routes):Mastra サーバーの組み込みルート