Snipe-IT API 완전 분석 – 주요 엔드포인트와 활용법




API 구조 개요

Snipe-IT API는 RESTful 설계 원칙을 따르며, 다음과 같은 구조로 구성됩니다:

Base URL Structure:

https://your-domain.com/api/v1/{resource}

HTTP 메소드별 용도:

  • GET: 데이터 조회
  • POST: 새 데이터 생성
  • PUT/PATCH: 기존 데이터 수정
  • DELETE: 데이터 삭제

Assets API – 자산 관리의 핵심

Assets API는 Snipe-IT의 가장 중요한 API로, 모든 하드웨어 자산을 관리합니다.

주요 엔드포인트:

메소드엔드포인트목적
GET/hardware모든 자산 조회
GET/hardware/{id}특정 자산 상세 조회
POST/hardware새 자산 생성
PUT/hardware/{id}자산 정보 수정
DELETE/hardware/{id}자산 삭제
POST/hardware/{id}/checkout자산 체크아웃
POST/hardware/{id}/checkin자산 체크인

자산 조회 (GET /hardware)

기본 요청:

pythonimport requests

headers = {
    'Authorization': 'Bearer your-token',
    'Accept': 'application/json'
}

response = requests.get(
    'https://your-domain.com/api/v1/hardware',
    headers=headers
)

고급 필터링:

python# 특정 상태의 자산만 조회
params = {
    'status': 'Ready to Deploy',
    'limit': 50,
    'offset': 0,
    'sort': 'created_at',
    'order': 'desc'
}

response = requests.get(
    'https://your-domain.com/api/v1/hardware',
    headers=headers,
    params=params
)

응답 구조:

json{
  "total": 150,
  "rows": [
    {
      "id": 1,
      "name": "Dell-Laptop-001",
      "asset_tag": "DL001",
      "serial": "ABC123DEF",
      "model": {
        "id": 5,
        "name": "Dell Latitude 7420"
      },
      "status_label": {
        "id": 1,
        "name": "Ready to Deploy",
        "status_type": "deployable"
      },
      "assigned_to": {
        "id": 10,
        "name": "홍길동",
        "type": "user"
      },
      "location": {
        "id": 2,
        "name": "서울 본사"
      },
      "purchase_date": "2023-01-15",
      "purchase_cost": "1500000",
      "notes": "신입사원용 노트북"
    }
  ]
}

자산 생성 (POST /hardware)

pythonnew_asset = {
    "name": "New Dell Laptop",
    "asset_tag": "DL002",
    "model_id": 5,
    "status_id": 1,
    "purchase_date": "2024-01-15",
    "purchase_cost": "1600000",
    "supplier_id": 1,
    "location_id": 2,
    "notes": "신규 구매 장비"
}

response = requests.post(
    'https://your-domain.com/api/v1/hardware',
    headers=headers,
    json=new_asset
)

체크아웃 (POST /hardware/{id}/checkout)

pythoncheckout_data = {
    "assigned_user": 15,  # 사용자 ID
    "checkout_at": "2024-01-20 09:00:00",
    "expected_checkin": "2024-12-31",
    "note": "신입사원 지급"
}

response = requests.post(
    f'https://your-domain.com/api/v1/hardware/{asset_id}/checkout',
    headers=headers,
    json=checkout_data
)

Users API – 사용자 관리

사용자 정보를 관리하고 자산 할당 현황을 추적합니다.

주요 엔드포인트:

메소드엔드포인트목적
GET/users모든 사용자 조회
GET/users/{id}특정 사용자 상세 조회
POST/users새 사용자 생성
PUT/users/{id}사용자 정보 수정
GET/users/{id}/assets사용자 할당 자산 조회

사용자별 할당 자산 조회:

pythondef get_user_assets(user_id):
    """특정 사용자에게 할당된 모든 자산 조회"""
    response = requests.get(
        f'https://your-domain.com/api/v1/users/{user_id}/assets',
        headers=headers
    )
    
    if response.status_code == 200:
        assets = response.json()['rows']
        print(f"사용자 {user_id}에게 할당된 자산: {len(assets)}개")
        
        for asset in assets:
            print(f"- {asset['name']} ({asset['asset_tag']})")
    
    return response.json()

Categories, Manufacturers, Models API

자산 분류 및 메타데이터를 관리합니다.

Categories API (자산 카테고리)

python# 모든 카테고리 조회
response = requests.get(
    'https://your-domain.com/api/v1/categories',
    headers=headers
)

# 새 카테고리 생성
new_category = {
    "name": "모바일 기기",
    "category_type": "asset",
    "eula_text": "모바일 기기 사용 약관..."
}

response = requests.post(
    'https://your-domain.com/api/v1/categories',
    headers=headers,
    json=new_category
)

Manufacturers API (제조사)

python# 제조사 목록 조회
manufacturers = requests.get(
    'https://your-domain.com/api/v1/manufacturers',
    headers=headers
).json()

# 새 제조사 추가
new_manufacturer = {
    "name": "삼성전자",
    "url": "https://www.samsung.com",
    "support_url": "https://www.samsung.com/sec/support/",
    "support_phone": "1588-3366"
}

response = requests.post(
    'https://your-domain.com/api/v1/manufacturers',
    headers=headers,
    json=new_manufacturer
)

Models API (모델)

python# 특정 제조사의 모델 조회
def get_models_by_manufacturer(manufacturer_id):
    params = {'manufacturer_id': manufacturer_id}
    
    response = requests.get(
        'https://your-domain.com/api/v1/models',
        headers=headers,
        params=params
    )
    
    return response.json()

