registerApiRoute()
registerApiRoute() 函数创建与 Mastra 服务器集成的自定义 HTTP 路由。路由可以包含 OpenAPI 元数据,以显示在 Swagger UI 文档中。
🌐 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.
导入Direct link to 导入
🌐 Import
import { registerApiRoute } from "@mastra/core/server";
参数Direct link to 参数
🌐 Parameters
pathDirect link to path
路由的 URL 路径。支持使用 :param 语法的路径参数。
🌐 The URL path for the route. Supports path parameters using :param syntax.
registerApiRoute("/items/:itemId", { ... })
注意: 路径不能以 /api/ 开头,因为此前缀已被保留用于 Mastra 服务器路由。
optionsDirect link to options
method:
handler?:
createHandler?:
middleware?:
openapi?:
OpenAPI 选项Direct link to OpenAPI 选项
🌐 OpenAPI Options
openapi 属性接受来自 hono-openapi 的标准 OpenAPI 3.1 操作字段。没有 openapi 属性的路由不会包含在 Swagger UI 中。
🌐 The openapi property accepts standard OpenAPI 3.1 operation fields from hono-openapi. Routes without an openapi property are not included in Swagger UI.
summary?:
description?:
deprecated?:
parameters?:
requestBody?:
responses?:
security?:
返回值Direct link to 返回值
🌐 Return Value
返回一个 ApiRoute 对象,用于在 Mastra 配置中传递给 server.apiRoutes。
🌐 Returns an ApiRoute object to be passed to server.apiRoutes in the Mastra configuration.
处理器上下文Direct link to 处理器上下文
🌐 Handler Context
处理器接收一个 Hono 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" });
}
示例Direct link to 示例
🌐 Examples
基本 GET 路由Direct link to 基本 GET 路由
🌐 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" });
},
}),
],
},
});
带路径参数的路由Direct link to 带路径参数的路由
🌐 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 路由Direct link to 带请求体的 POST 路由
🌐 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);
},
});
带中间件的路由Direct link to 带中间件的路由
🌐 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" });
},
});
带有 OpenAPI 文档的路由Direct link to 带有 OpenAPI 文档的路由
🌐 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 });
},
});
使用 createHandlerDirect link to 使用 createHandler
🌐 Using createHandler
对于需要异步初始化的路由:
🌐 For routes that need async initialization:
registerApiRoute("/dynamic", {
method: "GET",
createHandler: async (c) => {
// Perform async setup
const config = await loadConfig();
return async (c) => {
return c.json({ config });
};
},
});
错误处理Direct link to 错误处理
🌐 Error Handling
使用 Hono 的 HTTPException 抛出带状态码的错误:
🌐 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);
},
});
相关Direct link to 相关
🌐 Related
- 自定义 API 路由指南 - 使用指南及示例
- 服务器中间件 - 全局中间件配置
- createRoute() - 适用于服务器适配器的类型安全路由创建
- 服务器路由 - 内置 Mastra 服务器路由