Python API Post request is generating error "required parameter uri missing" using Spotify

Question:

I am using, or trying to anyway, use spotify’s API to que a specific song using python on pycharm. I am receiving error 400 which suggests I am not including the uri parameter.

I am using the ‘requests’ library to make the call. I followed a pretty simple YouTube video that was using a different post request and tried to amend mine to what I was trying to accomplish. In my code, I created a ‘que_song’ function that takes in a string as a parameter which is the uri needed for the request. In the function, I set my headers and parameters and stored it in a ‘response’ object which is than returned by using ‘response.json()’.

When I try to run the file, I am met with the error explained above. I assume I am formatting my request incorrectly, seeing as it is not registering the uri that I am including. I am doing this for a basic passion project over my spring break, so I only just recently became acquainted with python. Apologies for any ugly code below.

import requests
from pprint import pprint

SPOTIFY_QUE_SONG_URL = 'https://api.spotify.com/v1/me/player/queue'
ACCESS_TOKEN = 'insert_generated_token'


def que_song(song):
    response = requests.post(
        SPOTIFY_QUE_SONG_URL,
        headers={
            "Authorization": f"Bearer {ACCESS_TOKEN}"
        },
        json={
            "uri": song
        }

    )
    json_resp = response.json()

    return json_resp

def main():
    next_song = que_song(song="spotify:track:12hVQgYR254ZziANtiKVWQ")

    print(f"Next Song: {next_song}")


if __name__ == '__main__':
    main()
Asked By: EJ VDG

||

Answers:

Interesting detail for at least this endpoint of the Spotify API is that although you do a POST, the uri is actually sent as part of the URL. No body is sent, as can be seen here: Spotify API docs

So try the following, it should work:

import requests

SPOTIFY_QUE_SONG_URL = 'https://api.spotify.com/v1/me/player/queue'
ACCESS_TOKEN = 'insert_generated_token'


def que_song(song):
    url = f"{SPOTIFY_QUE_SONG_URL}?uri={song}"
    response = requests.post(
        url,
        headers={
            "Authorization": f"Bearer {ACCESS_TOKEN}",
            "Accept": "application/json",
        },

    )
    json_resp = response.json()

    return json_resp

def main():
    next_song = que_song(song="spotify:track:12hVQgYR254ZziANtiKVWQ")

    print(f"Next Song: {next_song}")


if __name__ == '__main__':
    main()
Answered By: g_uint
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.