Hello @Kimfucious,
Thanks for your question on how to access the albums relationship from a Song.
I'm afraid you've chosen to use the wrong tool for the job here.
When using MusicKit for Swift, you should always try to use other more strongly-typed mechanisms first, such as MusicCatalogSearchRequest or MusicCatalogResourceRequest.
Indeed, to the extent possible, we want to leverage the power of the Swift compiler and of Xcode's auto-completion support to enhance the developer experience, precisely to avoid the sort of confusion you're facing with having to construct a URL whose format the Swift compiler cannot understand.
For this specific purpose, you can find this Song much more easily, without having to construct any URL nor decode the raw data response with any Decodable conforming structure by using MusicCatalogResourceRequest's filtering API:
For example, you can find a song whose isrc property matches a certain value with these few lines of code:
let songsRequest = MusicCatalogResourceRequest<Song>(matching: \.isrc, equalTo: "GBDUW0000059")
let songsResponse = try await songsRequest.response()
if let song = songsResponse.items.first {
print("Found \(song).")
}
This code produces the following output:
Found Song(id: "697195787", title: "Harder Better Faster Stronger", artistName: "Daft Punk").
Then, you can use the with(…) method to load a more complete representation of this song that includes the albums relationship:
let detailedSong = try await song.with([.albums])
if let album = detailedSong.albums?.first {
print("\(song) is included\n in \(album)")
}
which produces the following output:
Song(id: "697195787", title: "Harder Better Faster Stronger", artistName: "Daft Punk") is included
in Album(id: "697194953", title: "Discovery", artistName: "Daft Punk")
However, with our latest beta 4, you can even achieve the same result with fewer lines of code, and also more efficiently, by including .albums in MusicCatalogResourceRequest's properties:
var songsRequest = MusicCatalogResourceRequest<Song>(matching: \.isrc, equalTo: "GBDUW0000059")
songsRequest.properties = [.albums]
let songsResponse = try await songsRequest.response()
if let song = songsResponse.items.first, let album = song.albums?.first {
print("\(song) is included\n in \(album)")
}
which also produces the same output as above:
Song(id: "697195787", title: "Harder Better Faster Stronger", artistName: "Daft Punk") is included
in Album(id: "697194953", title: "Discovery", artistName: "Daft Punk")
Back to my initial comment, MusicDataRequest is a very powerful tool, but one that is designed to be used only as a last resort, when you can't get access to the data you need with other APIs such as the ones I just went over. For example, MusicDataRequest is the right tool for the job if you're trying to load content from Apple Music API which isn't modeled in MusicKit for Swift, such as catalog charts.
I hope this helps.
Best regards,