Apple Music/Music Kit: how to get song IDs from regular URLs?

The Apple Music API provides a service to fetch a song via an identifier, as detailed in their documentation in this format: https://api.music.apple.com/v1/catalog/us/songs/900032829

However, I noticed that when linking to a song on Apple Music, the link looks like this: https://music.apple.com/us/album/take-on-me-1985-12-mix-2015-remastered/1035047659?i=1035048414

What I am unable to do (unless without using the Spotify API to look up the IRSC code) is to extract the song ID from the regular music URL.

What is the best way to do this?

Hello, @daspianist

The URL pattern when sharing a song currently links to the album page, with the song selected. The ID of the specific track is indicated by the i query parameter.

For your specific API request, you could use the request URL: https://api.music.apple.com/v1/catalog/us/songs/1035048414

Where 1035048414 was extracted from the query param in the user-facing URL https://music.apple.com/us/album/take-on-me-1985-12-mix-2015-remastered/1035047659?i=1035048414

Edit: I didn't see that this question was for MusicKit JS. Apologies.

I don't know how to delete the answer, so I'll leave it for someone else to find it helpful.


You can extract the song ID from the link by creating a URL component and getting the query items out of the component.

Here, the query parameter is "i" with the value 1035048414 as the song ID. You get the first query item and fetch the value out of it:

let components = URLComponents(string: "https://music.apple.com/us/album/take-on-me-1985-12-mix-2015-remastered/1035047659?i=1035048414")

guard let songID = components?.queryItems?.first?.value else { return }

print("SONG ID IS - \(songID)")

Now, you can just use a standard MusicCatalogResourceRequest:

let request = MusicCatalogResourceRequest<Song>(matching: \.id, equalTo: MusicItemID(songID))

do {
    let response = try await request.response()
    print(response.description)
} catch {
    print(error)
}

When I print it:

SONG ID IS - 1035048414

MusicCatalogResourceResponse<Song>(
  items: [
    Song(id: "1035048414", title: "Take On Me (1985 12" Mix) [2015 Remastered]", artistName: "a-ha")
  ]
)

I hope that helps!

Hello @daspianist,

The responses from @admkjs and @snuff4 are essentially correct.

That said, just one quick note to add to @snuff4's response: if you need to do this in Swift, instead of using the first query item, make sure to specifically look for the URLQueryItem instance whose name is equal to "i". That minor tweak should make this code a little bit more robust in the face of possible future changes to the list of query parameters in those URLs.

I hope this helps.

Best regards,

Apple Music/Music Kit: how to get song IDs from regular URLs?
 
 
Q