encore-api — скилл для Claude Code: типизированные эндпоинты Encore.ts
Помогает агенту писать эндпоинты Encore.ts через api(...): типы запроса и ответа, параметры пути, валидация, ошибки.
npx skills add encoredev/skills --skill encore-api -a claude-code
npx skills add encoredev/skills --skill api -a claude-codeЧто делает encore-api
Скилл описывает, как объявлять эндпоинты в Encore.ts. Агент получает готовые шаблоны: импорт api из encore.dev/api, отдельные интерфейсы под запрос и ответ, вызов api({ method, path, expose }, handler). Есть четыре конфигурации — с телом запроса и ответом, только ответ, только запрос, ни того ни другого.
Внутри разобраны параметры: Query<number> для строки запроса, Header<"X-Webhook-Signature">, Cookie<"session">, :id в пути маппится в поле интерфейса. Валидация идёт через пересечение типов из encore.dev/validate — IsEmail, MinLen<3>, Min<13>, MatchesRegexp. Неверный запрос возвращает 400 с полем details. Ошибки бросаются через APIError.notFound или new APIError(ErrCode.NotFound, ...).
Учтите: скилл покрывает обычные эндпоинты. Для сырых обработчиков api.raw() и входящих вебхуков автор отправляет к другому скиллу — encore-webhook. Если пишете вебхук, этот набор вам не поможет.
Какие задачи решает
- объявить POST-эндпоинт с типизированным телом запроса
- вытащить параметр из пути
/users/:idв поле интерфейса - ограничить поле валидатором
IsEmailилиMinLen - вернуть 404 через
APIError.notFound - отдать статику из папки через
api.static
Примеры запросов агенту
- Сделай POST-эндпоинт /orders с типизированным запросом и ответом
- Добавь валидацию email и длины username в CreateUserRequest
- Верни 404, если пользователь не найден, через APIError
Как установить encore-api
1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill encore-api -a claude-codenpx skills add encoredev/skills --skill api -a claude-code2Вручную: положить файлы
~/.claude/skills/api/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/api/
1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill api -a codex2Вручную: положить файлы
.agents/skills/api/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill api -a cursor2Вручную: положить файлы
.cursor/skills/api/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install encoredev/skills api2Вручную: положить файлы
.github/skills/api/SKILL.md1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill api -a gemini-cli2Командой платформы
gemini skills install https://github.com/encoredev/skills --path encore/apiВручную: положить файлы
.devin/skills/api/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill api -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора10
Похожие
Рядом в теме «Бэкенд и API»
Всё по теме «Бэкенд и API» →Вопросы о encore-api
Как установить encore-api в Claude?
Через маркетплейс скиллов: npx skills add encoredev/skills --skill encore-api -a claude-code. Файл скилла окажется в ~/.claude/skills/api/SKILL.md.
Что делает encore-api?
Даёт агенту шаблоны для эндпоинтов Encore.ts: типы запроса и ответа, параметры пути, заголовков и куки, валидация и коды ошибок.
Чем encore-api отличается от encore-webhook?
encore-api — про обычные эндпоинты с типизированным JSON. Сырые обработчики api.raw() и входящие вебхуки описаны в скилле encore-webhook.
Исходный текст
SKILL.md · Apache-2.0
---
name: encore-api
description: Define typed API endpoints in Encore.ts using `api(...)` from `encore.dev/api`. Covers typed request/response interfaces, path/query/header/cookie params, request validation, and `APIError`. For raw endpoints (`api.raw()`) and inbound webhooks, use `encore-webhook` instead.
when_to_use: >-
User wants to define an endpoint, route, or REST handler in their own service — anything with a typed JSON request/response shape. Mentions of an endpoint, GET/POST/PUT/PATCH/DELETE, paths like `/orders` or `/users/:id`, request body, query parameters (`Query<>`), path parameters, headers (`Header<>`), cookies (`Cookie<>`), HTTP status codes (`HttpStatus`), request validation (`Min`, `MaxLen`, `IsEmail`, `IsURL`), `APIError.notFound` / 4xx-5xx errors, or `expose: true`. Trigger phrases: "POST endpoint at /orders", "typed endpoint", "GET /users/:id", "request validation", "return 404", "JSON response shape".
---
# Encore API Endpoints
## Instructions
When creating API endpoints with Encore.ts, follow these patterns:
### 1. Import the API module
```typescript
import { api } from "encore.dev/api";
```
### 2. Define typed request/response interfaces
Always define explicit TypeScript interfaces for request and response types:
```typescript
interface CreateUserRequest {
email: string;
name: string;
}
interface CreateUserResponse {
id: string;
email: string;
name: string;
}
```
### 3. Create the endpoint
```typescript
export const createUser = api(
{ method: "POST", path: "/users", expose: true },
async (req: CreateUserRequest): Promise<CreateUserResponse> => {
// Implementation
}
);
```
## API Options
| Option | Type | Description |
|--------|------|-------------|
| `method` | string | HTTP method: GET, POST, PUT, PATCH, DELETE |
| `path` | string | URL path, supports `:param` and `*wildcard` |
| `expose` | boolean | If true, accessible from outside (default: false) |
| `auth` | boolean | If true, requires authentication |
| `sensitive` | boolean | If true, redacts request/response payloads from traces |
## Request/Response Patterns
Encore supports four endpoint configurations:
```typescript
// Both request and response
export const createUser = api(
{ method: "POST", path: "/users", expose: true },
async (req: CreateRequest): Promise<CreateResponse> => { ... }
);
// Response only (no request body)
export const listUsers = api(
{ method: "GET", path: "/users", expose: true },
async (): Promise<ListResponse> => { ... }
);
// Request only (no response body)
export const deleteUser = api(
{ method: "DELETE", path: "/users/:id", expose: true },
async (req: DeleteRequest): Promise<void> => { ... }
);
// Neither request nor response
export const ping = api(
{ method: "GET", path: "/ping", expose: true },
async (): Promise<void> => { ... }
);
```
## Custom HTTP Status Codes
Include an `HttpStatus` field in your response to return custom status codes:
```typescript
import { api, HttpStatus } from "encore.dev/api";
interface CreateResponse {
id: string;
status: HttpStatus;
}
export const create = api(
{ method: "POST", path: "/items", expose: true },
async (req: CreateRequest): Promise<CreateResponse> => {
const item = await createItem(req);
return { id: item.id, status: HttpStatus.Created }; // Returns 201
}
);
```
## Parameter Types
### Path Parameters
```typescript
// Path: "/users/:id"
interface GetUserRequest {
id: string; // Automatically mapped from :id
}
```
### Query Parameters
```typescript
import { Query } from "encore.dev/api";
interface ListUsersRequest {
limit?: Query<number>;
offset?: Query<number>;
}
```
### Headers
```typescript
import { Header } from "encore.dev/api";
interface WebhookRequest {
signature: Header<"X-Webhook-Signature">;
payload: string;
}
```
### Cookies
```typescript
import { Cookie } from "encore.dev/api";
interface SessionRequest {
session?: Cookie<"session">;
settings?: Cookie<"user-settings">;
}
```
## Request Validation
Encore validates requests at runtime using TypeScript types. Add constraints for stricter validation:
```typescript
import { api } from "encore.dev/api";
import { Min, Max, MinLen, MaxLen, IsEmail, IsURL } from "encore.dev/validate";
interface CreateUserRequest {
email: string & IsEmail; // Must be valid email
username: string & MinLen<3> & MaxLen<20>; // 3-20 characters
age: number & Min<13> & Max<120>; // Between 13 and 120
website?: string & IsURL; // Optional, must be URL if provided
}
```
### Combining Validation Rules
Use `&` for AND logic (must pass all rules) and `|` for OR logic (must pass at least one):
```typescript
import { IsEmail, IsURL, MinLen, MaxLen } from "encore.dev/validate";
interface ContactRequest {
// Must be valid email OR valid URL
contact: string & (IsEmail | IsURL);
// Must be 5-100 chars AND be a valid URL
website: string & MinLen<5> & MaxLen<100> & IsURL;
}
```
### Available Validators
| Validator | Applies To | Example |
|-----------|-----------|---------|
| `Min<N>` | number | `age: number & Min<18>` |
| `Max<N>` | number | `count: number & Max<100>` |
| `MinLen<N>` | string, array | `name: string & MinLen<1>` |
| `MaxLen<N>` | string, array | `tags: string[] & MaxLen<10>` |
| `IsEmail` | string | `email: string & IsEmail` |
| `IsURL` | string | `link: string & IsURL` |
| `StartsWith<S>` | string | `id: string & StartsWith<"usr_">` |
| `EndsWith<S>` | string | `file: string & EndsWith<".json">` |
| `MatchesRegexp<R>` | string | `code: string & MatchesRegexp<"^[A-Z]{3}$">` |
### Validation Error Response
Invalid requests return 400 with details:
```json
{
"code": "invalid_argument",
"message": "validation failed",
"details": { "field": "email", "error": "must be a valid email" }
}
```
## Error Handling
Use `APIError` for proper HTTP error responses:
```typescript
import { APIError, ErrCode } from "encore.dev/api";
// Throw with error code
throw new APIError(ErrCode.NotFound, "user not found");
// Or use shorthand
throw APIError.notFound("user not found");
throw APIError.invalidArgument("email is required");
throw APIError.unauthenticated("invalid token");
```
## Common Error Codes
| Code | HTTP Status | Usage |
|------|-------------|-------|
| `NotFound` | 404 | Resource doesn't exist |
| `InvalidArgument` | 400 | Bad input |
| `Unauthenticated` | 401 | Missing/invalid auth |
| `PermissionDenied` | 403 | Not allowed |
| `AlreadyExists` | 409 | Duplicate resource |
## Static Assets
Serve static files (HTML, CSS, JS, images) with `api.static`:
```typescript
import { api } from "encore.dev/api";
// Serve files from ./assets under /static/*
export const assets = api.static(
{ expose: true, path: "/static/*path", dir: "./assets" }
);
// Serve at root (use !path for fallback routing)
export const frontend = api.static(
{ expose: true, path: "/!path", dir: "./dist" }
);
// Custom 404 page
export const app = api.static(
{ expose: true, path: "/!path", dir: "./public", notFound: "./404.html" }
);
```
### Path Syntax
- `*path` - Standard wildcard: matches all paths under the prefix (e.g., `/static/*path`)
- `!path` - Fallback routing: serves static files at domain root without conflicting with other API endpoints. Use this for SPAs where unmatched routes should serve `index.html`
## Guidelines
- Always use `import` not `require`
- Define explicit interfaces for type safety
- Use `expose: true` only for public endpoints
- Throw `APIError` instead of returning error objects
- For inbound webhooks (Stripe, GitHub, etc.) use `api.raw` — see the `encore-webhook` skill
- Path parameters are automatically extracted from the path pattern
- Use validation constraints (`Min`, `MaxLen`, etc.) for user input
© encoredev · Apache-2.0 · encoredev/skills