encore-api
БесплатноБез исполняемых скриптовНе проверенDefine typed API endpoints in Encore.ts using `api(...)` from `encore.dev/api`. Covers typed request/response interfaces, path/query/header/cookie params…
от encoredev★ 31 звезда на GitHubОб этом скилле
Encore API Endpoints
Instructions
When creating API endpoints with Encore.ts, follow these patterns:
1. Import the API module
import { api } from "encore.dev/api";
2. Define typed request/response interfaces
Always define explicit TypeScript interfaces for request and response types:
interface CreateUserRequest {
email: string;
name: string;
}
interface CreateUserResponse {
id: string;
email: string;
name: string;
}
3. Create the endpoint
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:
// 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:
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
// Path: "/users/:id"
interface GetUserRequest {
id: string; // Automatically mapped from :id
}
Query Parameters
import { Query } from "encore.dev/api";
interface ListUsersRequest {
limit?: Query<number>;
offset?: Query<number>;
}
Headers
import { Header } from "encore.dev/api";
interface WebhookRequest {
signature: Header<"X-Webhook-Signature">;
payload: string;
}
Cookies
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:
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):
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:
{
"code": "invalid_argument",
"message": "validation failed",
"details": { "field": "email", "error": "must be a valid email" }
}
Error Handling
Use APIError for proper HTTP error responses:
Установить encore-api в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл encore-api?
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.
Как установить скилл encore-api?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл encore-api запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic