[프롬프트] API 문서 자동 생성 프롬프트 - 최적 프롬프트 레시피

API 개발 및 OpenAPI 스웨거 문서화

[프롬프트] API 문서 자동 생성 프롬프트 - 최적 프롬프트 레시피

💡 한 줄 요약: "이 코드 보고 API 문서 써줘"라는 단순 질의 시 발생하는 Happy-path(200 OK) 위주 편향, 에러 모델(RFC 7807/RFC 9457) 누락, 필드별 정밀 유효성 검증(Type/Enum/Range/Regex) 결여, 인증 및 속도 제한(Rate Limit) 헤더 생략을 완벽히 차단하고, OpenAPI 3.1 스키마와 프로덕션급 Markdown API 레퍼런스를 한 번에 도출하는 실전 프롬프트 레시피입니다.

1. 페인포인트 & 작업 목표

  • 실제 작업 시나리오: Spring Boot, FastAPI, NestJS, Express, Go Fiber 등으로 백엔드 엔드포인트를 구현한 뒤 프론트엔드 팀, 외부 연동 고객사, 혹은 사내 타 스쿼드와의 협업을 위해 API 스펙을 신속히 문서화해야 하는 상황.
  • 단순 프롬프트 요청 시 발생하는 4대 실패 원인:
    • Happy-Path (200 OK) 편향 (Happy-Path Bias): "이 컨트롤러 보고 문서 써줘"라고 입력하면 성공 응답 한 가지만 작성하고, 클라이언트 연동에 필수적인 실패 응답(400, 401, 403, 404, 409, 422, 500)을 전면 침묵함.
    • RFC 7807/RFC 9457 표준 에러 규격 부재: 프로덕션 필수 표준 에러 스키마(type, title, status, detail, invalid_params[]) 없이 임의의 {"error": "message"} 문자열로 처리하여 프론트엔드 예외 처리를 무력화함.
    • 필드별 제약조건 및 유효성 검증 결여: 단순 타입(string, number)만 적을 뿐, 필수 여부(required), 글자 수 제한, 정규표현식 패턴(regex), 허용 열거값(Enum)을 누락하여 런타임 검증 오류 유발.
    • 인증 및 전송 헤더 무시: Authorization: Bearer <JWT>, Idempotency-Key, X-Request-Id, X-RateLimit-* 등 실제 호출에 필수적인 헤더와 보안 스키마를 누락함.
  • 최종 해결 목표:
    • 수석 API 아키텍트(Principal API Architect) 페르소나 주입: 단순 코드 주석 변환이 아닌 계약 중심(Contract-First) 거버넌스 관점의 명세 추출.
    • 완전 무결한 API 명세 6대 컴포넌트 강제: [엔드포인트 메타데이터, 보안/인증 헤더, 파라미터 테이블, 요청 본문 JSON Schema, 2xx 성공 및 4xx/5xx RFC 7807 에러 스펙, 재현 가능한 cURL CLI 예제].
    • OpenAPI 3.1 & Markdown 듀얼 호환성 보장: Swagger UI/Redoc 등록과 개발자 포털(Wiki/Notion)에 즉시 임베딩 가능한 고밀도 레퍼런스 동시 생성.

2. 프롬프트 레시피 비교

❌ 레시피 A: 기본형 (단순 질의 초안)

백엔드 코드나 엔드포인트 명세만 던지고 단순 작성을 요구하는 전형적인 초안:

English Prompt (AI 입력용 원문)
Write an API documentation for this endpoint code:
[PASTE_BACKEND_CODE_OR_ROUTE_DEFINITION]
한글 번역 및 한계점

번역: "이 엔드포인트 코드에 대한 API 문서를 작성해줘: [코드 붙여넣기]"

원인 분석: 200 정상 응답만 대략 표시하고 인증 실패(401), 권한 부족(403), 유효성 검증 실패(422)에 대한 규격이 전무하며 필드 제약조건(Enum, Min/Max) 및 cURL 커맨드가 누락됩니다.

⚡ 레시피 B: 실무 종결형 엔터프라이즈 API 명세서 프롬프트 (Principal API Architect)

