Cannot create new library playlist with Apple Music API

Hello, I'm writing a function that creates a new Apple Music library playlist for the user of my app.

I'm successfully asking for the user's permission to access their music, and I'm able to retrieve the user's "Music User Token". Unfortunately when it comes time to make the post request, I end up getting a 403 "Forbidden" error.

Here's a snippet of my code:

            let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists")!
            debugPrint("Querying: \(url.absoluteString)")
            let sessionConfig = URLSessionConfiguration.default
            let authValue: String = "Bearer \(appleMusicAuthKey)"
            
            var userToken: String

            let userTokenProvider = MusicUserTokenProvider.init()

            do {
                userToken = try await userTokenProvider.userToken(for: appleMusicAuthKey, options: MusicTokenRequestOptions.init())
                debugPrint("Got user token")

                sessionConfig.httpAdditionalHeaders = ["Authorization": authValue, "Music-User-Token": userToken]
                var request = URLRequest(url: url)
                request.httpMethod = "POST"

                debugPrint(userToken)
                let urlSession = URLSession(configuration: sessionConfig)
                
                do {
                    let (data, response) = try await urlSession.upload(for: request, from: jsonData!)

                    if let httpResponse = response as? HTTPURLResponse {
                        print(httpResponse.statusCode)
                        
                        if (httpResponse.statusCode == 201) {
                            debugPrint("Created new playlist!")
                        } else {
                            debugPrint("Could not create the playlist")
                        }
                    }
                } catch {
                    debugPrint("Error loading \(url): \(String(describing: error))")
                }
            } catch {
                debugPrint("Could not get user token")
            }

(Please excuse some of the messy code, still prototyping this)

As far as I can tell, my developer token is fine, and the weirdest part is that I had it working with very similar code earlier. I cannot figure out what's wrong or what I'm missing.

Accepted Answer

You can avoid adding the tokens yourself if you are targeting iOS 15+ and take advantage of MusicKit instead. Most of the code can be reduced to:

let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists")!

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = data

let request = MusicDataRequest(urlRequest: urlRequest)
let response = try await request.response()

if response.urlResponse.statusCode == 201 {
 debugPrint("Created new playlist!")
} else {
 debugPrint("Could not create the playlist")
}

Also, I forgot to mention that you can use the new class MusicLibrary for iOS 16 and above to create and edit playlists. Here is an example:

let newPlaylist = MusicLibrary.shared.createPlaylist(name: "New playlist", description: "A new playlist with MusicKit", authorDisplayName: "Rudrank Riyam", items: items)

Where items are a collection of tracks as MusicItemCollection<Track>. It also returns the new playlist as Playlist.

Cannot create new library playlist with Apple Music API
 
 
Q