[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+176 -63
View File
@@ -2,91 +2,204 @@
id: wiki-2026-0508-public-apis
title: Public APIs
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Public API, External API, Open API, Developer API]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [backend, api, rest, graphql, design]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: hono
---
# [[Public APIs|Public APIs]]
# Public APIs
## 📌 한 줄 통찰 (The Karpathy Summary)
프론트엔드 아키텍처 및 컴포넌트 라이브러리 설계에서 퍼블릭 API(Public APIs)는 컴포넌트나 패키지가 외부와 상호작용하기 위해 노출하는 명시적인 계약이자 안정적인 진입점(entry point)을 의미합니다 [1, 2]. 이는 컴포넌트가 받는 속성(props)과 반환하는 이벤트(callbacks)를 정의하며, 내부 구현 세부 사항을 캡슐화합니다 [2]. 명확한 퍼블릭 API를 강제하는 것은 패키지 간의 무분별한 참조를 방지하고, 변화하는 요구사항 속에서도 안전하게 확장 가능한 UI를 구축하는 데 필수적입니다 [3, 4].
## 한 줄
> **"매 API 매 product"**. Public API 매 외부 developer-facing — versioning · auth · rate-limit · docs · SLA 매 first-class. 2026 stack: REST + OpenAPI 3.1, GraphQL Federation v2, gRPC for 내부, MCP for AI agents — Stripe · GitHub · Twilio 매 reference.
## 📖 구조화된 지식 (Synthesized Content)
* **컴포넌트 API 설계의 중요성:** 재사용 가능한 UI를 구축하는 것은 단순히 코드를 적게 작성하는 것이 아니라, 지속적인 변화에서 살아남을 수 있는 API를 설계하는 것입니다 [3]. 좋은 컴포넌트 API는 직관적이고 오용하기 어려워야 하며, 최소한의 속성(props)만 노출해야 합니다 [5]. 이는 컴포넌트가 무엇을 받아들이고, 무엇을 반환하며, 절대 하지 말아야 할 행동(예: 부모 상태 변이)을 규정하는 명시적 계약(Explicit Contracts) 역할을 수행합니다 [2].
* **모노레포와 패키지 경계 관리:** 대규모 모노레포 환경에서는 모듈성 유지를 위해 엄격한 퍼블릭 API 노출이 필요합니다 [1, 4]. 소비자는 내부의 깊은 경로(예: `import Button from "@acme/ui/src/button/Button"`)가 아닌, 의도적으로 노출된 안정적인 진입점(예: `import { Button } from "@acme/ui"`)을 통해서만 모듈을 가져와야 합니다 [4]. 이를 강제하기 위해 패키지의 `package.json`에서 `exports` 필드를 정의하거나 [[ESLint|ESLint]] 규칙을 적용하여 딥 임포트(deep imports)를 차단해야 합니다 [4, 6].
* **FSD([[Feature-Sliced Design|Feature-Sliced Design]])와의 통합:** 확장 가능한 프론트엔드 아키텍처 방법론인 FSD는 슬라이스(slice) 경계에서 명시적인 퍼블릭 API 사용을 권장합니다 [7]. 애플리케이션은 공유 패키지나 슬라이스의 `index.ts` 같은 퍼블릭 API 파일을 통해서만 임포트하고, 내부 파일은 철저히 내부에 유지되도록 설계함으로써 의도치 않은 결합(accidental coupling)을 크게 줄일 수 있습니다 [7, 8].
* **거버넌스 및 브레이킹 체인지 방지:** 여러 앱에서 사용되는 공유 패키지(예: `packages/ui`)의 퍼블릭 API가 변경될 경우 파급 효과가 크므로, 예측 불가능한 시스템 중단을 막기 위해 엄격한 관리가 필요합니다 [9, 10]. `CODEOWNERS` 등을 이용해 소유권을 명확히 하고, 공유 모듈의 퍼블릭 API에 변경 사항이 있을 때는 반드시 코드 리뷰를 요구하는 정책을 수립해야 합니다 [9, 10].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Component API Design|Component API Design]], Monorepo Architecture, [[Feature-Sliced Design (FSD)|Feature-Sliced Design (FSD]], Explicit Contracts
- **Projects/Contexts:** 대규모 리액트 애플리케이션의 모노레포 구축(Nx/[[Turborepo|Turborepo]]), 확장 가능하고 유지보수 용이한 재사용 UI 컴포넌트 라이브러리 설계
- **Contradictions/Notes:** 컴포넌트 내부의 복잡성은 숨기고 외부로는 단순하고 일관된 진입점을 제공해야 한다는 원칙은, 단일 컴포넌트 설계와 대규모 패키지 구조 설계 양쪽 모두에 공통적으로 핵심적인 지침으로 강조됩니다 [2, 4].
### 매 Design pillars
- **Versioning**: URL(`/v1`) · header(`API-Version: 2026-05-01`, Stripe). 매 deprecation policy.
- **Auth**: OAuth2 · API key · JWT · mTLS. Per-key scopes.
- **Rate limit**: token bucket per key/IP. `Retry-After` · `X-RateLimit-*` headers.
- **Pagination**: cursor (preferred) > offset. 매 stable · efficient.
- **Errors**: RFC 7807 Problem Details. 매 stable error codes.
- **Idempotency**: `Idempotency-Key` header (Stripe pattern).
- **Docs**: OpenAPI 3.1 + interactive (Scalar / Redocly).
---
*Last updated: 2026-04-26*
### 매 Protocol selection
- **REST + JSON**: 매 default · widest compat.
- **GraphQL**: 매 client-shaped queries · over-fetch 의 X.
- **gRPC**: 매 internal · low-latency · binary.
- **MCP**: 매 LLM agent tool exposure (2025+).
- **Webhooks**: server-push · async events.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. SaaS public API (Stripe, GitHub, Twilio).
2. Platform / marketplace.
3. Mobile/web client backend.
4. Partner integration.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### REST endpoint with OpenAPI (Hono + Zod)
```typescript
import { Hono } from 'hono';
import { z } from 'zod';
import { describeRoute } from 'hono-openapi/zod';
## 🧪 검증 상태 (Validation)
const app = new Hono();
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
const Order = z.object({
id: z.string().uuid(),
amount_cents: z.number().int().nonnegative(),
currency: z.enum(['USD','EUR','KRW']),
});
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
app.get('/v1/orders/:id',
describeRoute({
summary: 'Get order',
responses: { 200: { content: { 'application/json': { schema: Order } } } },
}),
async (c) => {
const o = await db.orders.find(c.req.param('id'));
if (!o) return c.json({ type:'/errors/not-found', title:'Order not found' }, 404);
return c.json(o);
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### Cursor pagination
```typescript
// GET /v1/orders?limit=50&cursor=opaque
app.get('/v1/orders', async (c) => {
const limit = Math.min(Number(c.req.query('limit') ?? 50), 100);
const cursor = c.req.query('cursor');
const after = cursor ? decode(cursor) : null; // {id, created_at}
const rows = await db.orders.list({ after, limit: limit + 1 });
const hasMore = rows.length > limit;
const page = rows.slice(0, limit);
return c.json({
data: page,
next_cursor: hasMore ? encode(page[page.length-1]) : null,
});
});
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Rate limit (Cloudflare/Redis token bucket)
```typescript
async function rateLimit(key: string, capacity = 100, refillPerSec = 10) {
const now = Date.now()/1000;
const lua = `
local b = redis.call('HMGET', KEYS[1], 'tokens','ts')
local tokens = tonumber(b[1]) or tonumber(ARGV[1])
local ts = tonumber(b[2]) or tonumber(ARGV[3])
local refill = (tonumber(ARGV[3]) - ts) * tonumber(ARGV[2])
tokens = math.min(tonumber(ARGV[1]), tokens + refill)
if tokens < 1 then return 0 end
redis.call('HMSET', KEYS[1], 'tokens', tokens-1, 'ts', ARGV[3])
return 1
`;
return redis.eval(lua, 1, key, capacity, refillPerSec, now);
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Idempotency-Key (Stripe pattern)
```typescript
app.post('/v1/payments', async (c) => {
const idem = c.req.header('Idempotency-Key');
if (!idem) return c.json({ error: 'idempotency_key_required' }, 400);
const cached = await idemStore.get(idem);
if (cached) return c.json(cached.body, cached.status);
const result = await chargeCard(await c.req.json());
await idemStore.put(idem, { status: 200, body: result }, { ttl: 86400 });
return c.json(result);
});
```
**기본값:**
> *(TODO)*
### Webhook with HMAC sig (verified)
```typescript
import crypto from 'node:crypto';
function verify(payload: string, sig: string, secret: string) {
const expected = crypto.createHmac('sha256', secret).update(payload).digest('hex');
return crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Versioning by header (Stripe-style)
```typescript
app.use('*', async (c, next) => {
const v = c.req.header('Stripe-Version') ?? '2026-05-01';
c.set('apiVersion', v);
await next();
});
// 매 handler 매 version-aware shape transform.
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Problem Details error (RFC 7807)
```typescript
function problem(status: number, type: string, title: string, detail?: string) {
return new Response(
JSON.stringify({ type, title, status, detail }),
{ status, headers: { 'Content-Type': 'application/problem+json' } }
);
}
```
### MCP server (AI agent tool)
```typescript
// 매 Public API 매 LLM-callable
import { McpServer } from '@modelcontextprotocol/sdk/server';
const server = new McpServer({ name: 'orders-api', version: '1.0.0' });
server.tool('get_order', { id: z.string() }, async ({ id }) => {
const o = await fetch(`https://api.acme.com/v1/orders/${id}`).then(r => r.json());
return { content: [{ type: 'text', text: JSON.stringify(o) }] };
});
```
## 매 결정 기준
| 요건 | Choice |
|---|---|
| External developer-facing | REST + OpenAPI 3.1 |
| Client-shaped queries | GraphQL |
| Internal RPC | gRPC |
| AI agent tool | MCP |
| Async event push | Webhooks |
| File upload large | Resumable (tus) |
| Real-time | SSE / WebSockets |
**기본값**: REST + OpenAPI + Idempotency-Key + cursor pagination.
## 🔗 Graph
- 부모: [[Backend Architecture]] · [[API Design]]
- 변형: [[REST]] · [[GraphQL]] · [[gRPC]] · [[MCP]]
- 응용: [[Stripe API]] · [[GitHub API]] · [[OpenAPI - Swagger]]
- Adjacent: [[Webhooks and Notifications]] · [[Rate Limiting]] · [[OAuth2]]
## 🤖 LLM 활용
**언제**: OpenAPI spec generation, error-shape design, 매 SDK scaffolding.
**언제 X**: 매 production rate-limit policy 의 직접 결정 — 매 traffic data 의 review.
## ❌ 안티패턴
- **No versioning**: breaking change 매 직격탄.
- **Random error shapes**: client 매 parse 못 함 — RFC 7807 의 사용.
- **Offset pagination on huge tables**: 매 deep scan.
- **Sync auth check on hot path**: cache JWT verification.
- **No `Idempotency-Key`**: 매 retry 매 double charge.
- **Leaking internal IDs**: opaque · cursor · UUID 의 사용.
## 🧪 검증 / 중복
- Verified (Stripe API docs 2026; GitHub API docs; *API Design Patterns* JJ Geewax).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content (pillars + 8 patterns) |