2025.02.22 - [Python] - [Python]치지직 API를 이용하여 파이썬 코드로 응답받기 - Authorization
[Python]치지직 API를 이용하여 파이썬 코드로 응답받기 - Authorization
https://developers.chzzk.naver.com/ 치지직 CHZZK지금, 스트리밍이 시작됩니다. 치지직-developers.chzzk.naver.com 네이버에서 운영하는 스트리밍 서비스 치지직에서 API를 공식으로 제공하고 있다. 사실, 치지
kante-kante.tistory.com
이전 포스트에서 Access Token을 발급받기 위해 인증(Authorization) 과정을 거쳤다.
API Scope를 등록 할 때 유저 조회와 방송 설정 조회에만 체크했기 때문에 API의 다른 정보들은 추후 권한 승인이 되고 나면 작성해보록 하고, 이번 포스트에서는 User, Channel 정보를 가져오는 간단한 포스트를 작성해보도록 하겠다.
https://chzzk.gitbook.io/chzzk
About CHZZK Developers | CHZZK
치지직 API는 치지직과의 연동 및 기능 사용을 제공합니다. 개발자는 치지직의 API를 사용하여 라이브 조회, 방송 설정 조회 및 변경, 채팅 발송 및 공지 등록 등 치지직에서 제공하는 다양한 기능
chzzk.gitbook.io
치지직 open api 문서는 위와 같다.
User 정보 가져오기
치지직 오픈 API의 엔드포인트가 users/me로 설정되어 있기 때문에 로그인 유저의 치지직 채널 정보만 조회할 수 있도록 처리되어 있다.
유저 API를 호출하기 위해서는 기존 포스트에서 로그인 후 발급 과정을 거쳐 얻은 Access Token이 필요하다. 또 API Scope에서 '유저 정보 조회' Scope에 대해 승인되어 있어야 사용할 수 있다.
만약 다른 유저의 채널 정보를 조회하고 싶다면 비공식 API를 사용해서 처리하는 방법이 있으니 아래에서 간략하게 설명하도록 한다.
HTTP Request
GET /open/v1/users/me
치지직 Open API의 공통 URL은 https://openapi.chzzk.naver.com/ 로 시작한다.
Response Body
Key | Type | Example |
channelId | String | 90950.... |
channelName | String | user123 |
먼저 Open API로 유저 정보를 조회하는 코드는 다음과 같다.
import requests
from chzzk_token import access_token
def get_user_info(channel_id=None):
"""로그인한 유저의 채널 정보를 조회합니다(None인 경우 내 채널 정보를 조회합니다.)"""
url = 'https://openapi.chzzk.naver.com/open/v1/users/me'
headers = {
'User-Agent': 'Mozilla/5.0',
'Content-Type': 'application/json',
'Authorization': f'Bearer {access_token}'
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
user_info = data.get('content', {})
print(f"""
유저 정보:
채널 ID: {user_info.get('channelId')}
채널명: {user_info.get('channelName')}
""")
return user_info
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"Error: {str(e)}")
return None
if __name__ == "__main__":
user_info = get_user_info()
header 정보로 access_token 정보를 같이 보내는데 토큰 타입은 Bearer로 고정이다.
위 코드를 실행하면
아래와 같이 Response Body로 채널 ID와 채널 명 값을 얻을 수 있다.
하지만 openapi가 로그인 유저의 치지직 채널 정보만 조회할 수 있기 때문에 다른 채널의 정보를 얻고 싶다면 아래와 같이 코드를 작성하면 된다.
import requests
from chzzk_token import access_token
def get_other_user_info(channel_id):
"""다른 유저의 채널 정보를 조회합니다."""
url = f'https://api.chzzk.naver.com/service/v1/channels/{channel_id}'
headers = {
'User-Agent': 'Mozilla/5.0',
'Content-Type': 'application/json'
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
channel_info = data.get('content', {})
print(f"""
채널 정보:
채널 ID: {channel_info.get('channelId')}
채널명: {channel_info.get('channelName')}
""")
return channel_info
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"Error: {str(e)}")
return None
if __name__ == "__main__":
user_info = get_user_info()
other_user_info = get_other_user_info("d7ddd7585a271e55159ae47c0ce9a9dd")
위 코드는 치지직 채널 '무한 도전' 채널 정보를 조회하는 코드를 간략하게 작성해보았다.
해당 코드에는 채널ID, 채널명 뿐만 아니라 팔로워,이미지 등 여러 정보가 포함되어 있지만 채널 ID와 채널 명만 가져오도록 처리했다.
해당 코드를 실행해보면
채널 ID와 채널 명 정보를 가져온다.
치지직 채널에서 동일한지 확인해보면 해당 정보와 동일하다는 것을 알 수 있다.
+
https://developers.naver.com/forum/posts/36682
개발자 포럼 - NAVER Developers
developers.naver.com
비공식 API의 경우 반드시 제재가 되는 것은 아니지만, 과도한 API 호출이나 비정상적인 경로로 네이버 쿠키를 사용하여 서비스에 영향을 주는 경우 자동으로 보호조치 처리된다는 답변이 있기 때문에 짧은 기간에 과도한 호출이나 비정상적인 경로로 호출하지 않도록 주의해야 한다.
Channel 정보 가져오기
채널 정보 조회에는 Access Token 정보가 필요하지 않다. 다만 헤더에 clientId, clientSecret 정보를 추가해주어야 채널 정보를 정상적으로 조회할 수 있다.
HTTP Request
GET /open/v1/channels
Requset Param
Field | Type | required | Description |
channelIds | String[] | * | 조회할 채널 ID 목록. 최대 20개까지 요청 가능 |
Response Body
채널 정보 목록과 id, 채널명, 이미지 URL 정보 및 팔로워 수를 가져온다.
위에 표시된 설명대로 최대 20개의 데이터만 가져올 수 있으니 참고한다.
open api를 사용한 코드는 아래와 같이 작성했다.
import requests
from chzzk_token import client_id, Token
def get_channel_info(channel_ids):
"""채널 정보를 조회합니다. channel_id가 None이면 내 채널 정보를 조회합니다."""
url = 'https://openapi.chzzk.naver.com/open/v1/channels'
# Client 인증 헤더 설정
headers = {
'User-Agent': 'Mozilla/5.0',
'Content-Type': 'application/json',
'Client-Id': client_id,
'Client-Secret': Token
}
params = {
'channelIds': ','.join(channel_ids) if isinstance(channel_ids, list) else channel_ids
}
try:
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
data = response.json()
channels = data.get('content', {}).get('data', [])
for channel in channels:
print(f"""
채널 정보:
채널 ID: {channel.get('channelId')}
채널명: {channel.get('channelName')}
채널 이미지: {channel.get('channelImageUrl')}
팔로워 수: {channel.get('followerCount')}
""")
return channels
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"Error: {str(e)}")
return None
if __name__ == "__main__":
# 내 채널 정보 조회
my_channel = get_channel_info()
# # 다른 채널 정보 조회
other_channel = get_channel_info("d7ddd7585a271e55159ae47c0ce9a9dd")
Access Token 발급이 필요하지 않기 때문에 id와 secret key 값을 헤더로 사용하여 클라이언트 인증을 진행한다.
필수 파라미터로 channelIds를 필요로 한다.
해당 코드로 data 오브젝트 값 내에 있는 채널 ID, 채널명, 이미지, 팔로워 수 등등을 가져올 수 있다.
그러면 이렇게 채널 정보를 가져올 수 있다.
비공식 API를 사용해서 채널 정보 조회하기
import requests
from chzzk_token import client_id, Token
# 채널명으로 검색
def search_channel(channel_name):
"""채널명으로 채널을 검색합니다"""
url = 'https://api.chzzk.naver.com/service/v1/search/channels'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Content-Type': 'application/json',
'Referer': 'https://chzzk.naver.com'
}
params = {
'keyword': channel_name,
'offset': 0,
'size': 3, # 검색 결과 개수
'sortType': 'ACCURACY', # 정확도순 정렬
'filterType': 'ALL'
}
try:
response = requests.get(url, headers=headers, params=params)
print(f"Request URL: {response.url}") # 실제 요청 URL 출력
print(f"Response Status: {response.status_code}") # 응답 상태 코드 출력
print(f"Response Headers: {response.headers}") # 응답 헤더 출력
print(f"Response Text: {response.text}") # 응답 내용 출력
if response.status_code == 200:
data = response.json()
channels = data.get('content', {}).get('data', [])
if not channels:
print(f"'{channel_name}' 검색 결과가 없습니다.")
return None
print(f"\n'{channel_name}' 검색 결과:")
for item in channels:
channel = item.get('channel', []) #'channel 객체 접근
print(f"""채널 정보:
채널 ID: {channel.get('channelId')}
채널명: {channel.get('channelName')}
채널 설명: {channel.get('channelDescription')}
팔로워 수: {channel.get('followerCount')}
라이브 여부: {channel.get('openLive', False)}
인증마크: {channel.get('verifiedMark', False)}
""")
return [item['channel'] for item in channels] # channel 객체만 반환
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"Error: {str(e)}")
return None
def get_channel_by_name(channel_name):
"""채널명으로 정확히 일치하는 채널을 찾습니다"""
channels = search_channel(channel_name)
if channels:
# 정확히 일치하는 채널 찾기
exact_match = next(
(ch for ch in channels if ch.get('channelName', '').lower() == channel_name.lower()),
None
)
if exact_match:
return exact_match
else:
print(f"'{channel_name}'과 정확히 일치하는 채널을 찾을 수 없습니다.")
return None
if __name__ == "__main__":
# 채널명으로 검색
ch_res = search_channel("풍월량")
# 정확한 채널명으로 단일 채널 검색
channel = get_channel_by_name("풍월량")
if channel:
print("\n정확히 일치하는 채널:")
print(f"채널 ID: {channel.get('channelId')}")
print(f"채널명: {channel.get('channelName')}")
print(f"팔로워 수: {channel.get('followerCount')}")
기존 open api는 채널ID로 조회했지만 비공식 api를 사용한 경우 채널 명으로 조회하도록 처리했다.
params의 size를 조절하면 원하는 만큼 검색 결과 개수를 출력할 수 있지만 너무 과다한 API 호출을 하지 않도록 유의한다.
이렇게 하면 위와 같이 검색어 기준 상위 3개의 데이터를 가져오고, 정확히 일치하는 채널명을 찾아준다.
'Python' 카테고리의 다른 글
[Python]치지직 API를 이용하여 파이썬 코드로 응답받기 - Authorization (0) | 2025.02.22 |
---|