Skip to main content
Version: v0.2.0

API 클라이언트 도구

D.Hub은 OpenAPI 3.x 스펙을 제공하는 REST API로, 별도의 1차 SDK 없이도 표준 HTTP 클라이언트·자동 생성 SDK·GUI 도구로 모두 호출할 수 있습니다. 본 페이지는 권장 도구들의 짧은 reference와 D.Hub 특유의 사용 패턴(JWT 인증·페이지네이션·에러 응답)을 한 곳에 모읍니다.

사전 준비
  • D.Hub 계정과 API 인증에서 발급한 JWT 토큰
  • 도구마다 다른 설치 환경 (각 섹션 참고)
dhub2 자체 SDK는 없습니다

2026년 5월 현재 D.Hub은 1차 SDK 패키지(예: dhub-python, dhub-typescript)를 제공하지 않습니다. 자동 생성 SDK 또는 아래 HTTP 클라이언트 직접 호출을 권장합니다. 향후 1차 SDK가 출시되면 본 페이지에 추가됩니다.

명령줄 도구 (CLI)

cURL

가장 보편적인 HTTP 클라이언트로, 모든 OS에 사전 설치되어 있습니다.

# GET 목록 (Bearer 토큰)
curl -H "Authorization: Bearer ${TOKEN}" \
https://{host}/api/v1/collections

# POST 생성
curl -X POST https://{host}/api/v1/collections \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{"name": "my-collection"}'

# 파일 업로드 (multipart, 파일 필드 이름은 files)
curl -X POST https://{host}/api/v1/datasets/${DATASET_ID}/upload \
-H "Authorization: Bearer ${TOKEN}" \
-F "files=@./data.csv"

