Почему я получаю неправильный ответ_ json на мой запрос в python - PullRequest
0 голосов
/ 04 апреля 2020

Я пытаюсь автоматизировать добавление песен для спойтинга, используя python. Здесь, в коде, я пытаюсь найти песню, используя song_name и имя исполнителя, и использую API Sittify, чтобы получить URI песни. (https://developer.spotify.com/documentation/web-api/reference/search/search/)

Однако полученный мною ответ недействителен, т.е. он не возвращает список песен с uris, он просто возвращает запрос или запрос, который я отправляю API.

например, {'track': {'href': 'https://api.spotify.com/v1/search?query=track%3AYEAH+RIGHT+artist%3AJoji&type=track&offset=0&limit=20', 'items': [], 'limit': 20, 'next': Нет, «смещение»: 0, «предыдущий»: нет, «всего»: 0}}

def get_spotify_uri(self, song_name, artist):
    """Search For the Song"""
    query = "https://api.spotify.com/v1/search?q=track:{}%20artist:{}&type=track".format(
        song_name,
        artist
    )
    response = requests.get(
        query,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format(spotify_token)
        }
    )
    response_json = response.json()
    print(response_json)
    songs = response_json["tracks"]["items"]

    # only use the first song
    uri = songs[0]["uri"]

    return uri            



Error: response
{'tracks': {'href': 'https://api.spotify.com/v1/search?query=track%3ANext+%28Album+Version%29+artist%3AThe+Weeknd&type=track&offset=0&limit=20', 'items': [], 'limit': 20, 'next': None, 'offset': 0, 'previous': None, 'total': 0}}
Traceback (most recent call last):
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 149, in <module>
    cp.add_song_to_playlist()
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 124, in add_song_to_playlist
    self.get_liked_videos()
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 77, in get_liked_videos
    "spotify_uri": self.get_spotify_uri(song_name, artist)
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 119, in get_spotify_uri
    uri = songs[0]["uri"]

1 Ответ

0 голосов
/ 04 апреля 2020

Я публикую ответ, потому что я не смог уместить все это в комментарии. Я просто хотел сказать, что я успешно справился с кодом ниже, который использует urllib, что может не соответствовать тому, что вы ищете, учитывая, что вы используете библиотеку requests. Возможно, это может быть полезно для сравнения (протестировано в python 3.8):

import urllib.request, urllib.parse
import base64, json

# fill with your own
client_id = b"insert_here_your_client_id"
client_secret = b"insert_here_your_client_secret"

# ask for authorization
query = "https://accounts.spotify.com/api/token"
postdata = urllib.parse.urlencode({"grant_type": "client_credentials"})
postheaders = {'Authorization': "Basic "+base64.b64encode( client_id+b':'+client_secret ).decode('latin-1')}
req = urllib.request.Request(query, data=postdata.encode('latin-1'), headers=postheaders)
req = urllib.request.urlopen(req).read().decode('latin-1')
req = json.loads(req)

# do the search query
query = "https://api.spotify.com/v1/search?q=track:Castles%20artist:Freya&type=track"
req = urllib.request.Request(query, data=None, headers={'Authorization': "Bearer "+req['access_token']})
req = urllib.request.urlopen(req).read().decode('latin-1')
print(req)
...