RFC 7807 표준 에러 규격, 필드별 제약조건 테이블, 보안 헤더, 프로덕션급 cURL 예제 및 완벽한 마크다운 API 레퍼런스를 한 번에 도출하는 완성형 프롬프트:

English Prompt (AI 입력용 원문 - 복사하여 사용)
You are a Principal API Architect and Tech Lead specializing in RESTful system design, OpenAPI 3.1 specifications, and enterprise API governance.
Your mission is to reverse-engineer and document the provided backend controller/handler code into a battle-tested, production-ready API Reference specification.

### Target Source Code / Endpoint Definition:
- Backend Framework: [e.g., FastAPI / Spring Boot / NestJS / Express / Go Fiber]
- Security Model: [e.g., Bearer JWT / OAuth2 / API Key / Session Cookie]
- Source Code:
[PASTE_CONTROLLER_SERVICE_OR_DTO_CODE_HERE]

### Execution Guidelines & Documentation Structure:
1. ENDPOINT METADATA HEADER:
   - Method & Full Route: e.g., `POST /v1/billing/subscriptions`
   - Summary & High-level Business Function.
   - Authentication & RBAC Scope: Required permissions, token type, and rate-limit tier.

2. HEADERS SPECIFICATION TABLE:
   - Provide a table of Request and Response Headers:
     | Header Name | Type | Required | Default / Example | Description |
   - Must include: `Authorization`, `Content-Type`, `X-Request-Id`, `Idempotency-Key` (if mutating), and `X-RateLimit-*`.

3. PARAMETERS & REQUEST BODY SCHEMA:
   - For Path/Query parameters, output a structured table:
     | Parameter | In | Type | Required | Constraints (Enum/Range/Regex) | Description |
   - For Request Body, provide:
     - Formatted JSON payload example (realistic, non-dummy values).
     - Field-by-field schema table detailing: [Field, Type, Nullable, Required, Validation Rules, Description].

4. RESPONSE SPECIFICATIONS (EXHAUSTIVE & STANDARDIZED):
   - Success Responses (200 OK / 201 Created / 204 No Content):
     - Complete JSON response body example.
     - Response schema dictionary with data types and nullability.
   - Error Responses (RFC 7807 Problem Details for HTTP APIs):
     - Document 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests, and 500 Internal Server Error.
     - Each error MUST follow the standard RFC 7807 JSON structure:
       `{ "type": "string", "title": "string", "status": 400, "detail": "string", "instance": "string", "code": "string", "invalid_params": [...] }`

5. PRODUCTION-READY CLI EXAMPLES:
   - Ready-to-execute `curl` command with realistic headers, auth bearer token placeholder, and JSON body.
   - Example successful CLI response payload.

### Strict Negative Constraints (Zero-Fluff Policy):
- Do NOT output shallow placeholders like `{"message": "success"}` or `{"data": "..."}`.
- Do NOT omit error responses; at least 3 distinct client/server error payloads MUST be explicitly rendered.
- Do NOT guess undocumented fields; if an enum or field constraint is inferred from annotations (e.g., `@Min(1)`, `pydantic.Field(ge=1)`), explicitly state the validation origin.
한글 번역 및 파라미터 핵심 해설

번역: "당신은 RESTful 시스템 설계, OpenAPI 3.1 스펙 및 엔터프라이즈 API 거버넌스를 전문으로 하는 수석 API 아키텍트이자 테크 리드입니다. 제공된 백엔드 코드를 역공학하여 프로덕션 배포가 가능한 완전한 API 레퍼런스 명세서로 문서화하십시오."

  • Principal API Architect 페르소나: 멱등성(Idempotency), 보안 스코프(RBAC), 속도 제한(Rate Limiting) 등 프로덕션 아키텍처 요소를 강제함.
  • RFC 7807 에러 스펙 준수: 표준 문제 세부정보(Problem Details) 구조를 강제하여 프론트엔드가 필드별 유효성 오류(invalid_params)를 즉시 UI 폼에 바인딩할 수 있도록 설계.
  • Field-by-field Validation Rules: 최소/최대 길이, 정규식, 허용 열거형 값을 테이블로 박제.
  • Zero-Fluff Negative Constraints: 얕은 {"data": "..."} 생략을 원천 봉쇄하고 실제 동작 가능한 curl 명령어 추출.
