Перейти к содержанию
Skillpedia
API и серверы (бэкенд)8.1k · #12588

webiny-http-route

Что он делает

Этот скилл направляет вашего ИИ при открытии обычного веб-адреса в API Webiny. Он нужен разработчикам, которым требуется простая HTTP-конечная точка для вебхуков, интеграций или собственных ответов.

Когда использовать

  • ✓Когда нужна обычная HTTP-конечная точка в API, а не запрос GraphQL.
  • ✓Когда другая система должна обращаться к собственному URL, чтобы передавать данные в ваш проект.
  • ✓Когда собственному маршруту нужен доступ к сервисам платформы, например к логированию.

Ссылка на скилл

https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/http-route/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/http-route/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Создай маршрут POST в нашем API Webiny, который принимает данные вебхука от платежного провайдера и записывает их в лог.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл объясняет, как написать класс обработчика с методом handle и зарегистрировать его с методом и путем маршрута в файле конфигурации. Обработчик получает свои сервисы через контейнер.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Custom HTTP Routes

TL;DR

Write a handler that implements HttpRouteHandler.Interface, then point <Api.Route> at it in webiny.config.tsx. The method and path props configure both the API Gateway route and the router, so the handler file never restates them. Handlers get full DI.

YOU MUST include the full file path with the .ts extension in the src prop. Use src={"/extensions/MyRoute.ts"}, not src={"/extensions/MyRoute"}. Omitting it fails the build.

YOU MUST use export default for the createImplementation() call. Named exports fail here.

The route pattern

// extensions/MyRoute.ts
import { HttpRouteHandler, Logger } from "webiny/api";

class MyRouteImpl implements HttpRouteHandler.Interface {
  constructor(private logger: Logger.Interface) {}

  async handle(request: HttpRouteHandler.Request, response: HttpRouteHandler.Response) {
    this.logger.info({ path: request.path }, "Handling request");

    return response.status(200).json({ status: "ok" });
  }
}

export default HttpRouteHandler.createImplementation({
  implementation: MyRouteImpl,
  dependencies: [Logger]
});

Register it:

<Api.Route method={"POST"} path={"/my-route"} src={"/extensions/MyRoute.ts"} />

Props reference

Prop Type Required Description
path string Yes Route path — must start with /
method string Yes HTTP method (see below)
src string Yes Path to the handler file (must include .ts)
routeName string No Route name (kebab-case). Derived from path + method if omitted. Doubles as the Pulumi resource name and the id a decorator matches on

Methods: DELETE, GET, HEAD, PATCH, POST, PUT, OPTIONS, ANY. Use ANY to match every method on a path.

Path parameters

Write them either way. {orderId} is API Gateway syntax, :orderId is the router's; the extension converts to whichever each consumer needs, so both work and mean the same thing.

<Api.Route method={"GET"} path={"/orders/{orderId}"} src={"/extensions/GetOrderRoute.ts"} />
<Api.Route method={"GET"} path={"/orders/:orderId"} src={"/extensions/GetOrderRoute.ts"} />

Read them off request.pathParameters:

class GetOrderRouteImpl implements HttpRouteHandler.Interface {
  constructor(private getOrder: GetOrderUseCase.Interface) {}

  async handle(request: HttpRouteHandler.Request, response: HttpRouteHandler.Response) {
    const order = await this.getOrder.execute(request.pathParameters.orderId);

    return response.status(200).json(order);
  }
}

export default HttpRouteHandler.createImplementation({
  implementation: GetOrderRouteImpl,
  dependencies: [GetOrderUseCase]
});

Wildcards are the exception: /files/* matches for the router, {proxy+} for API Gateway, and they capture differently. Write a wildcard route for the target you mean.

Request

HttpRouteHandler.Request is transport-agnostic — no API Gateway or Node types leak into your code.

interface Request {
  method: string;
  path: string;
  headers: Record<string, string>;
  query: Record<string, string>;
  pathParameters: Record<string, string>;
  body: any;
  /** Which route matched — `{ name, method, path }`. */
  route: MatchedRouteDefinition;
}

route is what makes a decorator able to act on one route (see below), and lets a handler read its own identity. method/path on it are the route's PATTERN (/orders/:orderId), where the top-level method/path are the request's actual values (/orders/abc123).

Response

HttpRouteHandler.Response is a mutable builder, the res of an Express-style handler. Every method returns this, so calls chain:

Method Purpose
Частые вопросы

Где задаются метод и путь?

В регистрации маршрута в файле конфигурации, поэтому файл обработчика их не повторяет.

Может ли обработчик использовать логгер?

Да. В примере скилла логгер внедряется как зависимость.

Нужно ли особое расширение файла в пути?

Да. Путь к исходнику должен содержать расширение .ts.

Подробности

Оригинальное описание автора

Adding custom HTTP routes to the API with <Api.Route> and HttpRouteHandler. Use this skill when the developer wants to expose a custom HTTP endpoint (GET, POST, PUT, etc.) on the API alongside the GraphQL handler, implement a route handler with full DI support, or register a custom HTTP route in webiny.config.tsx.

repo: webiny/webiny-js

Популярность

Звёзды на GitHub
8.1k
Место в рейтинге
#12588
Лицензия
—
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы