1. 데이터베이스 연동을 통한 동적 API 요청 생성
실제 테스트 환경에서는 데이터베이스(DB)에 저장된 데이터를 불러와 API 요청의 페이로드(Payload)로 구성해야 하는 경우가 많습니다. 다음은 MySQL에서 장치 정보를 조회하여 복잡한 JSON 구조의 API 요청 본문을 생성하고 전송하는 예제입니다.
import requests
import pymysql
import json
def sync_db_to_api():
# 데이터베이스 연결 설정
db_config = {
"host": "172.16.11.118",
"port": 3306,
"user": "root",
"password": "your_password",
"database": "digital_energy_base",
"cursorclass": pymysql.cursors.DictCursor
}
connection = pymysql.connect(**db_config)
try:
with connection.cursor() as cursor:
# 테스트에 필요한 기초 데이터 조회
query = "SELECT * FROM t_bus_col_point WHERE status = 1"
cursor.execute(query)
db_records = cursor.fetchall()
endpoint_url = "http://172.16.11.118/api/collect-template"
request_headers = {
"Content-Type": "application/json;charset=UTF-8",
"Authorization": "Bearer your_token_here"
}
# API 요청 바디 초기 구조 설정
api_payload = {
"templateName": "modbus_config_v1",
"protocolType": "MODBUS_TCP",
"description": "Auto-generated template",
"dataPoints": []
}
# DB 레코드를 기반으로 리스트 생성
for idx, record in enumerate(db_records):
point_entry = {
"name": record["name"],
"alias": record["name"],
"interval": 15,
"modbusAddress": f"{idx * 4}",
"valueType": "FLOAT32",
"calcLogic": record["calculate_type"],
"unit": record.get("unit", "N/A")
}
api_payload["dataPoints"].append(point_entry)
# POST 요청 실행
response = requests.post(endpoint_url, json=api_payload, headers=request_headers)
print(f"Status Code: {response.status_code}, Response: {response.text}")
finally:
connection.close()
if __name__ == "__main__":
sync_db_to_api()
2. 재귀 함수를 이용한 계층형 데이터 삭제 처리
트리(Tree) 구조로 이루어진 조직도나 카테고리 데이터를 처리할 때, 하위 노드부터 순차적으로 탐색하여 특정 작업을 수행해야 할 때가 있습니다. 다음은 재귀적으로 자식 노드를 찾아 최하위 노드부터 API로 삭제하는 로직입니다.
import requests
def cleanup_hierarchy(node_list, auth_headers):
"""
트리 구조를 탐색하며 자식이 없는 리프(Leaf) 노드부터 삭제 API를 호출합니다.
"""
base_api_url = "https://api.example.com/v1/organization"
for node in node_list:
node_id = node.get('id')
children = node.get('children', [])
if not children:
# 하위 노드가 없는 경우 삭제 API 호출
delete_url = f"{base_api_url}/{node_id}"
res = requests.delete(url=delete_url, headers=auth_headers)
if res.status_code == 200:
print(f"Successfully deleted node: {node_id}")
else:
# 자식 노드가 있다면 재귀적으로 탐색
cleanup_hierarchy(children, auth_headers)
def start_cleanup():
headers = {"Authorization": "Bearer sample_session_token"}
tree_fetch_url = "https://api.example.com/v1/organization/tree/root_id"
response = requests.get(tree_fetch_url, headers=headers)
org_data = response.json().get('data', [])
if org_data:
cleanup_hierarchy(org_data, headers)
if __name__ == "__main__":
start_cleanup()
3. Swagger API 문서를 분석하여 엑셀 명세서 자동 생성
Swagger(OpenAPI v2)의 JSON 엔드포인트를 분석하여 API 경로, 메소드, 파라미터 등의 정보를 추출하고, 이를 Pandas 라이브러리를 통해 엑셀 파일로 저장하는 자동화 스크립트입니다.
import requests
import pandas as pd
def export_swagger_to_excel(swagger_url, output_file):
try:
response = requests.get(swagger_url)
spec = response.json()
definitions = spec.get('definitions', {})
paths = spec.get('paths', {})
extracted_data = []
for path, methods in paths.items():
for method_type, details in methods.items():
# 기본 정보 추출
tag = details.get('tags', ['None'])[0]
summary = details.get('summary', 'No description')
# 파라미터 분석 로직
param_info = "N/A"
parameters = details.get('parameters', [])
if parameters:
first_param = parameters[0]
if 'schema' in first_param and '$ref' in first_param['schema']:
# Definition 참조 모델 파싱
ref_path = first_param['schema']['$ref'].split('/')[-1]
param_info = str(definitions.get(ref_path, {}).get('properties', {}))
else:
param_info = str(parameters)
extracted_data.append({
"Path": path,
"Method": method_type.upper(),
"Tag": tag,
"Description": summary,
"Parameters": param_info
})
# DataFrame 생성 및 엑셀 저장
df = pd.DataFrame(extracted_data)
df.to_excel(output_file, index=False)
print(f"API documentation saved to {output_file}")
except Exception as e:
print(f"Error occurred: {e}")
if __name__ == "__main__":
SWAGGER_JSON_URL = "http://localhost:8080/v2/api-docs"
export_swagger_to_excel(SWAGGER_JSON_URL, "api_inventory.xlsx")