Apple Music API

RSS for tag

Apple Music API integrates streaming music with Apple Music content.

Apple Music API Documentation

Posts under Apple Music API tag

84 Posts
Sort by:
Post not yet marked as solved
1 Replies
819 Views
I tried to use smart playlist to get all liked songs. But Smart playlists are not returned from Library Playlists endpoint https://api.music.apple.com/v1/me/library/playlists — only the regular playlists are returned.Is there a way to fetch user's smart playlists?If not is there a way to fetch liked songs? Currently I have to load ALL songs and the ratings for all of them, then manually filter. It takes ridiculous amount of time, especially because page size is limited to 100. Btw, is there a way to increase it?
Posted
by
Post not yet marked as solved
6 Replies
4.0k Views
I'm getting a variety of errors when I call prepareToPlay on the MPMusicPlayerController. Sometimes they happen, sometimes they don't. I'm trying to play songs from the Apple Music service. When I don't get the errors, it plays just fine. I have iOS v13.5.1 on my iPhone Xs and I'm using Xcode 11.5. This is my code: let applicationMusicPlayer = MPMusicPlayerController.applicationMusicPlayer applicationMusicPlayer.setQueue(with: [trackID]) applicationMusicPlayer.prepareToPlay(completionHandler:{ error in if let error = error { print(error.localizedDescription) return } DispatchQueue.main.async{ applicationMusicPlayer.play() } } These are the various errors I'm getting: [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=2 "Queue was interrupted by another queue" UserInfo={NSDebugDescription=Queue was interrupted by another queue} [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=9 "Preparing queue timed out" UserInfo={NSDebugDescription=Preparing queue timed out} [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6 "Failed to prepare to play" UserInfo={NSDebugDescription=Failed to prepare to play} [SDKPlayback] applicationQueuePlayer _establishConnectionIfNeeded timeout [ping did not pong]
Posted
by
Post not yet marked as solved
4 Replies
2.5k Views
I want to use Apple Music using MusicKit. I've created MusicKit identifier and private key by following all the steps mentioned here: https://help.apple.com/developer-account/#/devce5522674 I have my Team ID, the Music key ID and the private key (.p8 file) with me. I tried to generate the required JWT token by using many scripts that were mentioned in similar questions asked here, but none of them have worked so far. When I try to authenticate, I'm getting an error ERROR_FAILED_TO_VERIFY_JWT. Ref: Codes I've tried to generate the JWT token from: Thread 130168 - https://developer.apple.com/forums/thread/130168 A nice and simple blog by Lee Martin [Blog - Creating an Apple Music API Token] Thread 79074 - https://developer.apple.com/forums/thread/79074 Many other links But sadly, none of them worked and I had to post this question. I have tried the sample Android app: https://developer.apple.com/download/more/?=Android%20MusicKit After authentication, the page goes on with an infinite loader, which I believe must be because of the same error ERROR_FAILED_TO_VERIFY_JWT Also tried with this HTML page: <html> <head> <meta name="apple-music-developer-token" content="the-JWT-token-generated-using-the-reference-links"> <meta name="apple-music-app-name" content="My App Name"> <meta name="apple-music-app-build" content="1978.4.1"> </head> <body> <button id="apple-music-authorize"></button> <button id="apple-music-unauthorize"></button> </body> <script src="link-to-musickit.js"></script> <script> let music = MusicKit.getInstance(); &#9;&#9;music.player.play(); &#9;&#9;music.authorize().then(function() { &#9;&#9;&#9;&#9;music.player.play(); &#9;&#9;}); &#9;&#9;music.authorize().then(function() { &#9;&#9;&#9;&#9; music.api.library.albums.then(function(cloudAlbums) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;// user's cloudAlbums &#9;&#9;&#9;&#9;}); &#9;&#9;}); </script> </html>
Posted
by
Post not yet marked as solved
2 Replies
1.8k Views
Hello, I'm using systemMusicPlayer to play Apple Music Live Radio Station got from Apple Music API. But it doesn't work. How can I do that? Error: Test[46751:13235249] [SDKPlayback] Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6 "Failed to prepare to play" UserInfo={NSDebugDescription=Failed to prepare to play} My implementation:    let musicPlayerController = MPMusicPlayerController.systemMusicPlayer musicPlayerController.beginGeneratingPlaybackNotifications()      musicPlayerController.setQueue(with: "ra.978194965")     musicPlayerController.play() API response: { “id”: “ra.978194965”, “type”: “stations”, “href”: “/v1/catalog/us/stations/ra.978194965”, “attributes”: { “artwork”: { “width”: 4320, “url”: “https://is2-ssl.mzstatic.com/image/thumb/Features114/v4/e5/10/76/e5107683-9e51-ebc5-3901-d8fbd65f2c2a/source/{w}x{h}sr.jpeg”, “height”: 1080, “textColor3”: “332628”, “textColor2”: “120509”, “textColor4”: “33272a”, “textColor1”: “000000”, “bgColor”: “f4f4f4”, “hasP3”: false }, “url”: “https://music.apple.com/us/station/apple-music-1/ra.978194965”, “mediaKind”: “audio”, “supportedDrms”: [ “fairplay”, “playready”, “widevine” ], “requiresSubscription”: false, “name”: “Apple Music 1”, “kind”: “streaming”, “radioUrl”: “itsradio://music.apple.com/us/station/ra.978194965”, “playParams”: { “id”: “ra.978194965”, “kind”: “radioStation”, “format”: “stream”, “stationHash”: “CgkIBRoFlaS40gMQBA”, “mediaType”: 0 }, “editorialNotes”: { “name”: “Apple Music 1”, “short”: “The new music that matters.”, “tagline”: “The new music that matters.” }, “isLive”: true } },``` Thank you! Best regards, MichaelNg
Posted
by
Post not yet marked as solved
4 Replies
1.5k Views
I am trying to follow along with this in order to auto generate my dev token on requests to MusicKit, but I am getting an error about by identifier, which was configured Link: https://developer.apple.com/documentation/musickit/using-automatic-token-generation-for-apple-music-api Error: 2022-04-26 14:12:06.353589-0400 [6885:431407] [DataRequesting] Failed retrieving developer token: Error Domain=ICErrorDomain Code=-8200 "Media API Token Service responded with status code: Not Found (404). This suggests that "<set_bundle_ID>" was likely not registered as a valid client identifier." UserInfo={NSDebugDescription=Media API Token Service responded with status code: Not Found (404). This suggests that "<set_bundle_ID>" was likely not registered as a valid client identifier., NSUnderlyingError=0x2827669a0 {Error Domain=AMSErrorDomain Code=301 "Invalid Status Code" UserInfo={NSLocalizedDescription=Invalid Status Code, AMSURL=https://sf-api-token-service.itunes.apple.com/apiToken?REDACTED, AMSStatusCode=404, AMSServerPayload={     message = "Client not found";     status = 40402; }, NSLocalizedFailureReason=The response has an invalid status code}}}. Throwing .developerTokenRequestFailed. error getting token
Posted
by
Post not yet marked as solved
2 Replies
871 Views
I am trying to offer my users a wide variety of playlists, like Apple Music does in the "explore" section. I fetched the charting playlists for the current storefront, but that's as far as I get. For example, I fetch the top charts genres first. If a user selects a genre I want to display the playlists for this genre, so I call the charts endpoint with the genre as the id but I can't get a response. path = "/v1/catalog/\(storefrontID)/charts" components.queryItems = [ URLQueryItem(name: "types", value: "playlists"), URLQueryItem(name: "chart", value: "most-played") ] if let id = id { let genreQuery = URLQueryItem(name: "genre", value: id) components.queryItems?.append(genreQuery) } Even weirder, I get exactly one genre "Musik" (which isn't a genre) with identifier "34" and storefrontId "de" where it works and I get my playlists. All other genre return empty responses. I try to use AppleMusic API with MusicKit as an addition, but there doesn't seem to be a solution for this problem either.
Posted
by
Post not yet marked as solved
4 Replies
1.8k Views
Hey All I've been looking at adding a visual representation of the song's first genre in my app and therefor was wondering if there's a list available somewhere of all the Genre's available in MusicKit and their IDs e.g. Genre(id: "21", name: "Rock", parent: Genre(id: "34", name: "Music")) So my questions: Is there a list of all IDs? Are these IDs the same in every country? The reason why I would want this is to have my visuals be safe for localization. For example: If I'd call my asset icon-electronic and then localize my app in dutch it would ask for icon-electronisch. I hope this makes sense and I hope I don't have to browse and save a list of all Genre's by hand haha
Posted
by
Post not yet marked as solved
1 Replies
850 Views
In my Developer account under Certificates, Identifiers &amp; Profiles --&gt; Keys, I cannot add the "Media Services (MusicKit, ShazamKit) key. I have an app identifier where the "MusicKit" App Service is selected. How can I get the key to be available for this app?
Posted
by
Post not yet marked as solved
1 Replies
1.6k Views
Hello everyone! I am using the web version of the Apple Music Kit API, and similar to how Apple is able to produce a user's year in rewind playlist showing the most played artists/songs from a year, I am trying to replicate it for either a year or all time. I have been searching the internet for days trying to figure it out, but I've been completely stuck. I am able to make the following HTTP request successfully. GET https://api.music.apple.com/v1/me/library/songs/ which returns back the user's library of songs, but I haven't figured out how to get the play count. I have tried adding a query like such ?extend=playCount, but that doesn't work. I can see here that the Swift Music Kit API is able to extend a play count property, but I haven't been able to figure it out for Web. Ideally, I am looking for an endpoint that just shows a user's top artist/tracks similar to Spotify, however, whenever I try to use the heavy in rotation endpoint here, it always returns an empty array. The way that I have described is the long-roundabout way where I'll have to fetch each individual song and sort by playCount. But if anyone happens to know how I can do either of the options I've described, it will be truly appreciated ! I've seen other forums posts from years ago, but hopefully there's been a discovered way. Thank you!
Posted
by
Post not yet marked as solved
3 Replies
1.9k Views
I'm making a request to get 10 artists with their top songs at once, but for some artists it will always fail with a 504. The response is also in HTML which leads to a decoding error. This is my code var request = MusicCatalogResourceRequest<Artist>(matching: \.id, memberOf: ids) request.properties = properties let response = try await request.response() where ids is MusicItemId. Below I have an input which will always fail 100% of the time, even when retried. 10 elements  - 0 : "51639"  - 1 : "331584"  - 2 : "120199"  - 3 : "45058"  - 4 : "284786497"  - 5 : "44984"  - 6 : "37299"  - 7 : "518462"  - 8 : "39525"  - 9 : "73568" Example response: [DataRequesting] Failed to parse body of response with status code Unknown (504):  <!DOCTYPE html> <html lang="en"> <head>   <style>     body {       font-family: "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif;       font-size: 15px;       font-weight: 200;       line-height: 20px;       color: #4c4c4c;       text-align: center;     }     .section {       margin-top: 50px;     }   </style> </head> <body> <div class="section">   <h1>&#63743;</h1>   <h3>Gateway Timeout</h3>   <p>Correlation Key: WFRI6Q5HXAUJYXGNRKQ6YTBYIM</p> </div> </body> </html> I have also tried batching these into 2 requests of 5 artists instead of 1 request of 10 artists which still fails. However, I do have sets of 10 artists that work fine. Anyone know why?
Posted
by
Post not yet marked as solved
4 Replies
1.2k Views
Hello there! I have a problem: when i create Music User Token via AppleMusicKit, it returns me token that expires after one or two days. But regarding to this threads - https://developer.apple.com/forums/thread/654814 https://developer.apple.com/forums/thread/685343 it should expire in 6 months! Do I need to consider something when creating a token so that its lifetime will be 6 months and not 2 days? Maybe something with developer token or with MusicKit? Maybe something in apple account? p.s. i tried to find solution of this problem in internet and noticed that many other people have such problem too. And no one got any answers expect that token should live 6 months.
Posted
by
Post not yet marked as solved
0 Replies
398 Views
https://stackoverflow.com/questions/67835316/apple-music-kit-unable-to-get-proper-music-user-token-generated can we please solve this {"errors":[{"id":"3TNGC4HW4P7XPMSPUPLLHHKSOI","title":"Forbidden","detail":"Invalid authentication","status":"403","code":"40300"}]} works for all endpoints in /catalog but /me is a massive issue
Posted
by
Post not yet marked as solved
0 Replies
467 Views
I'm developing a flutter app and using https://pub.dev/packages/music_kit to leverage MusicKit to handle the initial user permission request and generating the userToken. I then need to make requests to the Apple Music API from my server through a background task to retrieve the user's heavy rotation information which is used to recommend events. The initial authorization works as expected and generates a developer token and user token, but when I use the developer token and user token in a get request to https://api.music.apple.com/v1/me/storefront it returns a 403 error "Invalid authentication". I can't seem to figure out what's causing this as I'm using the user token generated from MusicKit, I also test the developer token and it works on non-user specific api end points, so it's a correct developer token. Are user tokens generated by the MusicKit swift code only able to be used in MusicKit calls in the app? Also when making a status request through MusicKit I get "MusicAuthorizationStatus.authorized(musicUserToken: null)" which seems strange as I would assume the token that's returned would be included in the status if it's including the parameter musicUserToken. The account being connected is on a 1 month free trial at the moment if that makes a difference.
Posted
by
Post not yet marked as solved
1 Replies
490 Views
For some library records, the catalog relationships is empty in the response to request: /v1/me/library/albums?include=catalog The json will look like that: "catalog": { "href": "/v1/me/library/albums/l.mbhaBBs/catalog", "data": [] } The catalog relationship url (/v1/me/library/albums/l.mbhaBBs/catalog) will give: { "errors": [ { "id": "YS7BUVCTXA3QWDVX3YQQSCPEUY", "title": "No related resources", "detail": "No related resources found for catalog", "status": "404", "code": "40403" } ] } I am talking about an album that was added from the catalog in the first place. When it happens, removing the album from the library and adding it again using the Apple Music app, resolves the issue. Is there another way to force the library-album to reconcile with the catalog-album using the API itself ?
Posted
by
Post not yet marked as solved
0 Replies
679 Views
The following line of code worked fine in macOS 13.3 / Catalyst: try await MPMediaLibrary.default().addItem(withProductID: "1678639572") Since the 13.4 update it now throws an error: The operation couldn’t be completed. (MPErrorDomain error 11.) Although the Apple Music track with catalog Id 1678639572 does seem to get added to the library regardless. MPError.errorCode 11 is an undocumented value. Can someone please advise what error code 11 actually means, and if there's a workaround? I've raised this as feedback id FB12196635.
Posted
by
Post not yet marked as solved
0 Replies
482 Views
Hello Apple Developer community, I'm currently facing an issue with the integration of the Apple Music API in my application. I've followed the documentation and guidelines provided by Apple, but I'm encountering problems with authentication and parsing the Apple Music track details. Here's a summary of the issue: When making a request to fetch Apple Music track details using the provided API endpoint, I'm receiving the following error: "Error parsing Apple Music track details: The data couldn't be read because it isn't in the correct format." Additionally, the response status code is 401, indicating an unauthorized request. I have already tried the following troubleshooting steps: Verified that the MusicKit App Service is enabled in my app's App ID configuration. Confirmed that the bundle identifier used in the app matches the one in the App ID configuration. Ensured that I'm signed in with a valid Apple ID in the simulator and device I'm testing. Despite these efforts, the issue persists. I believe I have followed the correct procedures for automatic developer token generation, but there might be something missing or misconfigured. I'm seeking assistance and guidance from the Stack Overflow community on how to resolve this issue. Any insights, suggestions, or troubleshooting steps would be greatly appreciated. Thank you in advance for your help! func fetchAppleMusicTrackDetails(from mediaURL: URL, completion: @escaping (AppleMusicTrack?) -> Void) { let components = URLComponents(url: mediaURL, resolvingAgainstBaseURL: false) guard let itemID = components?.queryItems?.first(where: { $0.name == "id" })?.value else { completion(nil) return } fetchStorefront { storefront in guard let storefront = storefront else { print("storefront issue") completion(nil) return } let regex = try! NSRegularExpression(pattern: "\\s*\\(.*?\\)\\s*", options: .caseInsensitive) let trimmedStorefront = regex.stringByReplacingMatches(in: storefront, options: [], range: NSMakeRange(0, storefront.count), withTemplate: "") let encodedStorefront = trimmedStorefront.replacingOccurrences(of: " ", with: "%20") let lookupURLString = "https://api.music.apple.com/v1/catalog/\(encodedStorefront)/songs/\(itemID)" print(lookupURLString) guard let lookupURL = URL(string: lookupURLString) else { print("lookupURL issue") completion(nil) return } URLSession.shared.dataTask(with: lookupURL) { (data, response, error) in if let httpResponse = response as? HTTPURLResponse { print("Status code: \(httpResponse.statusCode)") } if let error = error { print("Error fetching Apple Music track details: \(error.localizedDescription)") completion(nil) return } guard let data = data else { completion(nil) print("no data") return } let responseString = String(data: data, encoding: .utf8) print("Response data: \(responseString ?? "No data")") do { let responseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] let results = responseJSON?["results"] as? [[String: Any]] let trackData = results?.first print(responseJSON) // Extract the necessary track information from the JSON response guard let title = trackData?["trackName"] as? String, let artist = trackData?["artistName"] as? String, let album = trackData?["collectionName"] as? String, let artworkURLString = trackData?["artworkUrl100"] as? String, let artworkURL = URL(string: artworkURLString), let trackURLString = trackData?["previewUrl"] as? String, let trackURL = URL(string: trackURLString) else { completion(nil) return } // Download the artwork image URLSession.shared.dataTask(with: artworkURL) { (artworkData, _, _) in guard let artworkData = artworkData, let artworkImage = UIImage(data: artworkData) else { completion(nil) return } let track = AppleMusicTrack(title: title, artist: artist, album: album, artwork: artworkImage, trackURL: trackURL) completion(track) }.resume() } catch { print("Error parsing Apple Music track details: \(error.localizedDescription)") completion(nil) } }.resume() } } func fetchStorefront(completion: @escaping (String?) -> Void) { SKCloudServiceController().requestStorefrontCountryCode { storefrontCountryCode, error in if let error = error { print("Error fetching storefront country code: \(error.localizedDescription)") completion(nil) return } guard let countryCode = storefrontCountryCode else { print("country code error") completion(nil) return } completion(countryCode) } }
Posted
by
Post not yet marked as solved
0 Replies
555 Views
Hey i am trying to integrate my api with my machine for some testing work but it is showing me an error code possibility combinations 18336326964 , 08336326964 , 8336326964 , Can anyone help me out fixing this i have been working really hard for this project
Posted
by