첫 API 호출

OAuth 인증 후 첫 번째 API를 호출해보세요.

첫 API 호출#

발급받은 API 자격 증명을 사용하여 첫 번째 API를 호출해보겠습니다.

Step 1: Access Token 발급#

OAuth 2.0 Client Credentials 플로우를 사용하여 Access Token을 발급받습니다.

Access Token 발급

cURL:

curl -X POST https://sandbox.api.onda.me/v1/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"

Python:

import requests

response = requests.post(
    "https://sandbox.api.onda.me/v1/oauth/token",
    data={
        "grant_type": "client_credentials",
        "client_id": "YOUR_CLIENT_ID",
        "client_secret": "YOUR_CLIENT_SECRET",
    },
)
token_data = response.json()
access_token = token_data["access_token"]
print(f"Access Token: {access_token}")

Node.js:

const response = await fetch("https://sandbox.api.onda.me/v1/oauth/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "client_credentials",
    client_id: "YOUR_CLIENT_ID",
    client_secret: "YOUR_CLIENT_SECRET",
  }),
});

const tokenData = await response.json();
const accessToken = tokenData.access_token;
console.log("Access Token:", accessToken);

응답 예시:

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 900,
  "scope": "read write"
}

Access Token은 15분(900초) 동안 유효합니다. 만료 전에 Refresh Token을 사용하여 갱신하세요.

Step 2: 숙소 목록 조회#

발급받은 Access Token을 사용하여 숙소 목록을 조회합니다.

숙소 목록 조회

cURL:

curl -X GET "https://sandbox.api.onda.me/v1/properties?limit=10" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Accept: application/json"

Python:

import requests

headers = {
    "Authorization": f"Bearer {access_token}",
    "Accept": "application/json",
}

response = requests.get(
    "https://sandbox.api.onda.me/v1/properties",
    headers=headers,
    params={"limit": 10},
)

properties = response.json()
print(f"총 {len(properties['data'])}개 숙소 조회됨")
for prop in properties['data']:
    print(f"- {prop['name']} ({prop['city']})")

Node.js:

const response = await fetch(
  "https://sandbox.api.onda.me/v1/properties?limit=10",
  {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      Accept: "application/json",
    },
  }
);

const properties = await response.json();
console.log(`총 ${properties.data.length}개 숙소 조회됨`);
properties.data.forEach(prop => {
  console.log(`- ${prop.name} (${prop.city})`);
});

Step 3: 응답 확인#

API 호출이 성공하면 다음과 같은 응답을 받습니다:

{
  "data": [
    {
      "id": "prop_123456",
      "name": "서울 센트럴 호텔",
      "type": "hotel",
      "star_rating": 5,
      "city": "서울",
      "district": "강남구",
      "address": "서울특별시 강남구 테헤란로 123",
      "latitude": 37.5012,
      "longitude": 127.0396,
      "description": "강남 중심부에 위치한 5성급 비즈니스 호텔",
      "amenities": ["wifi", "parking", "breakfast", "gym", "pool"],
      "images": [
        {
          "url": "https://cdn.onda.me/properties/prop_123456/main.jpg",
          "type": "main",
          "caption": "호텔 전경"
        }
      ],
      "check_in_time": "15:00",
      "check_out_time": "11:00"
    },
    // ... 더 많은 숙소
  ],
  "meta": {
    "total": 156,
    "page": 1,
    "limit": 10,
    "has_more": true
  }
}

에러 처리 기본#

API 호출 시 발생할 수 있는 주요 에러:

401 Unauthorized#

{
  "error": "invalid_token",
  "error_description": "The access token is invalid or has expired"
}

해결 방법: Access Token을 재발급하거나 Refresh Token으로 갱신하세요.

400 Bad Request#

{
  "error": "invalid_request",
  "error_description": "Missing required parameter: grant_type",
  "validation_errors": [
    {
      "field": "grant_type",
      "message": "This field is required"
    }
  ]
}

해결 방법: 요청 파라미터를 확인하고 누락된 필수 값을 추가하세요.

429 Too Many Requests#

{
  "error": "rate_limit_exceeded",
  "error_description": "API rate limit exceeded. Please retry after 60 seconds",
  "retry_after": 60
}

해결 방법: retry_after 초 후에 재시도하세요. Rate limit은 분당 1000건입니다.

다음 단계#

축하합니다! 첫 API 호출에 성공하셨습니다. 이제 다음 내용을 학습해보세요:

전체 예제 코드#

전체 플로우를 구현한 예제 코드:

전체 예제 (Python)

import requests
from datetime import datetime, timedelta

class OndaAPI:
    def __init__(self, client_id, client_secret, base_url="https://sandbox.api.onda.me/v1"):
        self.client_id = client_id
        self.client_secret = client_secret
        self.base_url = base_url
        self.access_token = None

    def get_access_token(self):
        """Access Token 발급"""
        response = requests.post(
            f"{self.base_url}/oauth/token",
            data={
                "grant_type": "client_credentials",
                "client_id": self.client_id,
                "client_secret": self.client_secret,
            },
        )
        response.raise_for_status()
        self.access_token = response.json()["access_token"]
        return self.access_token

    def get_properties(self, limit=10):
        """숙소 목록 조회"""
        if not self.access_token:
            self.get_access_token()

        headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Accept": "application/json",
        }

        response = requests.get(
            f"{self.base_url}/properties",
            headers=headers,
            params={"limit": limit},
        )
        response.raise_for_status()
        return response.json()

# 사용 예시
api = OndaAPI(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET"
)

properties = api.get_properties(limit=5)
print(f"총 {properties['meta']['total']}개 숙소 중 {len(properties['data'])}개 조회")
for prop in properties['data']:
    print(f"- {prop['name']} (⭐ {prop['star_rating']}성급)")