Community코딩 & 개발github.com

alfathafp/portofolio-web-design

안정적인 API 및 인터페이스 설계를 가이드합니다. API 설계, 모듈 경계 정의, 또는 모든 공개 인터페이스를 설계할 때 사용합니다. REST 또는 GraphQL 엔드포인트 생성, 모듈 간 타입 계약 정의, 또는 프론트엔드와 백엔드 간 경계 설정 시에 사용하세요.

portofolio-web-design란 무엇인가요?

이 스킬은 REST API, GraphQL 스키마, 모듈 경계, 컴포넌트 props 등 모든 코드 간 인터페이스 설계를 위한 원칙과 패턴을 제공합니다. Hyrum의 법칙(Hyrum's Law)과 원-버전 규칙(One-Version Rule)을 핵심 원칙으로 삼아, 안정적이고 오용하기 어려운 인터페이스를 설계하도록 돕습니다. 계약 우선(Contract First), 일관된 오류 의미론(Consistent Error Semantics), 경계에서의 검증(Validate at Boundaries), 수정보다는 추가 선호(Prefer Addition Over Modification), 예측 가능한 명명 규칙(Predictable Naming), 멱등성 키(Idempotency-Key) 처리와 같은 실용적인 패턴을 제시합니다. 특히 멱등성 키 처리에 대한 깊이 있는 설명과 경계 사례를 다루며, REST API 리소스 설계, 페이지네이션, 필터링, 부분 업데이트(PATCH)와 같은 구체적인 패턴을 타입스크립트 예시와 함께 제공합니다. 개발자는 이 스킬을 통해 API 설계 초기 단계부터 안정적이고 확장 가능한 인터페이스를 구축할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/alfathafp/portofolio-web-design/tree/HEAD/.agents/skills/api-and-interface-design

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

API 및 인터페이스 설계

개요

안정적이고 문서화가 잘 되어 있으며 오용하기 어려운 인터페이스를 설계합니다. 좋은 인터페이스는 올바른 일을 쉽게 만들고 잘못된 일을 어렵게 만듭니다. 이는 REST API, GraphQL 스키마, 모듈 경계, 컴포넌트 props 및 코드 조각이 서로 통신하는 모든 표면에 적용됩니다.

사용 시기

  • 새 API 엔드포인트 설계
  • 모듈 경계 또는 팀 간 계약 정의
  • 컴포넌트 prop 인터페이스 생성
  • API 형태에 영향을 미치는 데이터베이스 스키마 설정
  • 기존 공개 인터페이스 변경

핵심 원칙

Hyrum의 법칙

충분한 수의 API 사용자가 있는 경우, 계약에서 약속한 내용과 관계없이 시스템의 모든 관찰 가능한 동작은 누군가에 의해 의존됩니다.

즉, 문서화되지 않은 특성, 오류 메시지 텍스트, 타이밍 및 순서를 포함한 모든 공개 동작은 사용자가 의존하는 순간 사실상의 계약이 됩니다. 설계에 미치는 영향:

  • 노출하는 것에 의도적이어야 합니다. 모든 관찰 가능한 동작은 잠재적인 약속입니다.
  • 구현 세부 사항을 유출하지 마십시오. 사용자가 관찰할 수 있다면, 사용자는 그것에 의존할 것입니다.
  • 설계 시점에서 폐기를 계획하십시오. 사용자가 의존하는 것을 안전하게 제거하는 방법은 deprecation-and-migration을 참조하십시오.
  • 테스트만으로는 충분하지 않습니다. 완벽한 계약 테스트가 있더라도 Hyrum의 법칙에 따르면 "안전한" 변경 사항이 문서화되지 않은 동작에 의존하는 실제 사용자에게 문제를 일으킬 수 있습니다.

원-버전 규칙

소비자가 동일한 종속성 또는 API의 여러 버전 중에서 선택하도록 강요하지 마십시오. 다른 소비자가 동일한 것의 다른 버전을 필요로 할 때 다이아몬드 종속성 문제가 발생합니다. 한 번에 하나의 버전만 존재하는 세상을 위해 설계하십시오 — 분기(fork)하지 말고 확장(extend)하십시오.

1. 계약 우선

인터페이스를 구현하기 전에 정의하십시오. 계약이 명세서입니다 — 구현은 그 뒤를 따릅니다.

// 계약을 먼저 정의합니다
interface TaskAPI {
  // 작업을 생성하고 서버 생성 필드와 함께 생성된 작업을 반환합니다
  createTask(input: CreateTaskInput): Promise<Task>;

  // 필터와 일치하는 페이지네이트된 작업을 반환합니다
  listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;

  // 단일 작업을 반환하거나 NotFoundError를 throw합니다
  getTask(id: string): Promise<Task>;

  // 부분 업데이트 — 제공된 필드만 변경됩니다
  updateTask(id: string, input: UpdateTaskInput): Promise<Task>;

  // 멱등적 삭제 — 이미 삭제된 경우에도 성공합니다
  deleteTask(id: string): Promise<void>;
}

2. 일관된 오류 의미론

하나의 오류 전략을 선택하고 모든 곳에서 사용하십시오:

// REST: HTTP 상태 코드 + 구조화된 오류 본문
// 모든 오류 응답은 동일한 형태를 따릅니다
interface APIError {
  error: {
    code: string;        // 기계 판독 가능: "VALIDATION_ERROR"
    message: string;     // 사람 판독 가능: "Email is required"
    details?: unknown;   // 도움이 될 때 추가 컨텍스트
  };
}

// 상태 코드 매핑
// 400 → 클라이언트가 유효하지 않은 데이터를 보냄
// 401 → 인증되지 않음
// 403 → 인증되었지만 권한이 없음
// 404 → 리소스를 찾을 수 없음
// 409 → 충돌 (중복, 버전 불일치)
// 422 → 유효성 검사 실패 (의미적으로 유효하지 않음)
// 500 → 서버 오류 (내부 세부 정보를 절대 노출하지 마십시오)

패턴을 혼합하지 마십시오. 일부 엔드포인트가 throw하고, 다른 엔드포인트가 null을 반환하고, 또 다른 엔드포인트가 { error }를 반환하면 소비자는 동작을 예측할 수 없습니다.

3. 경계에서 검증

내부 코드를 신뢰하십시오. 외부 입력이 시스템에 들어오는 시스템 가장자리에서 검증하십시오:

// API 경계에서 검증
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(),
      },
    });
  }

  // 검증 후 내부 코드는 타입을 신뢰합니다
  const task = await taskService.create(result.data);
  return res.status(201).json(task);
});

