> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 등록ApiRoute() 그만큼`registerApiRoute()`기능은 Mastra 서버와 통합되는 사용자 정의 HTTP 경로를 생성합니다. 경로에는 Swagger UI 문서에 표시될 OpenAPI 메타데이터가 포함될 수 있습니다. ## 수입 ```typescript import { registerApiRoute } from '@mastra/core/server' ``` ## 매개변수 ### 길 경로의 URL 경로입니다. 다음을 사용하여 경로 매개변수를 지원합니다.`:param` syntax. ```typescript registerApiRoute("/items/:itemId", { ... }) ``` 사용자 지정 경로는 서버에 구성된 `apiPrefix`(기본값: `/api`)로 시작할 수 없습니다. 해당 접두사는 기본 제공 Mastra 경로용으로 예약되어 있기 때문입니다. 사용자 지정 `apiPrefix`를 설정하면 해당 접두사만 예약됩니다. 예를 들어 `apiPrefix: '/mastra/api'`인 경우 `/api/my-endpoint`와 같은 경로가 허용됩니다. > **경고:** 기본 인증 구성은 `/api/*`를 보호하고 `/api`, `/api/auth/*`를 공개 경로로 취급합니다. `apiPrefix`를 변경하면 이러한 기본값이 더 이상 일치하지 않아 기본 제공 경로가 보호 패턴에서 벗어납니다. 새 접두사를 참조하도록 `server.auth.protected`와 `server.auth.public`을 업데이트하고, `/api/*`에 요청하는 모든 클라이언트 코드(`MastraClient`의 `apiPrefix` 포함)도 업데이트하세요. ### 옵션 **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/ko/docs/server/custom-api-routes): 예시가 포함된 사용 가이드 - [서버 미들웨어](https://mastra.zisheng.pro/ko/docs/server/middleware): 글로벌 미들웨어 구성 - [경로 생성()](https://mastra.zisheng.pro/ko/reference/server/create-route): 서버 어댑터에 대한 유형 안전 경로 생성 - [서버 경로](https://mastra.zisheng.pro/ko/reference/server/routes): 내장된 Mastra 서버 경로