Spotipy 사용법 공식 문서
Welcome to Spotipy! - spotipy 2.0 documentation
Spotify API 불러오기
1. Spotify for Developers → DASHBOARD에서 CREATE AN APP
CREATE AN APP을 한 후, 발급된 ID, Secret 사용!
2. python에서 접근 ID, PW 설정
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pprint
cid = '9b5a593955474abfa7bc427fac9cd806'
secret = '부여받은 비밀번호'
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
출처: <https://conansjh20.tistory.com/54> [취미는 파이썬]
👉 1. spotipy : spotify API로, pip install spotipy 로 모듈 설치
- SpotifyClientCredentials 함수에서 ID와 PW설정 (Authorization 과정)
- pprint : 결과값이 딕셔너리, 리스트 합쳐진 복잡한 형태로 나오는데, 이 형태를 깔끔히 정리해주는 모듈
👉 위의 코드가 print로 받은 결과값 / 아래가 pprint로 받은 결과값
- authorization을 베이스로 spotipy 기능을 사용할 수 있는 변수 sp만들기!
👉 이제 이 변수 sp를 통해 spotipy의 모든 기능을 이용할 수 있다.
Search 기능
- 스포티파이의 DB에 있는 각 Artist나 Track에 대한 정보들을 가져오는 기능
👉 q : 검색 키워드
limit : 검색에 대한 결과 최대 개수 설정 (default = 10개)
offset : 인덱스 뛰어넘기? offset : 1이면 0번 → 2번 → 4번 이렇게 가는 것 같다
type : 검색 카테고리? → 가수, 곡, 플레이리스트, ...
market : 상관X
result = sp.search("coldplay", limit=1, type="artist")
pprint.pprint(result)
👉 coldplay 키워드로 가수를 검색해서 최대 1개의 결과를 result에 저장하겠다.
- 결과값!
데이터를 뽑아낸다면,
- 반복되는 부분을 items = result["artists"]["items"] 선언
- items 인덱싱
여기서 조심해야 되는 부분은 item의 내용들은 전부 리스트로 감싸져 있다!
구조가 리스트의 0번 인덱스 안에 값들이 딕셔너리 형태로 다 저장되어 있는 구조다!
따라서, 바로 딕셔너리의 키 값을 items["followers"] 이렇게 인덱싱하면 안 되고,
items[0]["followers"] 이렇게 0번 인덱스를 인덱싱하여 딕셔너리로 진입하고 키 값을 호출한다.
- 따라서, [0]도 반복되므로 items = result["artists"]["items"][0] 으로 설정하자!
이제 딕셔너리의 키 값으로 원하는 정보를 호출하면 된다.
- items["followers"]["total"] : 가수의 총 팔로워 수
- items["genres"] : 가수의 주 장르들 (리스트 형태로 리턴)
- items["id"] : 가수의 id
- items["images"][0]["url"] : image 주소
Artist의 앨범 정보 - artist_albums
- 해당 아티스트의 앨범 정보를 가져오는 기능
artist_id : 아티스트 ID, URI, URL 입력
album_type : 앨범 종류로, 4가지 있는 듯 (album, single, appears_on, compilation)
limit = 1~50
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
result = sp.search("birdy", limit=1, type="artist")
birdy_uri = result["artists"]["items"][0]["id"];
spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
results = spotify.artist_albums(birdy_uri, album_type='album')
albums = results['items']
while results['next']:
results = spotify.next(results)
albums.extend(results['items'])
for album in albums:
print(album['name'])
👉 해당 아티스트의 앨범 정보를 얻기 위해서는 먼저 아티스트의 ID가 필요하다.
위의 Search 기능에서 얻을 수 있었다.
result = sp.search("birdy", limit=1, type="artist")
birdy_uri = result["artists"]["items"][0]["id"];
EX) iu 앨범 정보 얻기
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pprint
cid = 'ID'
secret = '시크릿 키'
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
# artist_albums 기능
search_result = sp.search("iu", limit=1, type="artist")
iu_ID = search_result["artists"]["items"][0]["id"]
album_result = sp.artist_albums(iu_ID, limit=2)
items = album_result["items"]
pprint.pprint(items)
※ 앨범 각각이 리스트의 인덱스로 들어간다!
ex) 첫번째 앨범 정보 → items[0] / 두번째 앨범 정보 → items[1]
- items["image"][0]["url"] : 앨범 이미지 주소
- items["name"] : 앨범 이름
- items["release_date"] : 앨범 출시일
- items["total_tracks"] : 앨범 수록곡 수
- items["type"] : 앨범 타입(album, single, appears_on, complication
album_tracks : 앨범에 수록된 곡들 정보
👉 album_id : 앨범 id 입력
limit : 나오는 개수 제한
result = sp.album_tracks('01dPJcwyht77brL4JQiR8R')
pprint.pprint(result)
👉 IU 라일락 앨범 ID 입력 시 정보
- name : 곡 이름
- preview_url : 30초 미리듣기 url
- duration_ms : 곡 길이 (ms단위) → *0.001해서 초로 변환하기
참고 링크들
Python, Spotify? Spotipy? - Spotify Open API 사용하기 (1)
Python, Spotify? Spotipy? - Spotify Open API 사용하기 (2)
'Mu:ther 추천곡 Project > API 사용법' 카테고리의 다른 글
Spotify API 사용법 - Spotify Web API 사용 (Node.js & Ajax) (0) | 2022.03.09 |
---|---|
OpenWeather API 사용법 - by Ajax (0) | 2022.03.08 |