iosswifthttprequestapple-musicapple-musickit

Apple Music API getting 403 'Forbidden' when trying to fetch recent tracks


Hey there people of the great world!

I am attempting to retrieve all the recent tracks from the Apple Music API using the following HTTP request: static let AMRecentTracks = "https://api.music.apple.com/v1/me/recent/played/tracks"

Shamefully I keep receiving an error 403 forbidden. This makes no sense as I am able to successfully do a search request using this: static let AMMusicURL = "https://api.music.apple.com/v1/catalog/"

Any help would be greatly appreciated. It seems there is little information about this specific case. I've checked.

I am making the request with a Bearer and a token. static let prefix = "Bearer " to it I am appending the developer token.

Below is my code:

func fetchRecentPlayedResources(_ complition: @escaping (Result<[Song], Error>)->Void) {
    let suffix = "?types=songs"
    
    guard let searchURL     = URL(string: Request.AMRecentTracks + suffix) else { return }
    var musicRequest        = URLRequest(url: searchURL)
    musicRequest.httpMethod = HTTPRequest.GET
    musicRequest.addValue(HTTPRequest.prefix + self.developerToken, forHTTPHeaderField: HTTPRequest.authorization)
    
    
    URLSession.shared.dataTask(with: musicRequest) { [weak self] (data, response, error) in
        guard let self = self else { return }
        if let error = error {
            complition(.failure(error))
        } else {
            if let data = data {
                self.parseSongs(with: data) { songs in
                    complition(.success(songs))
                }
            }
        }
    }.resume()
}

Solution

  • You need to add two tokens when sending personalised requests, the example from the iTunes API documentation shows this:

    curl -v -H 'Music-User-Token: [music user token]' -H 'Authorization: Bearer [developer token]' "https://api.music.apple.com/v1/catalog/us/songs/203709340"
    

    So maybe just adding the developer token as Authorisation isn't enough and this is why you are getting a 403 error. Again, as the documentation states - this is due to invalid or insufficient authorisation.