encore-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Encore API Endpoints

Encore API 端点

Instructions

操作步骤

When creating API endpoints with Encore.ts, follow these patterns:
使用Encore.ts创建API端点时,请遵循以下模式:

1. Import the API module

1. 导入API模块

typescript
import { api } from "encore.dev/api";
typescript
import { api } from "encore.dev/api";

2. Define typed request/response interfaces

2. 定义类型化的请求/响应接口

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;
}
始终为请求和响应类型定义明确的TypeScript接口:
typescript
interface CreateUserRequest {
  email: string;
  name: string;
}

interface CreateUserResponse {
  id: string;
  email: string;
  name: string;
}

3. Create the endpoint

3. 创建端点

typescript
export const createUser = api(
  { method: "POST", path: "/users", expose: true },
  async (req: CreateUserRequest): Promise<CreateUserResponse> => {
    // Implementation
  }
);
typescript
export const createUser = api(
  { method: "POST", path: "/users", expose: true },
  async (req: CreateUserRequest): Promise<CreateUserResponse> => {
    // 实现逻辑
  }
);

API Options

API 选项

OptionTypeDescription
method
stringHTTP method: GET, POST, PUT, PATCH, DELETE
path
stringURL path, supports
:param
and
*wildcard
expose
booleanIf true, accessible from outside (default: false)
auth
booleanIf true, requires authentication
选项类型描述
method
stringHTTP方法:GET、POST、PUT、PATCH、DELETE
path
stringURL路径,支持
:param
*wildcard
expose
boolean如果为true,则对外可访问(默认值:false)
auth
boolean如果为true,则需要身份验证

Parameter Types

参数类型

Path Parameters

路径参数

typescript
// Path: "/users/:id"
interface GetUserRequest {
  id: string;  // Automatically mapped from :id
}
typescript
// 路径: "/users/:id"
interface GetUserRequest {
  id: string;  // 自动从:id映射
}

Query Parameters

查询参数

typescript
import { Query } from "encore.dev/api";

interface ListUsersRequest {
  limit?: Query<number>;
  offset?: Query<number>;
}
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;
}
typescript
import { Header } from "encore.dev/api";

interface WebhookRequest {
  signature: Header<"X-Webhook-Signature">;
  payload: string;
}

Request Validation

请求验证

Encore validates requests at runtime using TypeScript types. Add constraints for stricter validation:
typescript
import { api, Min, Max, MinLen, MaxLen, IsEmail, IsURL } from "encore.dev/api";

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
}
Encore会使用TypeScript类型在运行时验证请求。添加约束以实现更严格的验证:
typescript
import { api, Min, Max, MinLen, MaxLen, IsEmail, IsURL } from "encore.dev/api";

interface CreateUserRequest {
  email: string & IsEmail;                    // 必须是有效的邮箱
  username: string & MinLen<3> & MaxLen<20>;  // 3-20个字符
  age: number & Min<13> & Max<120>;           // 13到120之间
  website?: string & IsURL;                   // 可选,若提供则必须是URL
}

Available Validators

可用验证器

ValidatorApplies ToExample
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
验证器适用类型示例
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

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" }
}
无效请求会返回400状态码及详细信息:
json
{
  "code": "invalid_argument",
  "message": "validation failed",
  "details": { "field": "email", "error": "must be a valid email" }
}

Raw Endpoints

原始端点

Use
api.raw
for webhooks or when you need direct request/response access:
typescript
export const stripeWebhook = api.raw(
  { expose: true, path: "/webhooks/stripe", method: "POST" },
  async (req, res) => {
    const sig = req.headers["stripe-signature"];
    // Handle raw request...
    res.writeHead(200);
    res.end();
  }
);
对于Webhook或需要直接访问请求/响应的场景,使用
api.raw
typescript
export const stripeWebhook = api.raw(
  { expose: true, path: "/webhooks/stripe", method: "POST" },
  async (req, res) => {
    const sig = req.headers["stripe-signature"];
    // 处理原始请求...
    res.writeHead(200);
    res.end();
  }
);

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");
使用
APIError
返回正确的HTTP错误响应:
typescript
import { APIError, ErrCode } from "encore.dev/api";

// 抛出带错误码的异常
throw new APIError(ErrCode.NotFound, "user not found");

// 或使用简写形式
throw APIError.notFound("user not found");
throw APIError.invalidArgument("email is required");
throw APIError.unauthenticated("invalid token");

Common Error Codes

常见错误码

CodeHTTP StatusUsage
NotFound
404Resource doesn't exist
InvalidArgument
400Bad input
Unauthenticated
401Missing/invalid auth
PermissionDenied
403Not allowed
AlreadyExists
409Duplicate resource
错误码HTTP状态码用途
NotFound
404资源不存在
InvalidArgument
400输入参数错误
Unauthenticated
401缺失/无效的身份验证
PermissionDenied
403无权限访问
AlreadyExists
409资源重复

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" }
);
使用
api.static
提供静态文件(HTML、CSS、JS、图片):
typescript
import { api } from "encore.dev/api";

// 提供./assets目录下的文件,路径为/static/*
export const assets = api.static(
  { expose: true, path: "/static/*path", dir: "./assets" }
);

// 在根路径提供(使用!path作为回退路由)
export const frontend = api.static(
  { expose: true, path: "/!path", dir: "./dist" }
);

// 自定义404页面
export const app = api.static(
  { expose: true, path: "/!path", dir: "./public", notFound: "./404.html" }
);

Guidelines

规范

  • Always use
    import
    not
    require
  • Define explicit interfaces for type safety
  • Use
    expose: true
    only for public endpoints
  • Use
    api.raw
    for webhooks,
    api
    for everything else
  • Throw
    APIError
    instead of returning error objects
  • Path parameters are automatically extracted from the path pattern
  • Use validation constraints (
    Min
    ,
    MaxLen
    , etc.) for user input
  • 始终使用
    import
    而非
    require
  • 定义明确的接口以确保类型安全
  • 仅对公开端点使用
    expose: true
  • Webhook使用
    api.raw
    ,其他场景使用
    api
  • 抛出
    APIError
    而非返回错误对象
  • 路径参数会自动从路径模式中提取
  • 对用户输入使用验证约束(
    Min
    MaxLen
    等)