본문 바로가기
💻 programming

[트위터-티스토리] 티스토리 오픈 API 등록하기, Access token 발급받기, 카테고리 목록 가져오기 <2>

by 연구원-A 2022. 12. 21.
반응형

 

티스토리나 트위터 둘 다 일부 기능을 API로 제공하고 있어서

API 형식에 맞춰 요청하면 게시글 포스팅이라던지, 트윗 게시라던지 하는 것들을 쉽게 사용할 수 있다.

하지만 API를 바로 사용할 수 있는 건 아니고 서버에서 사용자 신원을 확인할 수 있도록 API 키를 발급받아야 한다.

티스토리 API 키 발급받기

티스토리 오픈 API 등록하기

작성 예시

인증 요청하기

웹 브라우저의 주소창에 아래 URL을 붙여넣고 해당 주소로 이동한다.

  • {client-id}: App ID
  • {redirect-url}: CallBack

표시된 화면에서 허가하기를 클릭한다

<https://www.tistory.com/oauth/authorize>?
  client_id={client-id}
  &redirect_uri={redirect-uri}
  &response_type=code
  &state=someValue

허가하기를 클릭하면 티스토리 메인 페이지로 이동하는데 아래처럼 {code}에 해당하는 부분을 복사해 저장해둔다

https://www.tistory.com/?code={code}%state=

Access token 발급받기

이전 단계에서 발급받은 appid, secret key, autentication code를 이용해 access token을 발급받는다.

아래 처럼 python 스크립트를 작성하고

내용에 본인의 app_id, secret_key, callback_uri, authentication_code를 입력하고 스크립트를 실행하면 된다.

 

스크립트 실행결과로 얻은 access_token은 반드시 따로 저장해두어야 하고,

git repository에도 공개하지 않도록 주의하자.

import requests
import re
app_id = 'appidfdslkfjasdlkfjdaslkfjdlskfjlasdk'
secret_key = 'secretkey123213213213443243423'

callback_uri = 'https://a-researcher.tistory.com/'

authentication_code = 'authenticationcode1203802914809325809439015'

url_2 = 'https://www.tistory.com/oauth/access_token'

params = { 'client_id': app_id,
           'client_secret': secret_key,
           'redirect_uri': callback_uri,
           'code':authentication_code,
           'grant_type': 'authorization_code' }

res = requests.get(url_2, params=params)

if res.status_code == 200:
    print(res.text.replace('access_token=',''))
else:
    print(res)

 

API 호출해보기

아래처럼 python 스크립트를 작성해 블로그의 카테고리 목록과 id를 가져올 수 있다.

(카테고리 목록과 id는 나중에 글을 포스팅 할 때 사용할 예정 - 원하는 카테코리에 포스팅하기)

import requests
import pandas as pd
from tabulate import tabulate
import json

url = 'https://www.tistory.com/apis/category/list'
params = {
    'access_token': access_token, # (e.g. '12380dflkgjfldkjlg1')
    'output': 'json',
    'blogName': blog_name, # (e.g. 'https://a-researcher.tistory.com/')
}

resp = requests.get(url, params=params)
if resp.status_code == 200:
    json_data = resp.json()

    data = json_data['tistory']['item']['categories']
    columns = ['id','label']
    df = pd.DataFrame(data, columns=columns)

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

else:
    print('failed to get category id: ', resp.status_code)

스크립트를 실행하면 아래처럼 id와 카테고리 목록이 프린트되는 것을 알 수 있다.

+----+--------+--------------------------------+
|    |     id | label                          |
+====+========+================================+
|  0 | 828844 | c++/basics                     |
+----+--------+--------------------------------+
|  1 | 828851 | programming/clean code         |
+----+--------+--------------------------------+
|  2 | 753848 | c++                            |
+----+--------+--------------------------------+
|  3 | 985567 | blogging/trending topics       |
+----+--------+--------------------------------+
|  4 | 722415 | PROJECT/FLUTTER                |
+----+--------+--------------------------------+
|  5 | 881020 | unity                          |
+----+--------+--------------------------------+
|  6 | 828845 | c++/library                    |
+----+--------+--------------------------------+
|  7 | 985568 | blogging/stock market          |
+----+--------+--------------------------------+
|  8 | 828907 | programming/algorithm          |
+----+--------+--------------------------------+
|  9 | 828847 | c++/more                       |
+----+--------+--------------------------------+
| 10 | 753844 | programming/design pattern     |
+----+--------+--------------------------------+
| 11 | 828853 | programming                    |
+----+--------+--------------------------------+
| 12 | 828852 | programming/socket programming |
+----+--------+--------------------------------+
| 13 | 985566 | blogging                       |
+----+--------+--------------------------------+

 

2022.12.29 - [programming] - [트위터-티스토리] 트위터 오픈 API 등록하기, 개발자 계정 신청하기, tweepy 실시간 트렌드 가져오기 <3>

반응형

댓글