본문 바로가기

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

3강-4. Python Search API 사용해보기 (Spotify)

반응형

썸네일

 

 

 

* Spotify Search API에 대한 상세한 설명은 url 참고할 것!
https://developer.spotify.com/documentation/web-api/reference/#category-search
! 목표
검색어를 입력해서 데이터를 불러온다.

 

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

import sys
import requests
import base64
import json
import logging​

 

2. Spotify API 연결을 위한 key

: Spotify API site dashboard에서 확인 가능

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

 

3. 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)

 

(추가 시나리오) 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에 따른 처리 방법
    - API를 사용했을 때 return해주는 코드(Web API 사이트에서 확인 가능)
    - 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)

☞ 둘 중 원하는 방식으로 3.의 요청 코드를 수정한다. 에러 핸들링은 중요해!

 

 

 

 

 

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

 

 

 

반응형