본문 바로가기

Data Science : Study/2. Data Engineering (FastCampus)

3강-3. Python API 토큰 가져오기 (Spotify)

반응형

썸네일

 

 

 

* Spotify API에 대한 상세한 설명은 url 참고할 것!
https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow

 

! 목표
API 사용을 위한 access token이 3600초마다 만료되기 때문에,

함수를 정의하여 적절한 client key를 넣었다면 만료되지 않은 access token을 반환하도록 하였다.

 

1. 필요한 패키지 불러오기

import sys
import requests
import base64
import json
import logging​

 

2. Spotify API 연결을 위한 key

: Spotify API site dashboard에서 확인 가능

client_id = "@@@"
client_secret = "@@@"

 

 

3. 함수 정의

endpoint
def get_headers(client_id, client_secret):

    endpoint = "https://accounts.spotify.com/api/token"
id와 secret key를 base64로 encoding
    encoded = base64.b64encode("{}:{}".format(client_id, client_secret).encode('utf-8')).decode('ascii')
POST 요청 시 요구되는 body parameter
    payload = {
        "grant_type": "client_credentials"
    }
요청
json.loads : dict 변환 후 key에 맞는 value값 return → access token
    r = requests.post(endpoint, data=payload, headers=headers)
    # r은 dict 형태의 "str"
    access_token = json.loads(r.text)['access_token']

format and return
    headers = {
        "Authorization": "Bearer {}".format(access_token)
    }

    return headers

 

 

 

 

 

이런 내용이 더 있으면 좋겠다, 이건 뭐라는지 모르겠다, 그 외의 어떤 얘기든 댓글로 남겨주세요!

 

 

 

반응형