registerApiRoute()
registerApiRoute() 関数は、Mastra サーバーと統合されるカスタム HTTP ルートを作成します。ルートに OpenAPI メタデータを含めると、Swagger UI ドキュメントに表示できます。
インポートインポートへの直接リンク
import { registerApiRoute } from '@mastra/core/server'
パラメーターパラメーターへの直接リンク
pathpathへの直接リンク
ルートの URL パスです。:param 構文によるパスパラメーターをサポートします。
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 を含む)も更新してください。
optionsoptionsへの直接リンク
method:
handler?:
handler と createHandler のいずれか一方を使用し、両方は使用しないでください。createHandler?:
handler と createHandler のいずれか一方を使用し、両方は使用しないでください。middleware?:
cors?:
server.cors と異なるクロスオリジンポリシーが必要な場合に使用します。openapi?:
OpenAPI オプションOpenAPI オプションへの直接リンク
openapi プロパティは、hono-openapi の標準的な OpenAPI 3.1 オペレーションフィールドを受け付けます。openapi プロパティのないルートは Swagger UI に含まれません。
summary?:
description?:
deprecated?:
parameters?:
requestBody?:
responses?:
security?:
戻り値戻り値への直接リンク
Mastra 設定の server.apiRoutes に渡す ApiRoute オブジェクトを返します。
ハンドラーコンテキストハンドラーコンテキストへの直接リンク
ハンドラーは、以下にアクセスできる 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)
},
})
ミドルウェアを持つルートミドルウェアを持つルートへの直接リンク
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)
},
})
関連項目関連項目への直接リンク
- カスタム API ルートガイド:使用例を含むガイド
- サーバーミドルウェア:グローバルミドルウェアの設定
- createRoute():サーバーアダプター向けの型安全なルート作成
- サーバールート:Mastra サーバーの組み込みルート