Spotify Web API Добавление песен в плейлист ошибка - PullRequest
0 голосов
/ 07 августа 2020

Работают первые две функции создания плейлиста и поиска треков. Моя ошибка появляется при попытке добавить URI песен во вновь созданный список воспроизведения. Я получаю эту ошибку:

"{'error': {'status': 400, 'message': 'Error parsing JSON.'}}"

Я считаю, что моя проблема в формате, который я отправляю в переменной request_body в .post, но не совсем уверен.

def createPlaylist():
    # Function to create a playlist for a user

    user_id = "**NOTMYREALID**"
    endpoint_url = f"https://api.spotify.com/v1/users/{user_id}/playlists"
    request_body = json.dumps({
        "name": "The Most Popular Songs",
        "description": "The most popular songs in XX on Spotify",
        "public": False #During practice programming
        })
    # respose from the requests.post io
    # Uses token generated from https://developer.spotify.com/console/post-playlists/
    response = requests.post(url=endpoint_url,
                             data=request_body,
                             headers={"Accept": "application/json", "Content-Type": "application/json",
                                      "Authorization": "Bearer {}".format(spotify_token)
                                      }
                             )
    json_response = response.json()
    print(json_response)

    print(response.status_code) # https://developer.spotify.com/documentation/web-api/ for error codes
    if response.status_code == 201:
        print("Success creating playlist")
    else:
        print("Error creating a playlist")
    return json_response


def searchPopularPlaylist():
    # Function to search for a popular playlist in a give category

    endpoint_url = "https://api.spotify.com/v1/recommendations?"

    # Filters based from https://developer.spotify.com/console/get-recommendations/
    limit = 10
    market = "US"
    seed_genres = "hip-hop"
    min_danceability = 0.9
    max_duration_ms = 240000
    min_popularity = 0.9

    # List for spotify URIs
    uris = []

    # query uses .get and the limits defined above to use search with a token from https://developer.spotify.com/console/get-recommendations/
    query = f'{endpoint_url}limit={limit}&market={market}&seed_genres={seed_genres}&min_danceability={min_danceability}&max_duration_ms={max_duration_ms}&max_duration_ms={max_duration_ms}&min_popularity{min_popularity}'
    # Response from requests io
    response = requests.get(query, headers = {"Content-Type":"application/json",
                            "Authorization":"Bearer {}".format(spotify_token)
                                              }
                            )

    json_response = response.json()


    if response.status_code == 200:
        print("Success searching for playlist songs")
        print(response.status_code)
    else:
        print("Error in searching for playlist songs")
        print(response.status_code)
    print(json_response)

    # Adds all song URI's to "uris" variable
    for items in json_response["tracks"]:
        # Printable list of songs that match filters
        #print(f"\"{items['name']}\" by {items['artists'][0]['name']}")
        uris.append(items['uri'])

    request_body = json.dumps({
        "uris" : uris
    })
    print(request_body)

    return(uris)


def add_songs_to_playlist():
    # Function to add songs to a created playlist
    # Variables used in request post
    user_id = "**NOTMYREALID**"
    uris = searchPopularPlaylist()
    playlistInfo = createPlaylist()
    playlist_id = playlistInfo["id"]
    endpoint_url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"

    print(playlist_id)
    print(uris)

    request_body = {"uris": uris}

    print(request_body)

    response = requests.post(url=endpoint_url,
                             data=request_body,
                             headers={"Accept": "application/json",
                                      "Content-Type": "application/json",
                                      "Authorization": "Bearer {}".format(spotify_token)
                                      }
                             )
    json_response = response.json()

    print(json_response)
    print(response.status_code)

Спасибо!

...