검증이 속하는 곳:

  • API 라우트 핸들러 (사용자 입력)
  • 양식 제출 핸들러 (사용자 입력)
  • 외부 서비스 응답 파싱 (타사 데이터 -- 항상 신뢰할 수 없는 것으로 취급)
  • 환경 변수 로딩 (구성)

타사 API 응답은 신뢰할 수 없는 데이터입니다. 로직, 렌더링 또는 의사 결정에 사용하기 전에 해당 형태와 내용을 검증하십시오. 손상되었거나 오작동하는 외부 서비스는 예기치 않은 유형, 악의적인 콘텐츠 또는 명령과 유사한 텍스트를 반환할 수 있습니다.

검증이 속하지 않는 곳:

  • 타입 계약을 공유하는 내부 함수 간
  • 이미 검증된 코드에 의해 호출되는 유틸리티 함수
  • 자체 데이터베이스에서 방금 가져온 데이터

4. 수정보다 추가 선호

기존 소비자를 중단시키지 않고 인터페이스를 확장하십시오:

// 좋음: 선택적 필드 추가
interface CreateTaskInput {
  title: string;
  description?: string;
  priority?: 'low' | 'medium' | 'high';  // 나중에 추가됨, 선택적
  labels?: string[];                       // 나중에 추가됨, 선택적
}

// 나쁨: 기존 필드 유형 변경 또는 필드 제거
interface CreateTaskInput {
  title: string;
  // description: string;  // 제거됨 — 기존 소비자 중단
  priority: number;         // 문자열에서 변경됨 — 기존 소비자 중단
}

5. 예측 가능한 명명

패턴규칙예시
REST 엔드포인트복수 명사, 동사 없음GET /api/tasks, POST /api/tasks
쿼리 매개변수camelCase?sortBy=createdAt&pageSize=20
응답 필드camelCase{ createdAt, updatedAt, taskId }
부울 필드is/has/can 접두사isComplete, hasAttachments
열거형 값UPPER_SNAKE"IN_PROGRESS", "COMPLETED"

6. 멱등성 키 처리

Idempotency-Key를 수락하는 것은 계약입니다. 이를 존중하는 것은 구현이며, 여기서 비용이 발생합니다 — 서버가 수락했지만 부주의하게 처리한 키는 키가 전혀 없는 것보다 나쁩니다. 클라이언트는 재시도가 안전하다고 믿기 때문입니다.

