Skip to main content

自定义 API 路由

🌐 Custom API Routes

默认情况下,Mastra 会通过其服务器自动公开已注册的代理和工作流。对于其他行为,你可以定义自己的 HTTP 路由。

🌐 By default, Mastra automatically exposes registered agents and workflows via its server. For additional behavior you can define your own HTTP routes.

路由可以通过来自 @mastra/core/server 的辅助工具 registerApiRoute() 提供。路由可以与 Mastra 实例位于同一个文件中,但将它们分开有助于保持配置的简洁。

🌐 Routes are provided with a helper registerApiRoute() from @mastra/core/server. Routes can live in the same file as the Mastra instance but separating them helps keep configuration concise.

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { registerApiRoute } from "@mastra/core/server";

export const mastra = new Mastra({
server: {
apiRoutes: [
registerApiRoute("/my-custom-route", {
method: "GET",
handler: async (c) => {
const mastra = c.get("mastra");
const agent = await mastra.getAgent("my-agent");

return c.json({ message: "Custom route" });
},
}),
],
},
});

注册后,自定义路由将可以从服务器根目录访问。例如:

🌐 Once registered, a custom route will be accessible from the root of the server. For example:

curl http://localhost:4111/my-custom-route

每个路由的处理程序都会接收 Hono 的 Context。在处理程序中,你可以访问 Mastra 实例来获取或调用代理和工作流。

🌐 Each route's handler receives the Hono Context. Within the handler you can access the Mastra instance to fetch or call agents and workflows.

中间件
Direct link to 中间件

🌐 Middleware

要添加特定路由的中间件,在调用 registerApiRoute() 时传入一个 middleware 数组。

🌐 To add route-specific middleware pass a middleware array when calling registerApiRoute().

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { registerApiRoute } from "@mastra/core/server";

export const mastra = new Mastra({
server: {
apiRoutes: [
registerApiRoute("/my-custom-route", {
method: "GET",
middleware: [
async (c, next) => {
console.log(`${c.req.method} ${c.req.url}`);
await next();
},
],
handler: async (c) => {
return c.json({ message: "Custom route with middleware" });
},
}),
],
},
});

OpenAPI 文档
Direct link to OpenAPI 文档

🌐 OpenAPI Documentation

自定义路由可以包含 OpenAPI 元数据,以便在 Swagger UI 中与 Mastra 服务器路由一起显示。通过 openapi 选项传递标准 OpenAPI 操作字段。

🌐 Custom routes can include OpenAPI metadata to appear in the Swagger UI alongside Mastra server routes. Pass an openapi option with standard OpenAPI operation fields.

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { registerApiRoute } from "@mastra/core/server";
import { z } from "zod";

export const mastra = new Mastra({
server: {
apiRoutes: [
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: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
},
},
},
},
},
404: {
description: "Item not found",
},
},
},
handler: async (c) => {
const itemId = c.req.param("itemId");
return c.json({ id: itemId, name: "Example Item" });
},
}),
],
},
});

使用 Zod 架构
Direct link to 使用 Zod 架构

🌐 Using Zod Schemas

在生成 OpenAPI 文档时,openapi 配置中的 Zod 模式会被转换为 JSON Schema:

🌐 Zod schemas in the openapi configuration are converted to JSON Schema when the OpenAPI document is generated:

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { registerApiRoute } from "@mastra/core/server";
import { z } from "zod";

const ItemSchema = z.object({
id: z.string(),
name: z.string(),
price: z.number(),
});

const CreateItemSchema = z.object({
name: z.string().min(1),
price: z.number().positive(),
});

export const mastra = new Mastra({
server: {
apiRoutes: [
registerApiRoute("/items", {
method: "POST",
openapi: {
summary: "Create a new item",
tags: ["Items"],
requestBody: {
required: true,
content: {
"application/json": {
schema: CreateItemSchema,
},
},
},
responses: {
201: {
description: "Item created",
content: {
"application/json": {
schema: ItemSchema,
},
},
},
},
},
handler: async (c) => {
const body = await c.req.json();
return c.json({ id: "new-id", ...body }, 201);
},
}),
],
},
});

在 Swagger UI 中查看
Direct link to 在 Swagger UI 中查看

🌐 Viewing in Swagger UI

在开发模式下运行 (mastra dev) 或在构建选项中使用 swaggerUI: true 时,你的自定义路由会出现在位于 /swagger-ui 的 Swagger UI 中。

🌐 When running in development mode (mastra dev) or with swaggerUI: true in build options, your custom routes appear in the Swagger UI at /swagger-ui.

export const mastra = new Mastra({
server: {
build: {
swaggerUI: true, // Enable in production builds
},
apiRoutes: [
// Your routes...
],
},
});

验证
Direct link to 验证

🌐 Authentication

当在你的 Mastra 服务器上配置了身份验证后,自定义 API 路由默认需要身份验证。要使路由公开可访问,请设置 requiresAuth: false

🌐 When authentication is configured on your Mastra server, custom API routes require authentication by default. To make a route publicly accessible, set requiresAuth: false:

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { registerApiRoute } from "@mastra/core/server";
import { MastraJwtAuth } from "@mastra/auth";

export const mastra = new Mastra({
server: {
auth: new MastraJwtAuth({
secret: process.env.MASTRA_JWT_SECRET,
}),
apiRoutes: [
// Protected route (default behavior)
registerApiRoute("/protected-data", {
method: "GET",
handler: async (c) => {
// Access authenticated user from request context
const user = c.get("requestContext").get("user");
return c.json({ message: "Authenticated user", user });
},
}),

// Public route (no authentication required)
registerApiRoute("/webhooks/github", {
method: "POST",
requiresAuth: false, // Explicitly opt out of authentication
handler: async (c) => {
const payload = await c.req.json();
// Process webhook without authentication
return c.json({ received: true });
},
}),
],
},
});

认证行为
Direct link to 认证行为

🌐 Authentication behavior

  • 未配置认证:所有路由(内置和自定义)均为公开
  • 身份验证已配置
    • Mastra 提供的路线(/api/agents/*/api/workflows/* 等)需要身份验证
    • 自定义路由默认需要身份验证
    • 自定义路由可以使用 requiresAuth: false 选择退出

访问用户信息
Direct link to 访问用户信息

🌐 Accessing user information

当请求被认证时,用户对象可以在请求上下文中使用:

🌐 When a request is authenticated, the user object is available in the request context:

registerApiRoute("/user-profile", {
method: "GET",
handler: async (c) => {
const requestContext = c.get("requestContext");
const user = requestContext.get("user");

return c.json({ user });
},
})

有关身份验证提供程序的更多信息,请参阅 身份验证文档

🌐 For more information about authentication providers, see the Auth documentation.

🌐 Related