跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

registerApiRoute()

The registerApiRoute() function creates custom HTTP routes that integrate with the Mastra server. Routes can include OpenAPI metadata to appear in the Swagger UI documentation.

Import
Import的直接链接

import { registerApiRoute } from '@mastra/core/server'

Parameters
Parameters的直接链接

path
path的直接链接

The URL path for the route. Supports path parameters using :param syntax.

registerApiRoute("/items/:itemId", { ... })

Custom route paths can't start with the server's configured apiPrefix (default: /api), as that prefix is reserved for built-in Mastra routes. If you set a custom apiPrefix, only that prefix is reserved. For example, with apiPrefix: '/mastra/api', paths like /api/my-endpoint are allowed.

注意

The default auth configuration protects /api/* and treats /api, /api/auth/* as public. When you change apiPrefix, those defaults no longer match and built-in routes fall outside the protected pattern. Update server.auth.protected and server.auth.public to reference the new prefix, and update any client code (including MastraClient apiPrefix) that hits /api/*.

options
options的直接链接

method:

'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
HTTP method for the route

handler?:

Handler
Route handler function receiving Hono Context. Use either handler or createHandler, not both.

createHandler?:

({ mastra }: { mastra: Mastra }) => Promise<ApiRouteHandler>
Async factory that receives the Mastra instance and returns the route handler. Runs once at server startup, so it can perform one-time setup. Use either handler or createHandler, not both.

middleware?:

MiddlewareHandler | MiddlewareHandler[]
Route-specific middleware functions

cors?:

CorsOptions
Route-specific CORS configuration. Use this when one custom route needs a different cross-origin policy from server.cors.

openapi?:

DescribeRouteOptions
OpenAPI metadata for Swagger UI documentation

OpenAPI options
OpenAPI options的直接链接

The openapi property accepts standard OpenAPI 3.1 operation fields from hono-openapi. Routes without an openapi property aren't included in Swagger UI.

summary?:

string
Short summary of the operation

description?:

string
Detailed description of the operation

tags?:

string[]
Tags for grouping in Swagger UI. Defaults to ['custom'] if not specified.

deprecated?:

boolean
Mark the operation as deprecated

parameters?:

ParameterObject[]
Path, query, and header parameters

requestBody?:

RequestBodyObject
Request body specification

responses?:

ResponsesObject
Response specifications by status code

security?:

SecurityRequirementObject[]
Security requirements for the operation

Return value
Return value的直接链接

Returns an ApiRoute object to be passed to server.apiRoutes in the Mastra configuration.

Handler context
Handler context的直接链接

The handler receives a Hono Context object with access to:

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' })
}

Examples
Examples的直接链接

Basic GET Route
Basic 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 with Path Parameters
Route with Path Parameters的直接链接

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 Route with Body
POST Route with Body的直接链接

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)
},
})

Route with Middleware
Route with Middleware的直接链接

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' })
},
})

Route with CORS
Route with CORS的直接链接

Use route-specific CORS when one custom route needs cross-origin credentials, but the rest of the server should keep the global CORS policy.

registerApiRoute('/customer-webhook', {
method: 'POST',
cors: {
origin: ['https://customer-saas.example'],
credentials: true,
},
handler: async c => {
return c.json({ ok: true })
},
})

Route with OpenAPI Documentation
Route with OpenAPI Documentation的直接链接

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 })
},
})

Using createHandler()
using-createhandler的直接链接

For routes that need async initialization:

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 })
}
},
})

Error handling
Error handling的直接链接

Throw errors with status codes using Hono's 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)
},
})