# 새 모델 생성
new_model = {
    "name": "Galaxy Book Pro 360",
    "manufacturer_id": 3,
    "category_id": 1,
    "model_number": "NP950QDB-KC1KR",
    "notes": "13.3인치 2-in-1 노트북"
}

response = requests.post(
    'https://your-domain.com/api/v1/models',
    headers=headers,
    json=new_model
)

Locations, Departments API

조직 구조와 위치 정보를 관리합니다.

Locations API

python# 계층적 위치 구조 조회
def get_location_hierarchy():
    """모든 위치를 계층 구조로 정리"""
    response = requests.get(
        'https://your-domain.com/api/v1/locations',
        headers=headers
    )
    
    locations = response.json()['rows']
    
    # 부모-자식 관계 정리
    hierarchy = {}
    for location in locations:
        parent_id = location.get('parent_id')
        if parent_id is None:
            # 최상위 위치
            hierarchy[location['id']] = {
                'name': location['name'],
                'children': []
            }
    
    return hierarchy

# 새 위치 생성
new_location = {
    "name": "부산 지점",
    "address": "부산광역시 해운대구 센텀중앙로 123",
    "city": "부산",
    "state": "부산광역시",
    "country": "KR",
    "zip": "48058",
    "parent_id": 1  # 본사 하위 위치
}

Departments API

python# 부서별 자산 현황 조회
def get_department_assets(department_id):
    """특정 부서의 자산 현황"""
    # 부서 소속 사용자 조회
    users_response = requests.get(
        f'https://your-domain.com/api/v1/users',
        headers=headers,
        params={'department_id': department_id}
    )
    
    users = users_response.json()['rows']
    department_assets = []
    
    for user in users:
        # 각 사용자의 할당 자산 조회
        assets_response = requests.get(
            f'https://your-domain.com/api/v1/users/{user["id"]}/assets',
            headers=headers
        )
        
        if assets_response.status_code == 200:
            user_assets = assets_response.json()['rows']
            department_assets.extend(user_assets)
    
    return department_assets

Reports 및 Dashboard API

다양한 리포트와 대시보드 데이터를 제공합니다.

Activity Log API

python# 최근 활동 로그 조회
def get_recent_activities(days=7):
    """최근 N일간의 활동 로그"""
    from datetime import datetime, timedelta
    
    start_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
    
    params = {
        'start_date': start_date,
        'limit': 100
    }
    
    response = requests.get(
        'https://your-domain.com/api/v1/reports/activity',
        headers=headers,
        params=params
    )
    
    return response.json()

Custom Fields API

python# 사용자 정의 필드 조회
def get_custom_fields():
    """모든 커스텀 필드 정보"""
    response = requests.get(
        'https://your-domain.com/api/v1/fields',
        headers=headers
    )
    
    fields = response.json()['rows']
    
    for field in fields:
        print(f"필드명: {field['name']}")
        print(f"필드 타입: {field['element']}")
        print(f"필수 여부: {field['required']}")
        print("---")
    
    return fields

통합 활용 예시

여러 API를 조합하여 복잡한 작업을 수행하는 예시입니다.

pythondef create_complete_asset_profile():
    """자산 프로필 완전 생성 (제조사→모델→자산)"""
    
    # 1. 제조사 생성 또는 확인
    manufacturer_data = {
        "name": "Apple Inc.",
        "url": "https://www.apple.com"
    }
    
    manufacturer_response = requests.post(
        'https://your-domain.com/api/v1/manufacturers',
        headers=headers,
        json=manufacturer_data
    )
    manufacturer_id = manufacturer_response.json()['payload']['id']
    
    # 2. 카테고리 확인
    categories = requests.get(
        'https://your-domain.com/api/v1/categories',
        headers=headers
    ).json()['rows']
    
    laptop_category = next(
        (cat for cat in categories if 'laptop' in cat['name'].lower()),
        None
    )
    
    # 3. 모델 생성
    model_data = {
        "name": "MacBook Pro 16-inch",
        "manufacturer_id": manufacturer_id,
        "category_id": laptop_category['id'],
        "model_number": "MVVJ2KH/A"
    }
    
    model_response = requests.post(
        'https://your-domain.com/api/v1/models',
        headers=headers,
        json=model_data
    )
    model_id = model_response.json()['payload']['id']
    
    # 4. 자산 생성
    asset_data = {
        "name": "MacBook Pro - DEV001",
        "asset_tag": "MBP001",
        "model_id": model_id,
        "status_id": 1,  # Ready to Deploy
        "purchase_date": "2024-01-15",
        "purchase_cost": "3500000"
    }
    
    asset_response = requests.post(
        'https://your-domain.com/api/v1/hardware',
        headers=headers,
        json=asset_data
    )
    
    return asset_response.json()

API 응답 처리 및 오류 핸들링

pythondef handle_api_response(response):
    """API 응답 통합 처리"""
    if response.status_code == 200:
        return {
            'success': True,
            'data': response.json()
        }
    elif response.status_code == 422:
        # 유효성 검사 오류
        errors = response.json().get('messages', {})
        return {
            'success': False,
            'error': 'Validation Error',
            'details': errors
        }
    elif response.status_code == 404:
        return {
            'success': False,
            'error': 'Resource Not Found'
        }
    else:
        return {
            'success': False,
            'error': f'HTTP {response.status_code}',
            'details': response.text
        }

이제 Snipe-IT의 모든 주요 API를 마스터했습니다!




Leave a Comment