🎯 레시피 C: 프레임워크 역공학 & 클라이언트 SDK/Zod 연계형 (Client Contract & SDK Generator)

백엔드 코드로부터 단순 문서를 넘어 프론트엔드 연동용 TypeScript 인터페이스, Zod 런타임 스키마, TanStack Query 커스텀 훅까지 동시 추출하는 고도화 프롬프트:

English Prompt (AI 입력용 원문)
You are a Staff Full-Stack Systems Engineer and Frontend Architecture Specialist.
From the provided backend endpoint handler, extract the complete API Specification AND immediately generate the corresponding frontend client integration artifacts in TypeScript.

### Input Backend Code:
[PASTE_CONTROLLER_OR_ROUTE_CODE]

### Required Artifacts:
1. ENDPOINT CONTRACT SUMMARY:
   - HTTP Method, URI pattern, Auth scope, Request/Response payload contracts.

2. TYPESCRIPT DOMAIN DTOs & SCHEMAS:
   - Request interface and Response interface with strict typing (`readonly`, union literals for Enums, nullable types).
   - Corresponding Zod schema (`z.object({...})`) reflecting all backend validations (regex, min/max, email, uuid).

3. CLIENT INTEGRATION HOOK (TanStack Query / Axios):
   - Fully typed API caller function using `axios` or native `fetch`.
   - Custom React Hook using `@tanstack/react-query` (`useQuery` for GET, `useMutation` for POST/PUT/DELETE) with robust error typing based on RFC 7807.

4. EDGE-CASE ERROR MATRIX:
   - Explicit table mapping HTTP status codes -> Client-side UI error actions (e.g., 401 -> Redirect to `/login`, 422 -> Bind errors to React Hook Form fields).

활용 맥락: 백엔드 구현 완료 직후 프론트엔드 팀에게 넘겨줄 완벽한 TypeScript 계약(Contract)과 클라이언트 연동 훅이 필요한 풀스택 협업 상황에 최적화되어 있습니다.

3. 실행 결과 비교

가상의 결제 구독 생성 엔드포인트(POST /v1/billing/subscriptions) 코드를 두 프롬프트에 주입했을 때의 결과물 차이를 대조합니다.

❌ 레시피 A 실행 결과 (부실한 기본 응답)
# POST /subscriptions
This API creates a subscription for a user.

### Request:
- customerId (string), planId (string), paymentMethodId (string)

### Response (200 OK):
{ "status": "success", "subscriptionId": "sub_999" }

⚠️ 결함: 플랜 허용값(Enum) 부재, 유효성 정규식 결여, 실패 응답(400/401/409/422) 및 cURL 명령어가 전혀 없습니다.

⚡ 레시피 B 실행 결과 (실무 종결형 엔터프라이즈 명세)
1. 헤더 명세 (Request Headers)
헤더명 타입 필수 예시 설명
Authorization string Yes Bearer eyJhbGci... OAuth2 / JWT 토큰 (Scope: billing:write)
Idempotency-Key string Yes 9b1deb4d-3b7d... 이중 결제 방지용 UUID v4 멱등키
Content-Type string Yes application/json 요청 본문 규격
2. 필드별 제약조건 테이블 (Request Body Schema)
필드명 타입 필수 유효성 검증 규칙 (Constraints) 설명
customerId string Yes Regex: ^cus_[a-z0-9]{9,16}$ 고객 고유 식별자
planId string Yes Enum: [STARTER_MONTHLY, PRO_MONTHLY, ENTERPRISE_ANNUAL] 구독 플랜 식별자
paymentMethodId string Yes Regex: ^pm_[a-zA-Z0-9]{14,24}$ 결제 수단 토큰
quantity integer No (Def: 1) Min: 1, Max: 1000 구매 시트 수량
3. 201 Created 정상 응답 (Success)
{
  "id": "sub_1Q1h7b2eZvKYlo2CL8",
  "object": "subscription",
  "status": "active",
  "customerId": "cus_9f83a4c12",
  "planId": "PRO_MONTHLY",
  "currentPeriodStart": "2026-10-15T00:00:00Z",
  "currentPeriodEnd": "2026-11-15T00:00:00Z",
  "seatQuantity": 5,
  "unitPriceAmount": 2900,
  "currency": "USD"
}
4. 422 Unprocessable Entity (RFC 7807 표준 에러)
{
  "type": "https://api.example.com/errors/validation-failed",
  "title": "Validation Failed",
  "status": 422,
  "detail": "Request payload failed semantic validation rules.",
  "instance": "/v1/billing/subscriptions",
  "code": "PAYLOAD_VALIDATION_ERROR",
  "invalid_params": [
    { "name": "planId", "reason": "Value must be one of [STARTER_MONTHLY, PRO_MONTHLY, ENTERPRISE_ANNUAL]" }
  ]
}
5. 프로덕션 실행 cURL 예제
curl -X POST "https://api.example.com/v1/billing/subscriptions" \
  -H "Authorization: Bearer eyJhbGciOi..." \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d" \
  -d '{"customerId":"cus_9f83a4c12","planId":"PRO_MONTHLY","paymentMethodId":"pm_1Hh12X4K38xLpQ","quantity":5}'