# 응답 파싱 (jq)
RESP=$(curl -s -H "Authorization: Bearer ${TOKEN}" https://{host}/api/v1/datasets)
echo "$RESP" | jq -r '.[].id'

API 튜토리얼이 동일 패턴을 6 step으로 전개합니다.

HTTPie

사람 친화적 syntax를 가진 CLI 도구. JSON body 작성·검색 헤더 표시·색상 출력이 모두 자동.

# 설치
brew install httpie # macOS
pip install httpie # Python 환경

# GET 호출
http GET https://{host}/api/v1/collections \
Authorization:"Bearer ${TOKEN}"

# POST (필드 = key=value, JSON body 자동 생성)
http POST https://{host}/api/v1/collections \
Authorization:"Bearer ${TOKEN}" \
name="my-collection" \
description="HTTPie 예제"

Postman / Insomnia

GUI 클라이언트. D.Hub OpenAPI 스펙 URL을 직접 import하면 전체 endpoint collection이 자동 생성됩니다.

  1. Postman → ImportLinkhttps://{host}/api/v1/openapi.json 입력
  2. Environment 변수에 host·token 등록 후 collection 전체에서 재사용
  3. 각 endpoint의 Code 탭에서 cURL·Python·Node.js 코드 즉시 생성 가능

CI·자동화 용도로는 적합하지 않으므로, 탐색·디버깅 단계에서만 권장합니다.

언어별 HTTP 클라이언트

Python (requests)

표준 HTTP 라이브러리. cURL 트랙과 1:1 매핑되며 세션 클래스로 wrapper를 만들면 인증 헤더가 재사용됩니다.

import requests

class DHubClient:
def __init__(self, host: str, token: str):
self.host = host
self.session = requests.Session()
self.session.headers["Authorization"] = f"Bearer {token}"

def get(self, path, **params):
r = self.session.get(f"{self.host}{path}", params=params)
r.raise_for_status()
return r.json()

def post(self, path, json):
r = self.session.post(f"{self.host}{path}", json=json)
r.raise_for_status()
return r.json()

client = DHubClient("https://{host}", "${TOKEN}")
collection = client.post("/api/v1/collections", {"name": "my-collection"})
print(collection["id"])

페이지네이션 헬퍼 (커서 기반, 제너레이터 패턴):

def list_all(client: DHubClient, path: str, limit: int = 100):
cursor = None
while True:
params = {"limit": limit}
if cursor:
params["cursor"] = cursor
page = client.get(path, **params)
items = page["items"] if isinstance(page, dict) else page
yield from items
cursor = page.get("next_cursor") if isinstance(page, dict) else None
if not cursor:
return

for dataset in list_all(client, "/api/v1/datasets"):
print(dataset["id"], dataset["name"])

JavaScript / Node.js (fetch)

Node 18+ 내장 fetch. 브라우저 환경에서 사용하려면 D.Hub의 CORS_ORIGINS 설정에 도메인이 포함되어야 합니다.

const headers = {
"Authorization": `Bearer ${TOKEN}`,
"Content-Type": "application/json",
};

// GET 목록
const list = await fetch(`https://${host}/api/v1/collections`, { headers })
.then((r) => r.json());

// POST 생성
const created = await fetch(`https://${host}/api/v1/collections`, {
method: "POST",
headers,
body: JSON.stringify({ name: "my-collection" }),
}).then((r) => r.json());

자동 생성 SDK (openapi-generator-cli)

D.Hub OpenAPI 스펙으로부터 typed client를 자동 생성합니다.

# 스펙 다운로드 (인증이 활성화된 환경이면 토큰 헤더 필요)
curl -H "Authorization: Bearer ${TOKEN}" \
-o openapi.json https://{host}/api/v1/openapi.json

# Python 클라이언트 생성
npx @openapitools/openapi-generator-cli generate \
-i ./openapi.json \
-g python \
-o ./dhub2-client-python

# TypeScript (axios) 클라이언트 생성
npx @openapitools/openapi-generator-cli generate \
-i ./openapi.json \
-g typescript-axios \
-o ./dhub2-client-ts

지원 generator는 50+ (Python · TypeScript · Go · Java · Kotlin · Ruby 등). 빌드된 SDK는 PyPI/npm/Maven에 사내 배포해 팀 단위로 재사용할 수 있습니다.

Generator언어비고
pythonPython 3sync (urllib3), 표준 권장
python-pydantic-v1Python 3Pydantic v1 기반 model
typescript-axiosTypeScriptAxios 기반, Node·브라우저 모두 동작
typescript-fetchTypeScriptfetch 기반, 의존성 적음
goGonet/http 기반
javaJava 8+Spring·Maven 통합

전체 generator 목록은 npx @openapitools/openapi-generator-cli list로 확인합니다.

에러 처리 패턴

API 응답의 4xx/5xx는 에러 처리 페이지의 모델을 따릅니다. 핵심 분기:

  • 401 / 403: 토큰 만료·권한 부족 → 토큰 재발급 또는 권한 점검 (API 인증)
  • 422 Unprocessable Entity: validation 실패 → detail[] array를 파싱해 어떤 필드가 잘못되었는지 표시
  • 5xx: 일시적 서버 오류 → exponential backoff (1s → 2s → 4s …) 최대 5회 retry 권장
import time

def with_retry(call, max_retries=5):
for attempt in range(max_retries):
try:
return call()
except requests.HTTPError as e:
if 500 <= e.response.status_code < 600 and attempt < max_retries - 1:
time.sleep(2 ** attempt)
continue
raise

페이지네이션 / 정렬 / 필터링

  • 페이지네이션: limit · cursor 쿼리 파라미터(커서 기반, 응답의 next_cursor 사용) — 개발자 가이드 개요 참고
  • 정렬: sort 쿼리 파라미터 (지원 endpoint에 한함). 일반적으로 -created_at 같은 prefix -로 내림차순
  • 필터링: 리소스별 query parameter. 각 endpoint의 자동 생성 API 레퍼런스 페이지의 Parameters 절 참고

다음 단계