encore-api について
encore-apiは、Encore.tsで型付きAPIエンドポイントを作成するためのスキルガイドです。TypeScriptでHTTPルート、リクエスト検証、エラー処理、静的アセット配信を定義する開発者向けです。
主な機能
- 01型付きHTTPエンドポイントの定義
- 02パス、クエリ、ヘッダー、Cookie入力のマッピング
- 03制約によるリクエスト検証
- 04APIErrorによるHTTPエラー応答
- 05静的アセットとSPAフォールバックの配信
活用シーン
- 01型付きCRUDエンドポイントの構築
- 02受信するユーザー入力の検証
- 03認証とリソースエラーの処理
- 04アプリケーション向け静的ファイルの配信
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ encoredev/ skills --skill encore-apiインストール後、Claude Code で/encore-apiを入力して読み込まれたか確認します。
詳細
Encore API エンドポイント
手順
Encore.ts で API エンドポイントを作成する際は、次のパターンに従ってください。
1. API モジュールをインポートする
import { api } from "encore.dev/api";
2. 型付きのリクエスト/レスポンスインターフェースを定義する
リクエストとレスポンスの型には、必ず明示的な TypeScript インターフェースを定義してください。
interface CreateUserRequest {
email: string;
name: string;
}
interface CreateUserResponse {
id: string;
email: string;
name: string;
}
3. エンドポイントを作成する
export const createUser = api(
{ method: "POST", path: "/users", expose: true },
async (req: CreateUserRequest): Promise<CreateUserResponse> => {
// Implementation
}
);
API オプション
| オプション | 型 | 説明 |
|---|---|---|
method | string | HTTP メソッド: GET、POST、PUT、PATCH、DELETE |
path | string | URL パス。:param と *wildcard をサポートします |
expose | boolean | true の場合、外部からアクセス可能になります(デフォルト: false) |
auth | boolean | true の場合、認証が必要になります |
sensitive | boolean | true の場合、トレースからリクエスト/レスポンスのペイロードを秘匿します |
リクエスト/レスポンスのパターン
Encore は 4 つのエンドポイント構成をサポートしています。
// 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> => { ... }
);
カスタム HTTP ステータスコード
カスタムステータスコードを返すには、レスポンスに HttpStatus フィールドを含めます。
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
}
);
パラメータの種類
パスパラメータ
// Path: "/users/:id"
interface GetUserRequest {
id: string; // Automatically mapped from :id
}
クエリパラメータ
import { Query } from "encore.dev/api";
interface ListUsersRequest {
limit?: Query<number>;
offset?: Query<number>;
}
ヘッダー
import { Header } from "encore.dev/api";
interface WebhookRequest {
signature: Header<"X-Webhook-Signature">;
payload: string;
}
Cookie
import { Cookie } from "encore.dev/api";
interface SessionRequest {
session?: Cookie<"session">;
settings?: Cookie<"user-settings">;
}
リクエストのバリデーション
Encore は 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
}
バリデーションルールの組み合わせ
AND ロジック(すべてのルールを満たす必要があります)には & を、OR ロジック(少なくとも 1 つを満たす必要があります)には | を使用します。
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;
}
利用可能なバリデータ
| バリデータ | 適用対象 | 例 |
|---|---|---|
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}$"> |
バリデーションエラーのレスポンス
無効なリクエストは詳細とともに 400 を返します。
{
"code": "invalid_argument",
"message": "validation failed",
"details": { "field": "email", "error": "must be a valid email" }
}
エラーハンドリング
適切な HTTP エラーレスポンスを返すには APIError を使用します。
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");
一般的なエラーコード
| コード | HTTP ステータス | 用途 |
|---|---|---|
NotFound | 404 | リソースが存在しません |
InvalidArgument | 400 | 不正な入力 |
Unauthenticated | 401 | 認証が欠落/無効 |
PermissionDenied | 403 | 許可されていません |
AlreadyExists | 409 | リソースが重複しています |
静的アセット
api.static で静的ファイル(HTML、CSS、JS、画像)を配信します。
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- 標準のワイルドカード: プレフィックス配下のすべてのパスに一致します(例:/static/*path)!path- フォールバックルーティング: 他の API エンドポイントと競合することなく、ドメインルートで静的ファイルを配信します。一致するルートがない場合にindex.htmlを配信する必要がある SPA に使用します
ガイドライン
- 常に
requireではなくimportを使用してください - 型安全性のために明示的なインターフェースを定義してください
expose: trueは公開エンドポイントにのみ使用してください- エラーオブジェクトを返す代わりに
APIErrorをスローしてください - 受信 Webhook(Stripe、GitHub など)には
api.rawを使用してください —encore-webhookスキルを参照してください - パスパラメータはパスパターンから自動的に抽出されます
- ユーザー入力にはバリデーション制約(
Min、MaxLenなど)を使用してください
コメント
Markdown 対応