-
[Data Engineering] Spotify API spotipy 사용하기Data Science/Data Engineering 2021. 7. 3. 21:46
먼저 spotipy 를 사용하기 위해서는 spotipy를 설치해야 합니다.
pip install spotipy
스포티파이의 api를 사용하기 위해서는 먼저 개발자 계정을 등록해야 하는데
기존에 스포티파이에 사용하는 계정이 있다면 해당 계정에 로그인하고 개발자 계정을 등록하기만 해도 되고,
기존에 사용하던 계정이 없다면 계정을 만든 후 개발자 계정을 등록하면 사용할 수 있습니다.
My Dashboard | Spotify for Developers
Create and manage Spotify Applications to use the Spotify Web API. Obtain credentials to authenticate with Spotify and fetch metadata.
developer.spotify.com
개발자 계정을 등록한 후에는 Dashboard에서 초록색 'CREATE AN APP'을 누르고 앱을 만들어 주면
spotipy를 이용하는데 필요한 Client ID와 Client Secret을 발급받을 수 있습니다.
Client ID와 Client Secret을 알았다면
스포티파이의 API를 사용하기 위해 SpotifyClientCredentials 로 클라이언트 자격 인증을 받아야 합니다.
스포티파이 API로 데이터를 요청하고 받아오기 전 꼭 필요한 부분이라 생각하시면 될 것 같습니다.
import spotipy from spotipy.oauth2 import SpotifyClientCredentials client_id = 'YOUR_APP_CLIENT_ID' client_secret = 'YOUR_APP_CLIENT_SECRET' client_credentials_manager = SpotifyClientCredentials(client_id = client_id, client_secret = client_secret) sp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)
spotipy의 search 메소드는 스포티파이의 검색 결과를 리턴해줍니다.
해당 코드는 'kpop' 이라고 검색했을 때의 playlist 결과를 3개까지 가져오기 위한 코드입니다.
파라미터 중 q에 검색할 값인 'kpop', type에 얻고자하는 결과인 'playlist'를, limit에 결과의 개수를 입력해주면 됩니다.
sp.search(q = 'kpop', limit = 3, type = 'playlist')
위 코드의 결과로 json 형태의 결과를 볼 수 있습니다.
다음은 '아이유' 라고 검색했을 때 아티스트 결과를 리턴받기 위한 코드입니다.
sp.search(q = '아이유', limit = 1, type = 'artist')['artists']['items'][0]
결과로 얻은 json 형태의 결과에서 아티스트 'id'라는 것을 볼 수 있는데
스포티파이에서의 artist id로 spotipy api에서 많이 사용되는 파라미터이므로 매우 유용하게 활용할 수 있습니다.
아래 spotipy의 문서에 다양한 메소드가 나와 있으니 원하는 것들을 찾아 사용하시면 됩니다.
spotipy.readthedocs.io/en/2.17.1/
Welcome to Spotipy! — spotipy 2.0 documentation
Authorization Code Flow This flow is suitable for long-running applications in which the user grants permission only once. It provides an access token that can be refreshed. Since the token exchange involves sending your secret key, perform this on a secur
spotipy.readthedocs.io
'Data Science > Data Engineering' 카테고리의 다른 글
[Data Engineering] selenium으로 리뷰 크롤링하기 (0) 2021.06.27 [Data Engineering] Git & Github 기본 사용법 (0) 2021.04.04 [Data Engineering] Docker - Docker 기본 사용법 (0) 2021.03.15 [Data Engineering] 파이썬 가상환경 - Anaconda (1) 2021.03.07