APIサンプルコード集
SURP MDM APIの実践的な使用例を、プログラミング言語別にまとめたリファレンスです。
📋 概要
このページでは、以下のプログラミング言語でのサンプルコードを提供します:
- JavaScript/TypeScript (Node.js, ブラウザ)
- Python
- PHP
- cURL (コマンドライン)
🔐 認証
すべてのリクエストにAuthorizationヘッダーが必要です。
cURL
curl -X GET "https://mdm.surp.tech/api/v1/definitions" \
-H "Authorization: Bearer sk_live_your_api_key_here" \
-H "Accept: application/json"
JavaScript (fetch)
const API_KEY = 'sk_live_your_api_key_here';
const BASE_URL = 'https://mdm.surp.tech/api/v1';
const response = await fetch(`${BASE_URL}/definitions`, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Accept': 'application/json'
}
});
const data = await response.json();
Python
import requests
API_KEY = 'sk_live_your_api_key_here'
BASE_URL = 'https://mdm.surp.tech/api/v1'
headers = {
'Authorization': f'Bearer {API_KEY}',
'Accept': 'application/json'
}
response = requests.get(f'{BASE_URL}/definitions', headers=headers)
data = response.json()
PHP
<?php
$apiKey = 'sk_live_your_api_key_here';
$baseUrl = 'https://mdm.surp.tech/api/v1';
$ch = curl_init("{$baseUrl}/definitions");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$apiKey}",
'Accept: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
?>
📖 マスター定義の取得
JavaScript
async function getDefinitions() {
const response = await fetch(`${BASE_URL}/definitions`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.items;
}
// 使用例
const definitions = await getDefinitions();
console.log(definitions);
Python
def get_definitions():
response = requests.get(
f'{BASE_URL}/definitions',
headers=headers
)
response.raise_for_status()
return response.json()['items']
# 使用例
definitions = get_definitions()
print(definitions)
📊 マスターデータの取得
ページネーション付き取得
JavaScript
async function getMasters(masterType, skip = 0, limit = 100) {
const url = `${BASE_URL}/masters/${masterType}?skip=${skip}&limit=${limit}`;
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
const data = await response.json();
return {
items: data.items,
total: data.total
};
}
// 使用例
const { items, total } = await getMasters('department', 0, 100);
console.log(`取得: ${items.length}件 / 全体: ${total}件`);
Python
def get_masters(master_type, skip=0, limit=100):
url = f'{BASE_URL}/masters/{master_type}'
params = {'skip': skip, 'limit': limit}
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
return {
'items': data['items'],
'total': data['total']
}
# 使用例
result = get_masters('department', skip=0, limit=100)
print(f"取得: {len(result['items'])}件 / 全体: {result['total']}件")
全データの取得(ページネーション自動処理)
JavaScript
async function getAllMasters(masterType) {
let allItems = [];
let skip = 0;
const limit = 100;
let total = 0;
do {
const { items, total: t } = await getMasters(masterType, skip, limit);
allItems = allItems.concat(items);
total = t;
skip += limit;
} while (allItems.length < total);
return allItems;
}
// 使用例
const allDepartments = await getAllMasters('department');
console.log(`全${allDepartments.length}件取得完了`);
Python
def get_all_masters(master_type):
all_items = []
skip = 0
limit = 100
while True:
result = get_masters(master_type, skip, limit)
all_items.extend(result['items'])
if len(all_items) >= result['total']:
break
skip += limit
return all_items
# 使用例
all_departments = get_all_masters('department')
print(f'全{len(all_departments)}件取得完了')
✏️ データの作成
JavaScript
async function createMaster(masterType, data) {
const response = await fetch(`${BASE_URL}/masters/${masterType}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ data })
});
if (response.status === 202) {
// 承認リクエストが作成された
const result = await response.json();
console.log('承認リクエスト作成:', result.approval_request_id);
return result;
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// 使用例
const newDept = await createMaster('department', {
departmentCode: 'D001',
departmentName: '営業部',
status: 'active'
});
console.log('作成完了:', newDept.id);
Python
def create_master(master_type, data):
url = f'{BASE_URL}/masters/{master_type}'
response = requests.post(
url,
headers={**headers, 'Content-Type': 'application/json'},
json={'data': data}
)
if response.status_code == 202:
# 承認リクエストが作成された
result = response.json()
print(f"承認リクエスト作成: {result['approval_request_id']}")
return result
response.raise_for_status()
return response.json()
# 使用例
new_dept = create_master('department', {
'departmentCode': 'D001',
'departmentName': '営業部',
'status': 'active'
})
print(f"作成完了: {new_dept['id']}")
🔄 データの更新
JavaScript
async function updateMaster(masterType, id, data) {
const response = await fetch(`${BASE_URL}/masters/${masterType}/${id}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ data })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// 使用例
const updated = await updateMaster('department', 'dept-id-123', {
departmentName: '営業第一部'
});
Python
def update_master(master_type, id, data):
url = f'{BASE_URL}/masters/{master_type}/{id}'
response = requests.put(
url,
headers={**headers, 'Content-Type': 'application/json'},
json={'data': data}
)
response.raise_for_status()
return response.json()
# 使用例
updated = update_master('department', 'dept-id-123', {
'departmentName': '営業第一部'
})
🗑️ データの削除
JavaScript
async function deleteMaster(masterType, id) {
const response = await fetch(`${BASE_URL}/masters/${masterType}/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// 使用例
await deleteMaster('department', 'dept-id-123');
console.log('削除完了');
Python
def delete_master(master_type, id):
url = f'{BASE_URL}/masters/{master_type}/{id}'
response = requests.delete(url, headers=headers)
response.raise_for_status()
return response.json()
# 使用例
delete_master('department', 'dept-id-123')
print('削除完了')
📥 CSVエクスポート
JavaScript
async function exportCSV(masterType) {
const response = await fetch(`${BASE_URL}/masters/${masterType}/export`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${masterType}.csv`;
a.click();
}
// 使用例
await exportCSV('department');
Python
def export_csv(master_type, output_path):
url = f'{BASE_URL}/masters/{master_type}/export'
response = requests.get(url, headers=headers)
response.raise_for_status()
with open(output_path, 'wb') as f:
f.write(response.content)
print(f'エクスポート完了: {output_path}')
# 使用例
export_csv('department', 'departments.csv')
📤 CSVインポート
JavaScript
async function importCSV(masterType, file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${BASE_URL}/masters/${masterType}/import`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`
},
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// 使用例
const fileInput = document.querySelector('input[type="file"]');
const result = await importCSV('department', fileInput.files[0]);
console.log(`インポート完了: ${result.success_count}件成功`);
Python
def import_csv(master_type, file_path):
url = f'{BASE_URL}/masters/{master_type}/import'
with open(file_path, 'rb') as f:
files = {'file': f}
response = requests.post(
url,
headers={'Authorization': f'Bearer {API_KEY}'},
files=files
)
response.raise_for_status()
result = response.json()
print(f"インポート完了: {result['success_count']}件成功")
return result
# 使用例
import_csv('department', 'departments.csv')
⚠️ エラーハンドリング
JavaScript
async function safeFetch(url, options) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
// レート制限
console.log('レート制限超過。60秒待機します...');
await new Promise(resolve => setTimeout(resolve, 60000));
return safeFetch(url, options); // リトライ
}
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || `HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API error:', error.message);
throw error;
}
}
Python
import time
def safe_request(method, url, **kwargs):
max_retries = 3
for attempt in range(max_retries):
try:
response = requests.request(method, url, **kwargs)
if response.status_code == 429:
# レート制限
print('レート制限超過。60秒待機します...')
time.sleep(60)
continue
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise
print(f'リトライ {attempt + 1}/{max_retries}')
time.sleep(5)
🔗 関連ガイド
- API入門ガイド - APIの基本
- APIエンドポイント一覧 - すべてのエンドポイント
- エラーメッセージ一覧 - エラーコードの説明
📞 サポート
サンプルコードに関する質問は、よくある質問をご覧いただくか、システム管理者にお問い合わせください。