[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -4,113 +4,186 @@ title: API Fundamentals
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-WEB-API-FUNDAMENTALS, API, 인터페이스, Application Programming Interface, 통신 규약]
|
||||
aliases: [API basics, REST GraphQL gRPC, Web API]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [Web_API, REST, GraphQL, gRPC, Architecture]
|
||||
raw_sources: [Datacollector_Export_2026-05-02]
|
||||
last_reinforced: 2026-05-02
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [api, rest, graphql, grpc, fundamentals]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: REST/GraphQL/gRPC/tRPC
|
||||
---
|
||||
|
||||
# [[API 핵심 원리 및 아키텍처 패턴 (API Fundamentals)]]
|
||||
# API Fundamentals
|
||||
|
||||
## 1. 개요
|
||||
API(Application Programming Interface)는 소프트웨어 컴포넌트 간의 통신 방법을 정의하는 규약이다. 현대적 시스템 아키텍처에서 API는 단순한 데이터 교환 수단을 넘어 시스템의 기능 경계를 정의하고, 클라이언트의 진입점(Entry Point) 역할을 수행하는 핵심 뼈대이다.
|
||||
## 매 한 줄
|
||||
> **"매 contract between systems — verbs, nouns, errors, evolution"**. 매 RPC (1980s, Sun RPC) → CORBA (1991) → SOAP (1998) → REST (Fielding 2000) → gRPC (2015) → GraphQL (2015) → tRPC (2020). 매 2026 modern stack 은 typed end-to-end (tRPC, GraphQL Codegen, gRPC + buf) + AsyncAPI 2.x for events.
|
||||
|
||||
## 2. API 아키텍처 계층 (4 Layers)
|
||||
1. **상호작용 계층 (Interaction Layer)**: 외부 요청 관리, 인증, 보안 및 통신 효율성 담당.
|
||||
2. **애플리케이션 계층 (Application Layer)**: 핵심 비즈니스 로직 및 기능 실행.
|
||||
3. **통합 계층 (Integration Layer)**: 서비스 간 조율, 데이터 변환 및 유효성 검사 수행.
|
||||
4. **데이터 계층 (Data Layer)**: 데이터베이스 및 저장소와의 상호작용 담당.
|
||||
## 매 핵심
|
||||
|
||||
## 3. 주요 API 통신 패턴
|
||||
- **REST (HTTP/JSON)**: 자원 기반의 무상태 통신. 범용성과 단순성으로 인해 표준으로 널리 사용됨.
|
||||
- **GraphQL**: 클라이언트가 필요한 데이터 구조를 명시적으로 요청. 오버페칭(Overfetching) 문제 해결.
|
||||
- **gRPC (HTTP/2)**: 이진 프로토콜 기반 고속 통신. 마이크로서비스 간 내부 통신에 최적화.
|
||||
- **WebSocket**: 양방향 실시간 스트리밍 통신. 채팅 및 라이브 데이터 처리에 적합.
|
||||
### 매 four styles
|
||||
- **REST**: resource-oriented, HTTP verbs, stateless, cacheable. 매 public API standard.
|
||||
- **GraphQL**: client-specified queries, single endpoint, strong types. 매 BFF / mobile.
|
||||
- **gRPC**: binary (protobuf), HTTP/2, streaming, codegen. 매 internal, low-latency.
|
||||
- **tRPC**: TypeScript-first, no codegen, type inference. 매 Next.js / monorepo.
|
||||
|
||||
## 4. 코드베이스 분석 전략
|
||||
- **진입점(Entry Points) 추적**: 컨트롤러나 라우터 정의부에서 API 엔드포인트를 식별하고, 하향식(Top-down)으로 호출 스택을 분석하여 비즈니스 흐름 파악.
|
||||
- **문서화 활용**: OpenAPI(Swagger) 명세를 통해 시스템의 의존성과 데이터 요구사항을 선제적으로 이해.
|
||||
### 매 cross-cutting concerns
|
||||
- **Versioning**: URI (`/v1`), header (`Accept-Version`), or evolution (additive only).
|
||||
- **Idempotency**: idempotency key for unsafe verbs (POST). At-least-once → exactly-once at API.
|
||||
- **Pagination**: cursor (preferred) vs offset. 매 cursor 의 stable ordering.
|
||||
- **Errors**: RFC 7807 problem+json, gRPC status codes, GraphQL `errors[]`.
|
||||
- **Auth**: OAuth2 / OIDC / mTLS / API key.
|
||||
|
||||
## 5. 지식 연결 (Related)
|
||||
- [[API_First_Architecture]]: 구현보다 설계를 우선하는 API 중심 개발 방법론.
|
||||
- [[Microservices_Architecture]]: API를 통해 서비스 간 경계를 정의하고 연결하는 구조.
|
||||
- [[Security_Best_Practices_for_APIs]]: API 키 관리 및 인증/인가 보안 전략.
|
||||
### 매 응용
|
||||
1. **Public REST + GraphQL** — Stripe (REST), GitHub (both), Shopify (GraphQL).
|
||||
2. **Internal gRPC mesh** — Google, Uber, Square.
|
||||
3. **Full-stack tRPC** — Vercel, Cal.com, T3 stack.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태**: 검증 완료 (Verified)
|
||||
- **출처 신뢰도**: A
|
||||
- **검토 이유**: 시스템 통합과 확장성의 근간이 되는 API의 핵심 개념 및 실천적 분석 방법론 정립.
|
||||
## 💻 패턴
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
|
||||
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### REST resource design
|
||||
```http
|
||||
GET /orders?status=pending&cursor=abc123 → 200 [{...}], next_cursor
|
||||
POST /orders → 201 {id, ...}, Location
|
||||
GET /orders/{id} → 200 {...} | 404
|
||||
PATCH /orders/{id} (JSON Merge Patch) → 200 {...}
|
||||
DELETE /orders/{id} → 204
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### REST idempotency
|
||||
```typescript
|
||||
app.post("/orders", async (req, res) => {
|
||||
const idemKey = req.header("Idempotency-Key");
|
||||
const cached = await redis.get(`idem:${idemKey}`);
|
||||
if (cached) return res.status(200).json(JSON.parse(cached));
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const order = await createOrder(req.body);
|
||||
await redis.setex(`idem:${idemKey}`, 86400, JSON.stringify(order));
|
||||
res.status(201).json(order);
|
||||
});
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Cursor pagination
|
||||
```typescript
|
||||
const limit = 50;
|
||||
const rows = await db.query(
|
||||
`SELECT * FROM orders WHERE (created_at, id) < ($1, $2)
|
||||
ORDER BY created_at DESC, id DESC LIMIT $3`,
|
||||
[cursor.ts, cursor.id, limit + 1]
|
||||
);
|
||||
const hasMore = rows.length > limit;
|
||||
const items = rows.slice(0, limit);
|
||||
const nextCursor = hasMore ? encode(items.at(-1)) : null;
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### GraphQL schema + resolver
|
||||
```graphql
|
||||
type Query {
|
||||
order(id: ID!): Order
|
||||
orders(first: Int!, after: String): OrderConnection!
|
||||
}
|
||||
type Order { id: ID!, status: OrderStatus!, items: [Item!]! }
|
||||
type OrderConnection {
|
||||
edges: [OrderEdge!]!
|
||||
pageInfo: PageInfo!
|
||||
}
|
||||
```
|
||||
```typescript
|
||||
const resolvers = {
|
||||
Query: {
|
||||
order: (_, {id}, ctx) => ctx.dataloaders.order.load(id),
|
||||
orders: async (_, {first, after}, ctx) => paginateOrders(first, after, ctx),
|
||||
},
|
||||
Order: {
|
||||
items: (order, _, ctx) => ctx.dataloaders.itemsByOrder.load(order.id),
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### gRPC service (proto3)
|
||||
```proto
|
||||
syntax = "proto3";
|
||||
package orders.v1;
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
service OrderService {
|
||||
rpc Get(GetRequest) returns (Order);
|
||||
rpc List(ListRequest) returns (stream Order); // server streaming
|
||||
rpc Watch(WatchRequest) returns (stream OrderEvent); // bidi-friendly
|
||||
}
|
||||
message Order {
|
||||
string id = 1;
|
||||
OrderStatus status = 2;
|
||||
google.protobuf.Timestamp created_at = 3;
|
||||
}
|
||||
```
|
||||
|
||||
### tRPC procedure
|
||||
```typescript
|
||||
import { router, publicProcedure } from "./trpc";
|
||||
import { z } from "zod";
|
||||
|
||||
export const orderRouter = router({
|
||||
get: publicProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.query(({ input, ctx }) => ctx.db.order.findUnique({ where: { id: input.id } })),
|
||||
|
||||
create: publicProcedure
|
||||
.input(z.object({ items: z.array(z.string()).min(1) }))
|
||||
.mutation(({ input, ctx }) => ctx.db.order.create({ data: { items: input.items } })),
|
||||
});
|
||||
// Client gets full type inference: trpc.order.get.useQuery({id}) typed
|
||||
```
|
||||
|
||||
### RFC 7807 error
|
||||
```json
|
||||
{
|
||||
"type": "https://api.example.com/errors/insufficient-funds",
|
||||
"title": "Insufficient funds",
|
||||
"status": 402,
|
||||
"detail": "Account 12345 has balance $5, requested $50",
|
||||
"instance": "/orders/abc"
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Style |
|
||||
|---|---|
|
||||
| Public 3rd-party API | REST + OpenAPI 3.1 |
|
||||
| Mobile/web with diverse query needs | GraphQL |
|
||||
| Internal microservices, low latency | gRPC |
|
||||
| TypeScript monorepo (Next.js) | tRPC |
|
||||
| Real-time bidirectional streams | gRPC streaming or WebSocket |
|
||||
| Async events | AsyncAPI + Kafka/NATS |
|
||||
|
||||
**기본값**: 매 REST + OpenAPI 의 public, 매 gRPC 의 internal, 매 tRPC 의 TS monorepo.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed Systems]] · [[Web Architecture]]
|
||||
- 변형: [[REST]] · [[GraphQL]] · [[gRPC]] · [[tRPC]] · [[WebSocket]]
|
||||
- 응용: [[OpenAPI]] · [[API Gateway]] · [[Service Mesh]]
|
||||
- Adjacent: [[OAuth2]] · [[JSON Schema]] · [[Protocol Buffers]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 cross-system contract 의 design, 매 client/server 매 separated, 매 versioned interface 필요.
|
||||
**언제 X**: 매 internal function call (just call it), 매 single process, 매 < 100 lines glue script.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **GET with side effects**: 매 cache poisoning, 매 idempotency violation.
|
||||
- **HTTP 200 with `{error: ...}` body**: 매 status code semantics 의 ignore.
|
||||
- **Versioning by minor change**: 매 v1/v2/v3 explosion. 매 additive evolution 의 prefer.
|
||||
- **Chatty API**: 매 N+1 client roundtrips. 매 batch endpoint or GraphQL.
|
||||
- **No pagination**: 매 unbounded list → OOM at scale.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (RFC 7231 HTTP, RFC 7807 problem+json, gRPC docs, GraphQL spec, tRPC docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content (REST/GraphQL/gRPC/tRPC fundamentals) |
|
||||
|
||||
Reference in New Issue
Block a user