의도(intent)에서 키를 파생시키고 시도(attempt)에서 파생시키지 마십시오. 키는 하나의 의도에 대한 재시도 간에 안정적이어야 하고 서로 다른 의도 간에는 달라야 합니다:

crypto.randomUUID()                    // ✗ 시도당 새 키 — 모든 재시도가 새 청구가 됩니다
`${userId}:${amount}`                  // ✗ 두 개의 합법적인 $50 청구가 하나로 합쳐집니다
`${orderId}:${Date.now()}`             // ✗ 타임스탬프는 모자를 쓴 randomUUID()입니다

req.headers['idempotency-key']         // ✓ 클라이언트가 한 번 생성하고 재시도 시 재사용합니다
`charge:v1:${orderId}`                 // ✓ 변경 불가능한 식별자에서 파생됩니다

키는 클라이언트 또는 시작 이벤트에서 옵니다 — 재시도를 수행하는 계층에서 절대 오지 않습니다.

원자적으로 선점하십시오(Claim atomically). 확인 후 실행은 경쟁 조건(race)입니다:

// ✗ TOCTOU: 두 개의 동시 재시도가 모두 "보지 못함"을 읽고, 둘 다 청구합니다
if (!(await db.exists(key))) {
  await chargeCard(amount);
  await db.insert(key);
}

// ✓ 고유 제약 조건이 승자를 선택하도록 합니다
try {
  await db.insert({ key, state: 'in_progress', requestHash });
} catch (e) {
  if (isUniqueViolation(e)) return replayOrReject(key);
  throw e;
}
const result = await chargeCard(amount);
await db.update({ key, state: 'succeeded', response: result });

고유 제약 조건 자체가 메커니즘입니다. 한 번의 작업으로 고유성을 강제할 수 없는 저장소는 이를 뒷받침할 수 없습니다.

페이로드를 보호하십시오. 동일한 키와 다른 본문은 클라이언트 버그이며, 첫 번째 응답을 두 번째 요청에 제공하는 대신 큰 소리로 실패해야 합니다:

if (existing.requestHash !== hash(req.body)) {
  return res.status(422).json({ error: 'idempotency key reused with a different payload' });
}

진행 중인 중복 항목이 무엇을 받을지 결정하십시오. 첫 번째 요청이 아직 실행 중일 때 두 번째 요청이 도착합니다 — 재시도 폭풍에서 일반적인 경우입니다:

전략응답사용 시기
거부409 Conflict클라이언트가 나중에 재시도할 수 있음; 가장 간단하고 안전함
대기결과를 위해 차단, 제한됨호출자가 동기식으로 필요로 함
보류 중 반환202 + 상태 URL장기 실행 효과

첫 번째가 "멈춘 것처럼 보인다"고 해서 두 번째 호출자를 통과시키지 마십시오. 운명을 알 수 없는 중단된 시도는 정확히 중복 비용이 가장 많이 드는 경우입니다.

모든 호출에는 성공, 실패, 알 수 없음의 세 가지 결과가 있습니다. 시간 초과는 효과가 적용되었는지 여부를 알려주지 않습니다. 호출하기 전에 의도를 기록하여, 호출과 응답 사이의 충돌이 나중에 해결해야 할 증거를 남기도록 하십시오 — 조용히 재시도된 청구보다는.

디스크 비용이 아닌 가장 긴 재시도 체인에서 보존 기간을 설정하십시오. 키는 일주일 후에 재생되는 데드 레터 큐와 공급자 분쟁 기간을 포함하여 동일한 의도를 재전달할 수 있는 모든 경로보다 오래 지속되어야 합니다. 7일 DLQ 뒤의 24시간 키 TTL은 발생할 준비가 된 중복입니다.

REST API 패턴

리소스 설계

GET    /api/tasks              → 작업 목록 (필터링을 위한 쿼리 매개변수 포함)
POST   /api/tasks              → 작업 생성
GET    /api/tasks/:id          → 단일 작업 가져오기
PATCH  /api/tasks/:id          → 작업 업데이트 (부분)
DELETE /api/tasks/:id          → 작업 삭제

GET    /api/tasks/:id/comments → 작업에 대한 댓글 목록 (하위 리소스)
POST   /api/tasks/:id/comments → 작업에 댓글 추가

페이지네이션

