api-and-interface-design – skill Thiết kế & UI cho agent AI
Hướng dẫn thiết kế API và giao diện ổn định. Dùng khi thiết kế API, ranh giới module hoặc bất kỳ giao diện công khai nào. Dùng khi tạo endpoint REST hoặc GraphQL, định nghĩa hợp đồng kiểu giữa các module, hoặc thiết lập ranh giới giữa frontend và backend.
Cài skill api-and-interface-design bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/api-and-interface-design-61233.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /api-and-interface-design – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/api-and-interface-design-61233.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $api-and-interface-design – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/api-and-interface-design-61233.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /api-and-interface-design – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/api-and-interface-design-61233.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /api-and-interface-design – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
API and Interface Design
Overview
Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another.
When to Use
- Designing new API endpoints
- Defining module boundaries or contracts between teams
- Creating component prop interfaces
- Establishing database schema that informs API shape
- Changing existing public interfaces
Core Principles
Hyrum's Law
> With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract.
This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications:
- Be intentional about what you expose. Every observable behavior is a potential commitment.
- Don't leak implementation details. If users can observe it, they will depend on it.
- Plan for deprecation at design time. See
deprecation-and-migrationfor how to safely remove things users depend on. - Tests are not enough. Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.
The One-Version Rule
Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork.
1. Contract First
Define the interface before implementing it. The contract is the spec — implementation follows.
// Define the contract first
interface TaskAPI {
// Creates a task and returns the created task with server-generated fields
createTask(input: CreateTaskInput): Promise<Task>;
// Returns paginated tasks matching filters
listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;
// Returns a single task or throws NotFoundError
getTask(id: string): Promise<Task>;
// Partial update — only provided fields change
updateTask(id: string, input: UpdateTaskInput): Promise<Task>;
// Idempotent delete — succeeds even if already deleted
deleteTask(id: string): Promise<void>;
}2. Consistent Error Semantics
Pick one error strategy and use it everywhere:
// REST: HTTP status codes + structured error body
// Every error response follows the same shape
interface APIError {
error: {
code: string; // Machine-readable: "VALIDATION_ERROR"
message: string; // Human-readable: "Email is required"
details?: unknown; // Additional context when helpful
};
}
// Status code mapping
// 400 → Client sent invalid data
// 401 → Not authenticated
// 403 → Authenticated but not authorized
// 404 → Resource not found
// 409 → Conflict (duplicate, version mismatch)
// 422 → Validation failed (semantically invalid)
// 500 → Server error (never expose internal details)Don't mix patterns. If some endpoints throw, others return null, and others return { error } — the consumer can't predict behavior.
3. Validate at Boundaries
Trust internal code. Validate at system edges where external input enters:
// Validate at the API boundary
app.post('/api/tasks', async (req, res) => {
const result = CreateTaskSchema.safeParse(req.body);
if (!result.success) {
return res.status(422).json({
error: {
code: 'VALIDATION_ERROR',
message: 'Invalid task data',
details: result.error.flatten(),
},
});
}
// After validation, internal code trusts the types
const task = await taskService.create(result.data);
return res.status(201).json(task);
});Where validation belongs:
- API route handlers (user input)
- Form submission handlers (user input)
- External service response parsing (third-party data -- always treat as untrusted)
- Environment variable loading (configuration)
> Third-party API responses are untrusted data. Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text.
Where validation does NOT belong:
- Between internal functions that share type contracts
- In utility functions called by already-validated code
- On data that just came from your own database
4. Prefer Addition Over Modification
Extend interfaces without breaking existing consumers:
// Good: Add optional fields
interface CreateTaskInput {
title: string;
description?: string;
priority?: 'low' | 'medium' | 'high'; // Added later, optional
labels?: string[]; // Added later, optional
}
// Bad: Change existing field types or remove fields
interface CreateTaskInput {
title: string;
// description: string; // Removed — breaks existing consumers
priority: number; // Changed from string — breaks existing consumers
}5. Predictable Naming
| Pattern | Convention | Example |
|---------|-----------|---------|
| REST endpoints | Plural nouns, no verbs | GET /api/tasks, POST /api/tasks |
| Query params | camelCase | ?sortBy=createdAt&pageSize=20 |
| Response fields | camelCase | { createdAt, updatedAt, taskId } |
| Boolean fields | is/has/can prefix | isComplete, hasAttachments |
| Enum values | UPPER_SNAKE | "IN_PROGRESS", "COMPLETED" |
Authorization and compatibility boundaries
Runtime validation is distinct from authorization: authenticate callers and enforce tenant/resource ownership and field-level permissions for every operation, including deletes and PATCH. Treat database rows or internal messages as new trust boundaries when legacy/imported/multi-tenant data can violate assumptions; types alone do not validate runtime values. Branded string casts prevent some accidental mixing, not malicious IDs or access violations. Bound pagination, allowlist sortable/filterable fields and use a stable tie-breaker/cursor under concurrent writes. Define null versus absent PATCH semantics, concurrency/version checks and idempotency for retried creates. JSON timestamps are serialized strings, not JavaScript Date instances. Additive enum/field changes can break strict clients; test actual compatibility and choose versioning when extension cannot preserve semantics.
REST API Patterns
Resource Design
GET /api/tasks → List tasks (with query params for filtering)
POST /api/tasks → Create a task
GET /api/tasks/:id → Get a single task
PATCH /api/tasks/:id → Update a task (partial)
DELETE /api/tasks/:id → Delete a task
GET /api/tasks/:id/comments → List comments for a task (sub-resource)
POST /api/tasks/:id/comments → Add a comment to a taskPagination
Paginate list endpoints:
// Request
GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc
// Response
{
"data": [...],
"pagination": {
"page": 1,
"pageSize": 20,
"totalItems": 142,
"totalPages": 8
}
}Filtering
Use query parameters for filters:
GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01Partial Updates (PATCH)
Accept partial objects — only update what's provided:
// Only title changes, everything else preserved
PATCH /api/tasks/123
{ "title": "Updated title" }TypeScript Interface Patterns
Use Discriminated Unions for Variants
// Good: Each variant is explicit
type TaskStatus =
| { type: 'pending' }
| { type: 'in_progress'; assignee: string; startedAt: Date }
| { type: 'completed'; completedAt: Date; completedBy: string }
| { type: 'cancelled'; reason: string; cancelledAt: Date };
// Consumer gets type narrowing
function getStatusLabel(status: TaskStatus): string {
switch (status.type) {
case 'pending': return 'Pending';
case 'in_progress': return `In progress (${status.assignee})`;
case 'completed': return `Done on ${status.completedAt}`;
case 'cancelled': return `Cancelled: ${status.reason}`;
}
}Input/Output Separation
// Input: what the caller provides
interface CreateTaskInput {
title: string;
description?: string;
}
// Output: what the system returns (includes server-generated fields)
interface Task {
id: string;
title: string;
description: string | null;
createdAt: Date;
updatedAt: Date;
createdBy: string;
}Use Branded Types for IDs
type TaskId = string & { readonly __brand: 'TaskId' };
type UserId = string & { readonly __brand: 'UserId' };
// Prevents accidentally passing a UserId where a TaskId is expected
functio… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- design-system-patterns – Xây dựng design system có khả năng mở rộng với design token, hạ tầng theming và kiến…
- baoyu-xhs-images – Tạo chuỗi thẻ hình ảnh infographic với 12 phong cách trực quan, 8 bố cục và 3 bảng màu…
- concept-diagrams – Tạo hình minh họa SVG giáo dục phẳng, tối giản dưới dạng HTML.
- apify-brand-reputation-monitoring – Thu thập review, đánh giá và các lượt nhắc đến thương hiệu từ nhiều nền tảng bằng Apify…
- playwright-interactive – Tương tác bền vững với trình duyệt và ứng dụng Electron qua `js_repl` để gỡ lỗi giao…
- apify-influencer-discovery – Tìm và đánh giá influencer cho hợp tác thương hiệu, đánh giá các tín hiệu xác thực công…
- image – Khi người dùng muốn tạo, sinh, chỉnh sửa hoặc tối ưu hình ảnh cho marketing — ảnh hero…
- generate-image – Tạo hoặc chỉnh sửa hình ảnh bằng mô hình AI qua OpenRouter Image API (Gemini, Seedream…