4. 메커니즘 심층 분석

1. 역할 및 페르소나 주입 (Principal API Architect Persona)

단순 개발자 페르소나는 코드에 적힌 변수명만 텍스트로 치환합니다. 반면 Principal API Architect & Enterprise Governance Tech Lead 페르소나는 모델의 어텐션 윈도우를 시스템 계약(API Contract), 트랜잭션 무결성(Idempotency), 보안 스코프(RBAC), 실패 허용성 파라미터로 이동시켜 코드에 없더라도 결제/생성 엔드포인트에 멱등키와 409 Conflict 명세를 선제적으로 도출합니다.

2. 엄격한 음의 제약조건 (Negative Constraints)

LLM은 토큰 생성 비용을 절감하기 위해 본능적으로 "data": "..." 같은 더미 축약을 시도합니다. 프롬프트에 Do NOT output shallow placeholders와 at least 3 distinct error payloads MUST be explicitly rendered를 선언함으로써 실무에 즉시 쓸 수 있는 구체적 JSON 페이로드와 상태 코드를 생성하도록 강제합니다.

3. RFC 7807 / RFC 9457 스키마 주입 효과

IETF 공식 표준인 type, title, status, detail, invalid_params 스키마 키셋을 프롬프트에 주입하면, LLM은 인메모리 파서 역할을 수행하여 DTO 유효성 어노테이션(@NotBlank, @Min 등)을 파싱해 invalid_params 하위 배열로 자동 매핑합니다.

5. 실전 응용 팁 & 커스텀 가이드

📌 프로젝트 맞춤형 재사용 플레이스홀더 템플릿

You are a Principal API Architect.
Reverse-engineer the provided [{TARGET_FRAMEWORK}] code into an enterprise Markdown API specification.

### Context:
- Framework: {TARGET_FRAMEWORK} (e.g., FastAPI / Spring Boot / NestJS)
- Auth Strategy: {AUTH_STRATEGY} (e.g., Bearer JWT / API Key)
- Error Standard: {ERROR_STANDARD} (e.g., RFC 7807 Problem Details)

### Target Code:
{PASTE_CODE}

### Output Rules:
1. Include Header Table (Auth, Content-Type, Idempotency).
2. Generate Request Body Schema Table with Type, Nullability, Enum, and Regex.
3. Detail Success (200/201) and Failure (400/401/403/404/422/500) payloads.
4. Output ready-to-run curl command.
  • Swagger / OpenAPI 3.1 YAML 내보내기: 마크다운 대신 Redoc/Swagger UI용 파일이 필요할 경우, "Output the specification strictly in valid OpenAPI 3.1 YAML format within a single code block" 지침을 추가하세요.
  • 대규모 컨트롤러 처리 팁: 엔드포인트 메서드가 수십 개인 경우 한꺼번에 주입하지 말고, 도메인/리소스 그룹 단위(1회당 1~2개 엔드포인트)로 분할 입력해야 필드 제약조건과 에러 페이로드의 정밀도가 극대화됩니다.

댓글 쓰기

다음 이전