> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sajuapi.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# v1 마이그레이션 가이드

> 기존 API에서 v1 API로 마이그레이션하기

## 개요

사주 API v1은 RESTful 리소스 기반 설계로 전면 개편되었습니다.
기존 `/api/*` 엔드포인트는 deprecated되며, `/v1/*` 엔드포인트로 마이그레이션해야 합니다.

<Warning>
  기존 엔드포인트는 2025년 6월까지 지원됩니다.
  `Deprecation` 헤더가 포함된 응답을 받고 있다면 마이그레이션을 진행해 주세요.
</Warning>

***

## 주요 변경사항

### 엔드포인트 변경

| 기존                             | 신규                               | 변경 내용        |
| ------------------------------ | -------------------------------- | ------------ |
| POST /api/daily-fortune        | POST /v1/fortunes                | 리소스 기반 URL   |
| POST /api/daily-fortune-stream | POST /v1/fortunes/stream         | 경로 구조 변경     |
| POST /api/saju                 | POST /v1/calculations/saju       | 계산 리소스로 분리   |
| POST /api/fortune              | POST /v1/calculations/yearly     | 연간 운세 계산     |
| -                              | GET/POST/PUT/DELETE /v1/profiles | 프로필 CRUD 추가  |
| -                              | GET /v1/fortunes                 | 운세 목록 조회 추가  |
| -                              | /v1/\*/unmasked                  | 복호화 엔드포인트 추가 |

### 요청 형식 변경

#### 기존 방식

```json theme={null}
{
  "saju": {
    "pillars": { ... },
    "dayMaster": { ... }
  },
  "userName": "김철수",
  "model": "haiku"
}
```

#### 신규 방식

```json theme={null}
{
  "profile_id": "prf_abc123",
  "type": "daily",
  "model": "haiku"
}
```

<Note>
  v1에서는 사주 정보를 직접 전송하는 대신 프로필 ID를 참조합니다.
  프로필에 사주 정보가 저장되어 있습니다.
</Note>

***

## 마이그레이션 단계

### 1단계: 프로필 생성

기존에 클라이언트에서 관리하던 사용자 데이터를 프로필로 등록합니다:

```bash theme={null}
# 프로필 생성
curl -X POST https://api.sajuapi.dev/v1/profiles \
  -H "X-API-Key: bs_live_xxx" \
  -d '{
    "external_id": "user_12345",
    "name": "김철수",
    "birth_year": 1990,
    "birth_month": 3,
    "birth_day": 15,
    "birth_hour": 14,
    "gender": "male"
  }'
```

응답으로 받은 `id`를 저장합니다:

```json theme={null}
{
  "id": "prf_abc123",  // ← 이 ID를 저장
  "external_id": "user_12345",
  "day_master": "병화",
  ...
}
```

### 2단계: 기존 사주 계산 코드 제거

프로필 생성 시 사주가 자동으로 계산되므로 클라이언트 측 사주 계산 로직을 제거합니다:

```javascript theme={null}
// 기존 코드 (제거)
const saju = SajuCalculator.calculate({
  year: birthYear,
  month: birthMonth,
  day: birthDay,
  hour: birthHour,
  gender: gender
});

// 신규 코드 (프로필 ID만 사용)
const profileId = "prf_abc123";
```

### 3단계: 운세 요청 변경

```javascript theme={null}
// 기존 코드
const response = await fetch('/api/daily-fortune', {
  method: 'POST',
  headers: { 'X-API-Key': API_KEY },
  body: JSON.stringify({
    saju: saju,
    userName: '김철수',
    model: 'haiku',
    date: '2025-01-15'
  })
});

// 신규 코드
const response = await fetch('/v1/fortunes', {
  method: 'POST',
  headers: {
    'X-API-Key': API_KEY,
    'Idempotency-Key': `fortune-2025-01-15-${profileId}`
  },
  body: JSON.stringify({
    profile_id: profileId,
    type: 'daily',
    model: 'haiku',
    date: '2025-01-15'
  })
});
```

### 4단계: 응답 형식 대응

응답 구조가 일부 변경되었습니다:

