How do you do a POST to a user's playlist so as to add tracks?

Trying to do what I can do pretty easily with a standard post request in a JS app, but now with Swift, and I'm struggling.

I've tried with MusicRequestItem, but that fails, so I went with this and it responds with a 400.

func addTracksToAppleMusicPlaylist(targetPlaylistId: String, tracksToSave: [Song]) async throws -> Void {

    let tracks = tracksToSave.compactMap{

        AppleMusicPlaylistPostRequest(id: $0.id, type: "songs")

    }

    do {

        print("Saving tracks to Apple Music Playlist: \(targetPlaylistId)")

        let tokens = try await self.getAppleMusicTokens()

        if let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists/\(targetPlaylistId)/tracks") {

            var request = URLRequest(url: url)

            request.httpMethod = "POST"

            request.addValue("Bearer \(tokens.devToken)", forHTTPHeaderField: "Authorization")

            request.addValue("\(tokens.userToken)", forHTTPHeaderField: "Music-User-Token")

            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            let encoder = JSONEncoder()

            let data = try encoder.encode(tracks)

            request.httpBody = data

            let session = URLSession(configuration: .default)

            let task = session.dataTask(with: request) {(data, response, error) in

                if error == nil {

                    if let httpResponse = response as? HTTPURLResponse {

                        print("statusCode: \(httpResponse.statusCode)")

                        print("response: \(httpResponse)")

                    }

                } else {

                    print("Error saving tracks to playlist \(String(describing: error))")

                }

            }

            task.resume()

        } else {

            print("Bad URL!")

        }

    } catch {

        print("Error Saving Tracks to Playlist", error)

        throw error

    }

}

Hello @Kimfucious,

You should be able to accomplish this using MusicDataRequest. Please refer to my suggestion in this duplicate thread.

I hope this helps.

Best regards,

How do you do a POST to a user's playlist so as to add tracks?
 
 
Q