목록 엔드포인트를 페이지네이트하십시오:

// 요청
GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc

// 응답
{
  "data": [...],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "totalItems": 142,
    "totalPages": 8
  }
}

필터링

필터에 쿼리 매개변수를 사용하십시오:

GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01

부분 업데이트 (PATCH)

부분 객체를 수락하십시오 — 제공된 것만 업데이트하십시오:

// 제목만 변경되고 나머지는 유지됨
PATCH /api/tasks/123
{ "title": "Updated title" }

TypeScript 인터페이스 패턴

변형에 판별 유니온(Discriminated Unions) 사용

// 좋음: 각 변형이 명시적임
type TaskStatus =
  | { type: 'pending' }
  | { type: 'in_progress'; assignee: string; startedAt: Date }
  | { type: 'completed'; completedAt: Date; completedBy: string }
  | { type: 'cancelled'; reason: string; cancelledAt: Date };

// 소비자는 타입 좁히기를 얻음
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}`;
  }
}

입력/출력 분리

// 입력: 호출자가 제공하는 것
interface CreateTaskInput {
  title: string;
  description?: string;
}

// 출력: 시스템이 반환하는 것 (서버 생성 필드 포함)
interface Task {
  id: string;
  title: string;
  description: string | null;
  createdAt: Date;
  updatedAt: Date;
  createdBy: string;
}

ID에 브랜디드 타입(Branded Types) 사용

type TaskId = string & { readonly __brand: 'TaskId' };
type UserId = string & { readonly __brand: 'UserId' };

// TaskId가 예상되는 곳에 UserId를 실수로 전달하는 것을 방지합니다
function getTask(id: TaskId): Promise<Task> { ... }

일반적인 합리화

합리화현실
"API 문서는 나중에 작성하겠습니다"타입이 문서입니다. 먼저 정의하십시오.
"지금은 페이지네이션이 필요 없습니다"누군가 100개 이상의 항목을 가질 때 필요할 것입니다. 처음부터 추가하십시오.
"PATCH는 복잡하니 PUT을 사용합시다"PUT은 매번 전체 객체가 필요합니다. PATCH가 클라이언트가 실제로 원하는 것입니다.
"필요할 때 API를 버전 관리하겠습니다"버전 관리 없는 획기적인 변경은 소비자를 중단시킵니다. 처음부터 확장을 위해 설계하십시오.
"아무도 그 문서화되지 않은 동작을 사용하지 않습니다"Hyrum의 법칙: 관찰 가능하면 누군가 의존합니다. 모든 공개 동작을 약속으로 취급하십시오.
"두 가지 버전을 유지 관리하면 됩니다"여러 버전은 유지 관리 비용을 배가시키고 다이아몬드 종속성 문제를 만듭니다. 원-버전 규칙을 선호하십시오.
"내부 API에는 계약이 필요 없습니다"내부 소비자도 여전히 소비자입니다. 계약은 결합을 방지하고 병렬 작업을 가능하게 합니다.
"Idempotency-Key 헤더를 수락하는 것으로 충분합니다"헤더는 계약입니다. 결과에 대해 키를 저장하는 것이 구현입니다. 수락했지만 존중하지 않는 키는 클라이언트에게 재시도가 안전하지 않을 때 안전하다고 말합니다.
"우리 큐는 정확히 한 번 전달을 보장합니다"소비자 충돌 시 이를 보장하는 큐는 없습니다 — 브로커의 ack와 당신의 부작용은 하나의 트랜잭션에 있지 않습니다. 멱등적 처리를 통해 최소 한 번(at-least-once)을 위해 설계하십시오.
"중복 요청은 드뭅니다"이들은 상관관계가 있습니다. 재시도는 정확히 종속성이 저하될 때 급증합니다 — 중복이 가장 가능성이 높고 가장 비용이 많이 드는 순간입니다.

위험 신호

  • 조건에 따라 다른 형태를 반환하는 엔드포인트
  • 엔드포인트 간 일관성 없는 오류 형식
  • 경계 대신 내부 코드 전체에 분산된 유효성 검사
  • 기존 필드에 대한 획기적인 변경 (유형 변경, 제거)
  • 페이지네이션이 없는 목록 엔드포인트
  • REST URL의 동사 (/api/createTask, /api/getUsers)
  • 검증 또는 살균 없이 사용된 타사 API 응답
  • 멱등성 키에 대한 SELECT 다음에 INSERT가 오는 경우 — 이는 경쟁 조건(race)이지 보호 장치가 아닙니다
  • 시도당 재생성되는 UUID, 타임스탬프 또는 다른 것에서 파생된 멱등성 키
  • 동일한 키가 다른 요청 본문으로 수락되어 첫 번째 응답을 조용히 반환하는 경우
  • 요청을 재전달할 수 있는 가장 긴 경로보다 짧은 키 보존 기간

검증

API를 설계한 후:

  • 모든 엔드포인트에 타입화된 입력 및 출력 스키마가 있습니다
  • 오류 응답이 단일 일관된 형식을 따릅니다
  • 유효성 검사가 시스템 경계에서만 발생합니다
  • 목록 엔드포인트가 페이지네이션을 지원합니다
  • 새 필드는 추가적이고 선택적입니다 (하위 호환 가능)
  • 명명이 모든 엔드포인트에서 일관된 규칙을 따릅니다
  • API 문서가...

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

alfathafp/portofolio-web-design

Tests in real browsers via Chrome DevTools MCP. Use when building or debugging anything that runs in a browser. Use when you need to inspect the DOM, capture console errors, analyze network requests, profile performance, or verify visual output with real runtime data. Requires the chrome-devtools MCP server to be configured.

alfathafp/portofolio-web-design

Automates CI/CD pipeline setup. Use when setting up or modifying build and deployment pipelines. Use when you need to automate quality gates, configure test runners in CI, or establish deployment strategies.

alfathafp/portofolio-web-design

Conducts multi-axis code review. Use before merging any change. Use when reviewing code written by yourself, another agent, or a human. Use when you need to assess code quality across multiple dimensions before it enters the main branch. Use when asked to review a diff or a pull request, even when the diff is pasted inline.

alfathafp/portofolio-web-design

Simplifies code for clarity. Use when refactoring code for clarity without changing behavior. Use when code works but is harder to read, maintain, or extend than it should be. Use when reviewing code that has accumulated unnecessary complexity.

alfathafp/portofolio-web-design

Establishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.

alfathafp/portofolio-web-design

Optimizes agent context setup. Use when starting a new session, when agent output quality degrades, when switching between tasks, or when you need to configure rules files and context for a project.

alfathafp/portofolio-web-design

Guides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing.

alfathafp/portofolio-web-design

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

alfathafp/portofolio-web-design

Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.

alfathafp/portofolio-web-design

Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.

alfathafp/portofolio-web-design

Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies

alfathafp/portofolio-web-design

Records decisions and documentation. Use when you need to document an architecture decision (ADR) or the reasoning behind a design choice, when changing public APIs, shipping features, or when you need to record context that future engineers and agents will need to understand the codebase.

alfathafp/portofolio-web-design

Subjects every non-trivial decision to a fresh-context adversarial review before it stands. Use when you want every assumption cross-examined before proceeding, when stress-testing a plan for hidden failure modes, when correctness matters more than speed, when working in unfamiliar code, when stakes are high (production auth, security-sensitive logic, a high-stakes migration, irreversible operations), or any time a confident output would be cheaper to verify now than to debug later.

alfathafp/portofolio-web-design

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

alfathafp/portofolio-web-design

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

alfathafp/portofolio-web-design

Builds production-quality, accessible, responsive user-facing UIs. Use when building or modifying interfaces and pages, creating components, implementing layouts, meeting WCAG accessibility requirements, managing state, or when the output needs to look and feel production-quality rather than AI-generated.

alfathafp/portofolio-web-design

Structures git workflow practices. Use when making any code change. Use when committing, branching, resolving conflicts, splitting uncommitted work in a messy working tree into clean atomic commits, opening or reviewing a pull request (PR), pushing to a remote, or when you need to organize work across multiple parallel streams. Use when cutting a release, choosing a semantic version bump, tagging, or writing a changelog.

alfathafp/portofolio-web-design

Refines raw ideas into sharp, actionable concepts through structured divergent and convergent thinking. Use when an idea is still vague, when you need to stress-test assumptions before committing to a plan, or when you want to expand options before converging on one. Triggers on "ideate", "refine this idea", or "stress-test my plan".

alfathafp/portofolio-web-design

Delivers changes incrementally in thin, verifiable slices. Use when implementing any feature or change that touches more than one file, or when picking up the next task from a plan. Use when rolling a change out behind a feature flag, when you're about to write a large amount of code at once, or when a task feels too big to land in one step.

alfathafp/portofolio-web-design

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

관련 스킬