I’m working on an iOS app that uses the Spotify SDK. I want to add more advanced track searching features using the Web API. The search part works fine without auth, but I’m stuck trying to add tracks to a playlist.
Here’s what I’ve tried:
let apiEndpoint = "https://api.spotify.com/v1/users/mySpotifyUsername/playlists/playlistID123/tracks"
let trackURIs = "spotify:track:abc123,spotify:track:def456"
let authToken = spotifySession.accessToken
let requestURL = "\(apiEndpoint)?uris=\(trackURIs)"
var request = URLRequest(url: URL(string: requestURL)!)
request.addValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
When I test this in a browser, I get a 401 error saying authentication is required. Am I setting up the request wrong? I thought the SDK’s access token would work for this. Any ideas on how to fix this?
I’ve encountered this issue before. The problem likely lies in the authentication process. The Spotify SDK’s access token isn’t automatically valid for Web API requests. You need to obtain a separate token for the Web API with the correct scopes.
Try implementing the authorization code flow as described in Spotify’s Web API documentation. This involves redirecting to Spotify’s authorization page, getting a code, then exchanging it for an access token.
Also, ensure you’re using a POST request and sending the track URIs in the request body as JSON. The URL should only contain the endpoint, not the query parameters.
If you’re still facing issues, double-check your app’s settings in the Spotify Developer Dashboard. Make sure the redirect URI is correctly set and that you’ve enabled the necessary scopes for your application.
I’ve been down this road before, and it can be tricky. The Spotify SDK and Web API authentication can be a bit finicky. Here’s what worked for me:
-
Double-check your authorization scopes. As mentioned, you need ‘playlist-modify-public’ or ‘playlist-modify-private’.
-
Make sure you’re using a POST request, not GET. Your code snippet doesn’t specify the HTTP method.
-
The track URIs should be in the request body, not the URL. Try something like this:
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let json = ["uris": ["spotify:track:abc123", "spotify:track:def456"]]
request.httpBody = try? JSONSerialization.data(withJSONObject: json)
- If you’re still getting 401 errors, try refreshing your access token. The SDK should handle this, but sometimes it needs a nudge.
Let me know if you’re still stuck after trying these steps.
hey there, i had a similar issue. make sure ur using the right scopes when authorizing. for playlist modification, u need the ‘playlist-modify-public’ or ‘playlist-modify-private’ scope. also, check if ur access token is still valid. they expire after an hour. hope this helps!