insert variable into data request dictionary python

Viewed 117

I am trying to build a simple record player with the spotify API and I would like to save the playlist id's in variables so it is easier to change or add in the future

import json 
import requests

spotify_user_id = "...."
sgt_peppers_id = "6QaVfG1pHYl1z15ZxkvVDW"  

class GetSongs:
    def __init__(self):
        self.user_id=spotify_user_id
        self.spotify_token = ""
        self.sgt_peppers_id = sgt_peppers_id


    def find_songs(self):
        query = "https://api.spotify.com/v1/me/player/play?
        device_id=......"


        headers={"Content.Type": "application/json", "Authorization": "Bearer 
{}".format(self.spotify_token)}
        data= '{"context_uri":"spotify:album:6QaVfG1pHYl1z15ZxkvVDW"}'

        response = requests.put(query, headers=headers, data=data)

I would like to be able to have it like this: data= '{"context_uri":f"spotify:album:{sgt_peppers_id}"}'

but sadly it doesnt work and all the other methods for inserting variables into strings dont work either. Hope somebody has the anser to this. thank you in advance!

1 Answers

The Spotify API is expecting the request body to be json, which you're currently building by hand. But, it looks like you're using a misspelled header: Content.Type instead of Content-Type (dot instead of dash).

Luckily, the python requests library can encode python objects into json for you and add the Content-Type headers automatically. It can also add the parameters to the url for you, so you don't have to create the ?query=string manually.

# We can add this to the string as a variable in the `json={...}` arg below
album_uri = "6QaVfG1pHYl1z15ZxkvVDW"

response = requests.put(
    "https://api.spotify.com/v1/me/player/play",  # url without the `?`
    params={"device_id": "..."},  # the params -- ?device_id=...
    headers={"Authorization": f"Bearer {self.spotify_token}"},
    json={"context_uri": f"spotify:album:{album_uri}"},
)

Let the requests library do the work for you!

Related