Spotify API (Search) - helloMinji/chatbot_spotify GitHub Wiki

Spotify Search API 사용

API 사용을 위한 access token

def main():

    headers = get_headers(client_id, client_secret)

Search API parameter

    params = {
        "q": "BTS",          # 검색하려고 하는 str (필수)
        "type": "artist",    # q의 type (필수)
        "limit": "5"         # 불러오는 데이터 개수
        # "market" 나라
        # "offset" 몇 번째부터 불러올 건지
    }

요청

    r = requests.get("https://api.spotify.com/v1/search", params=params, headers=headers)

    # 값 확인
    print(r.status_code)    # 실행상태: 200(정상)
    print(r.text)
    print(r.headers)
    sys.exit(0)

blank

Error Handling

아래 요청에 대해 error 발생한 경우 handling 방식을 추가한다.

    r = requests.get("https://api.spotify.com/v1/search", params=params, headers=headers)

1. log 확인 및 강제종료

    try:
        r = requests.get("https://api.spotify.com/v1/search", params=params, headers=headers)
    except:
        logging.error(r.text)
        sys.exit(1)

2. status code에 따른 처리 방법

    if r.status_code != 200:    # 정상
        logging.error(r.text)

        if r.status_code == 429:    # 짧은 시간에 많은 요청을 한 경우
            retry_after = json.loads(r.headers)['Retry-After']
            time.sleep(int(retry_after))

            r = requests.get("https://api.spotify.com/v1/search", params=params, headers=headers)

        elif r.status_code == 401:    # Authorization 문제: header expired
            headers = get_headers(client_id, client_secret)
            r = requests.get("https://api.spotify.com/v1/search", params=params, headers=headers)

        else:
            sys.exit(1)