Creating Library Playlist using Apple Music API and getting 400 - Bad Request?

537 views Asked by At

As per this documentation shared link below,

https://developer.apple.com/documentation/applemusicapi/create_a_new_library_playlist

I'm able to get developer token and music user token but I am getting error for 'Invalid Request Body' (400 Bad Request).

This is the function that I'm using to create apple music playlist.

func createAppleMusicPlaylist() {
    
    let playlistURL = URL(string: Config.appleCreatePlaylist)!
    var playlistRequest = URLRequest(url: playlistURL)
    playlistRequest.httpMethod = "POST"
    let params = ["name"        : kPlaylistName,
                  "description" : kPlaylistDesc]

    playlistRequest.httpBody = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    
    playlistRequest.addValue("Bearer \(DeveloperToken)", forHTTPHeaderField: "Authorization")
    playlistRequest.addValue("\(UserToken)", forHTTPHeaderField: "Music-User-Token")
    
    URLSession.shared.dataTask(with: playlistRequest) { data, response, error in
        guard error == nil else {
            print("\(String(describing: error?.localizedDescription))")
            return
        }
        
        if let data = data {
            let json = try? JSONDecoder().decode(AppleCreatePlaylistModel.self, from: data)

        }
    }.resume()
}

API Response:

{
    "errors": [
        {
            "id": "X4IK3UU6LYGGRSQ6U2KQANL63A",
            "title": "Invalid Request Body",
            "detail": "Unable to parse request body",
            "status": "400",
            "code": "40007"
        }
    ]
}

Please suggest required body parameters. Thanks!

1

There are 1 answers

0
Larme On

You need to follow the API documentation, Create a New Library Playlist, and follow the HTTP Body part that causing issue in your case.

HTTP Body LibraryPlaylistCreationRequest The POST request containing the name, tracks and parent playlist folder for the playlist to be added.

Now, let's check LibraryPlaylistCreationRequest:

Properties

  • attributes
    LibraryPlaylistCreationRequest.Attributes
    (Required)
    A dictionary that includes strings for the name and description of the new playlist.
  • relationships
    LibraryPlaylistCreationRequest.Relationships
    An optional key including tracks for the new playlist.

So, body should like this, at this point:

{
    "attributes": ...,    //Required
    "relationships": ...  //Optional
}

Let's see now LibraryPlaylistCreationRequest.Attributes:

Properties

  • description
    string
    The description of the playlist.
  • name
    string
    (Required) The name of the playlist.description
    string

So, now, the JSON should look like this (I skipped the relationships part since you don't use it):

{
    "attributes": {
        "name": "playlist name",
        "description": "playlist description"
    }
}