```javascript theme={null}
// 기존 응답
{
  "success": true,
  "data": {
    "character": { ... },
    "todayFortune": { ... }
  },
  "meta": { ... }
}

// 신규 응답
{
  "id": "ftn_xyz789",
  "profile_id": "prf_abc123",
  "type": "daily",
  "score": 78,
  "data": {
    "character": { ... },
    "today_fortune": { ... }  // camelCase → snake_case
  },
  "meta": { ... },
  "created_at": "2025-01-15T09:00:00Z"
}
```

***

## 필드명 변경

| 기존 (camelCase)       | 신규 (snake\_case)      |
| -------------------- | --------------------- |
| `userName`           | `name` (프로필)          |
| `todayFortune`       | `today_fortune`       |
| `dayMaster`          | `day_master`          |
| `investmentTendency` | `investment_tendency` |
| `actionItems`        | `action_items`        |
| `overallAnalysis`    | `overall_analysis`    |

***

## 호환성 레이어

마이그레이션 기간 동안 기존 엔드포인트는 리다이렉트됩니다:

```http theme={null}
POST /api/daily-fortune HTTP/1.1

HTTP/1.1 301 Moved Permanently
Location: /v1/fortunes
Deprecation: true
Sunset: 2025-06-30
```

<Warning>
  `Deprecation: true` 헤더가 포함된 응답을 받으면
  가능한 빨리 신규 엔드포인트로 전환하세요.
</Warning>

***

## SDK 업데이트

### JavaScript SDK

```bash theme={null}
npm update @sajuapi/sdk@latest
```

```javascript theme={null}
// 기존 SDK
import { getDailyFortune } from '@sajuapi/sdk';
const fortune = await getDailyFortune(saju, userName);

// 신규 SDK
import { SajuClient } from '@sajuapi/sdk';
const client = new SajuClient({ apiKey: API_KEY });

// 프로필 생성 (최초 1회)
const profile = await client.profiles.create({
  name: '김철수',
  birthYear: 1990,
  // ...
});

// 운세 조회
const fortune = await client.fortunes.create({
  profileId: profile.id,
  type: 'daily'
});
```

### Python SDK

```bash theme={null}
pip install --upgrade sajuapi
```

```python theme={null}
# 기존 SDK
from sajuapi import get_daily_fortune
fortune = get_daily_fortune(saju, user_name)

# 신규 SDK
from sajuapi import SajuClient
client = SajuClient(api_key=API_KEY)

# 프로필 생성 (최초 1회)
profile = client.profiles.create(
    name="김철수",
    birth_year=1990,
    # ...
)

# 운세 조회
fortune = client.fortunes.create(
    profile_id=profile.id,
    type="daily"
)
```

***

## 체크리스트

<Steps>
  <Step title="프로필 마이그레이션">
    기존 사용자 데이터를 프로필로 등록

    * [ ] 프로필 생성 API 호출
    * [ ] 반환된 프로필 ID 저장
    * [ ] external\_id로 기존 시스템과 연결
  </Step>

  <Step title="코드 업데이트">
    API 호출 코드 수정

    * [ ] 엔드포인트 URL 변경 (/api/\* → /v1/\*)
    * [ ] 요청 본문 형식 변경
    * [ ] Idempotency-Key 헤더 추가
  </Step>

  <Step title="응답 처리">
    응답 파싱 코드 수정

    * [ ] snake\_case 필드명 대응
    * [ ] 새로운 응답 구조 처리
    * [ ] 에러 응답 형식 대응
  </Step>

  <Step title="테스트">
    전체 기능 테스트

    * [ ] 프로필 CRUD 테스트
    * [ ] 운세 생성/조회 테스트
    * [ ] 에러 케이스 테스트
  </Step>

  <Step title="모니터링">
    프로덕션 배포 후 모니터링

    * [ ] Deprecation 헤더 확인
    * [ ] 에러율 모니터링
    * [ ] 성능 비교
  </Step>
</Steps>

***

## 지원

마이그레이션 관련 문의는 아래 채널로 연락해 주세요:

* 이메일: [migration@sajuapi.dev](mailto:migration@sajuapi.dev)
* 슬랙: #sajuapi-support
* 문서: [https://docs.sajuapi.dev/guides/migration](https://docs.sajuapi.dev/guides/migration)
