Home > Software engineering >  Problem sending post requests to spotify api in python
Problem sending post requests to spotify api in python

Time:12-06

def queue_song(session_id):
    song_uri='spotify:track:5RwV8BvLfX5injfqYodke9'
    tokens = get_user_tokens(session_id)
    headers = {'Content-Type': 'application/json',
               'Authorization': "Bearer "   tokens.access_token,
               }
    url = BASE_URL  'player/queue'
    data={
        'uri':song_uri
    }
    response = requests.post(url,headers=headers,data=data).json()
    print(response)

Output:

{'error': {'status': 400, 'message': 'Required parameter uri missing'}}

https://developer.spotify.com/documentation/web-api/reference/#/operations/add-to-queue

I dont thing there is any problem with auth tokens... coz 'GET' requests are working fine

CodePudding user response:

By default, using data= in requests.post() sets the content type to application/x-www-form-urlencoded which makes the body a akin to a HTTP form request.

Spotify's API is JSON based, so your data needs to be a valid json data.

You can do it in 2 ways:

response = requests.post(url,headers=headers,data=json.dumps(data)).json()

Or, more simply:

response = requests.post(url,headers=headers,json=data).json()

and in this way you don't need to manually set the application/json header as well.

Edit: After going through the API docs you linked, there's more wrong with the call you're making.

You're sending the parameters in data - which is the body of the request. But Spotify API specifies the parameters need to be put in the Query i.e. the query string of the URI. Which means your request should be:

response = requests.post(url,headers=headers,params=data).json()  # set query string not body
  • Related