thumbnail image

[파이썬] 티스토리 API - 카테고리 목록 가져오기

Taedi

·

2021. 2. 16. 23:06

반응형

티스토리 API를 이용해 글을 작성하거나 수정하기 위해서는 카테고리 번호를 파라미터로 입력해야 하기 때문에 오늘은 블로그에 존재하는 카테고리 목록을 가져오는 도전을 해보았습니다. 앞서 포스트 목록을 가져오는 단계에서 많은 삽질을 한 덕분에 꽤 수월하게 처리할 수 있었습니다.

 

시작에 앞서 어김없이 티스토리에서 제공하는 '오픈 API 가이드'를 확인하여 보았습니다.

티스토리 오픈 API 카테고리 목록 설명

 

처음엔 API 가이드가 아주 불친절하다고 생각했는데 이제는 위의 주소에 아래의 파라미터 값을 적절하게 넣어서 호출하면 되겠구나.. 하는 어렴풋한 개념이 자리 잡아가고 있습니다. 역시 서투른 목수가 연장 탓을 한다고... 다만, 응답 item이 5개라고 설명하고 있으나 실제로는 6개의 item이 응답되고 있습니다.

 

import requests

appid = ""
access_token = ""
callback_url = ""
blogName = ""

def list_of_Category():
    url = "https://www.tistory.com/apis/category/list"

    params = {
        'access_token': access_token,
        'output': 'json', # json, xml 두 가지 형식 지원
        'blogName': blogName   # ().tistory.com 또는 블로그 주소 전체
    }
    
    res = requests.get(url, params=params)

    if res.status_code == 200:
        res_json = res.json()
        print(res_json)

if __name__ == '__main__':

    list_of_Category()

 

 

위의 코드로 응답되는 내용을 확인해 보았고, 포스트 목록 확인 때와 마찬가지로 dict 형태로 카테고리 목록에 대한 정보를 확인할 수 있었습니다.

 

{'tistory': {'status': '200', 'item': {'url': 'tae-di', 'secondaryUrl': '', 'categories': [{'id': '947991', 'name': 'Review', 'parent': '947990', 'label': 'Tip/Review', 'entries': '1', 'entriesInLogin': '1'}, {'id': '947279', 'name': 'Python', 'parent': '932530', 'label': 'Study/Python', 'entries': '6', 'entriesInLogin': '6'}, {'id': '932530', 'name': 'Study', 'parent': '', 'label': 'Study', 'entries': '24', 'entriesInLogin': '24'}, {'id': '947990', 'name': 'Tip', 'parent': '', 'label': 'Tip', 'entries': '3', 'entriesInLogin': '3'}, {'id': '947992', 'name': 'Site', 'parent': '947990', 'label': 'Tip/Site', 'entries': '2', 'entriesInLogin': '2'}, {'id': '947280', 'name': 'Excel', 'parent': '932530', 'label': 'Study/Excel', 'entries': '3', 'entriesInLogin': '3'}, {'id': '933890', 'name': 'Etc', 'parent': '', 'label': 'Etc', 'entries': '0', 'entriesInLogin': '0'}, {'id': '947993', 'name': 'Application', 'parent': '947990', 'label': 'Tip/Application', 'entries': '0', 'entriesInLogin': '0'}, {'id': '947277', 'name': 'AutoHotkey', 'parent': '932530', 'label': 'Study/AutoHotkey', 'entries': '1', 'entriesInLogin': '1'}, {'id': '947278', 'name': 'Nas', 'parent': '932530', 'label': 'Study/Nas', 'entries': '1', 'entriesInLogin': '1'}, {'id': '947276', 'name': 'Mac', 'parent': '932530', 'label': 'Study/Mac', 'entries': '6', 'entriesInLogin': '6'}, {'id': '947989', 'name': 'Win', 'parent': '932530', 'label': 'Study/Win', 'entries': '2', 'entriesInLogin': '2'}, {'id': '947281', 'name': 'Blog', 'parent': '932530', 'label': 'Study/Blog', 'entries': '5', 'entriesInLogin': '5'}]}}}

 

item은 'id', 'name', 'parent', 'label', 'entries', 'entriesInLogin' 총 여섯개로 구성되어 있었는데 개인적으로는 카테고리 ID와 육안으로 구분할 수 있는 라벨 정도만 있으면 될 것 같아 출력되는 부분은 두 가지 아이템만 지정해 보았습니다. (전체 아이템이 필요하다면 주석처리된 cloumns 부분을 사용하면 됩니다.) 아래는 테이블로 가공한 카테고리 목록을 tabulate 및 csv로 출력하는 부분을 포함한 전체 코드입니다.

 

import requests
import pandas as pd
from tabulate import tabulate

appid = ""
access_token = ""
callback_url = ""
blogName = ""

def list_of_Category():
    url = "https://www.tistory.com/apis/category/list"

    params = {
        'access_token': access_token,
        'output': 'json', # json, xml 두 가지 형식 지원
        'blogName': blogName   # ().tistory.com 또는 블로그 주소 전체
    }
    
    res = requests.get(url, params=params)

    if res.status_code == 200:
        res_json = res.json()
        data = res_json['tistory']['item']['categories']
        
        # columns = ['id', 'name', 'parent', 'label', 'entries', 'entriesInLogin']
        columns = ['id', 'label']
        df = pd.DataFrame(data, columns=columns)

        print(tabulate(df, headers='keys', tablefmt='grid'))

        df.to_csv('./result.csv', sep=',', na_rep='NaN', encoding='utf-8-sig')


if __name__ == '__main__':

    list_of_Category()

 

결과

전체적으로 포스트 목록을 가져오는 방식과 동일하여 손쉽게 원하는 내용을 얻을 수 있었습니다. 알면알수록 API의 매력에 빠져드는 느낌입니다 :)

 

tabulate 결과

 

반응형

티스토리 아이디로 코멘트를 남기려면

여기를 눌러주세요!

닫기 아이콘
사이드 프로필 배경이미지
아바타 이미지

Taedi's Log

#태디 #코딩린이

자습한 내용을 기록하는 공간이라 다소 먼 길로 돌아가는 방법들이 존재할 수 있습니다🐹 Python, Web에 관심을 갖기 시작했습니다🐶