> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/modules/apple-music.md). Agents can also search and read this documentation through its [MCP server](https://docs.thewalletcrew.io/~gitbook/mcp).

# twc/apple-music

Resolve artist, album and playlist names to Apple Music catalog IDs from a script with the twc/apple-music module, for Apple Wallet event tickets.

An Apple Wallet event ticket can carry Apple Music links: the artists, albums and playlists of the event, identified by their Apple Music catalog IDs. Brands usually know only names, such as the artist printed in a ticketing system. The `twc/apple-music` module turns those names into the IDs, the performer names as Apple Music writes them, and a genre, so that a pass data provider can write them on the pass data and the pass template can use them.

The module is used from scripts only when the names come from the tenant's own data. A pass whose IDs are known in advance carries them directly and needs no script.

<details>

<summary><strong>Real-world examples</strong></summary>

* A ticketing export gives the headliner and the supporting act of a concert as plain names; a pass data provider resolves both to artist IDs when the ticket is issued.
* A venue knows the name of the festival playlist and resolves it once, then every ticket carries the same ID.
* A script resolves an album together with its artist, to tell apart two albums that share a title.

</details>

## Import and functions

```js
import { semantics, getArtistId, getAlbumId, getPlaylistId, find, search, lookup } from "twc/apple-music";
```

There is no global: the functions exist only when imported. Every function is asynchronous and is awaited.

| Function                        | Parameters                                                                   | Returns                                                       |
| ------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------- |
| `semantics(request)`            | `request`: `{ artists?, albums?, playlists?, ...options }` (arrays of names) | `{ artistIDs, albumIDs, playlistIDs, performerNames, genre }` |
| `getArtistId(name, options?)`   | name of an artist                                                            | the catalog ID as a string, or `undefined`                    |
| `getAlbumId(name, options?)`    | name of an album; `options.artist` narrows the search                        | the catalog ID, or `undefined`                                |
| `getPlaylistId(name, options?)` | name of a playlist                                                           | the catalog ID, or `undefined`                                |
| `find(kind, name, options?)`    | `kind`: `"artist"`, `"album"` or `"playlist"`                                | a match object, or `undefined`                                |
| `search(term, options?)`        | free text; `options.kinds` restricts the kinds                               | an array of match objects                                     |
| `lookup(kind, id, options?)`    | `kind` and a known catalog ID                                                | a match object, or `undefined`                                |

`semantics` is the call to use for an event ticket, because it returns every value in the shape that the ticket expects. The other functions serve scripts that need a single ID, or that want to show or check an item.

## Options

All options are optional and use camelCase names. They are accepted by every function, and `semantics` takes them in the same object as the names.

| Option         | Default   | Meaning                                                                                                                                                                                                        |
| -------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `storefront`   | `us`      | The two-letter country code of the Apple Music catalog to search, such as `us` or `fr`. Any other value throws.                                                                                                |
| `limit`        | `5`       | How many items of each kind are examined, from 1 to 25. A value outside the range is brought back to it.                                                                                                       |
| `kinds`        | all three | For `search` only: any of `artist`, `album` and `playlist`.                                                                                                                                                    |
| `match`        | `exact`   | `exact` keeps the first answer whose name equals the searched name, ignoring case and accents, and finds nothing when none does. `best` keeps the answer that Apple Music ranks first. Any other value throws. |
| `artist`       | none      | For albums only: the artist, added to the search to tell apart albums that share a title.                                                                                                                      |
| `throwOnError` | `true`    | Whether an unreachable Apple Music, with no earlier answer to fall back on, fails the script. With `false` the lookup finds nothing instead.                                                                   |

The default `exact` is deliberate: a wrong artist on a ticket is worse than none. `best` is appropriate when names are typed by hand and spelled loosely, at the price of occasional wrong matches, so results should be spot-checked.

## Results

`semantics` returns arrays in the order in which names were given. A name that Apple Music does not know is left out, so an array can be shorter than the request, or empty.

| Member                                 | Meaning                                                                             |
| -------------------------------------- | ----------------------------------------------------------------------------------- |
| `artistIDs`, `albumIDs`, `playlistIDs` | Catalog IDs, without duplicates.                                                    |
| `performerNames`                       | The names of the artists as Apple Music writes them.                                |
| `genre`                                | The first genre of the first artist other than the generic `Music`, or `undefined`. |

Albums of a `semantics` call are searched together with the first artist of the request. A single call accepts at most 20 names in total, artists, albums and playlists added up; a longer request throws.

A match object, returned by `find`, `search` and `lookup`, has these members:

| Member       | Meaning                                                                           |
| ------------ | --------------------------------------------------------------------------------- |
| `id`         | The catalog ID.                                                                   |
| `kind`       | `artist`, `album` or `playlist`.                                                  |
| `name`       | The name in the language of the storefront.                                       |
| `url`        | The Apple Music page of the item, when it has one.                                |
| `artworkUrl` | The artwork address, with `{w}` and `{h}` where the size goes, when there is one. |
| `color`      | The background color of the artwork as `RRGGBB`, when there is one.               |
| `genres`     | The genres of the item, without `Music`. Empty when none is listed.               |

The single-ID functions return `undefined` when nothing is found, so the result is tested before use.

## Caching and limits

The Apple Music catalog is public, so answers are kept in a cache shared by all tenants. An answer is kept for 30 days. A search that finds nothing is kept for one hour only, since the item may not be published yet. When Apple Music cannot be reached, a kept answer is served even if it is older, for up to 90 days, and a failed lookup is not tried again for a minute. A script therefore keeps working through short outages for names it has already resolved.

Lookups that really reach Apple Music are limited: 60 per minute for a tenant and 600 per minute for the whole platform. Answers served from the cache do not count. When a limit is reached, the lookup throws and the operation that ran the script fails. Resolving names once, when the event is created, and never in a loop over many tickets keeps a tenant far below the limit.

If Apple Music is not set up on the platform, every lookup finds nothing and a warning is logged, without failing the script.

## Example

The pass data provider below resolves the artists and the playlist of a ticket and writes them on the pass data. The lists are written as comma-separated text, which is the form that the pass template reads for `artistIDs`, `albumIDs` and `playlistIDs`.

```js
import { semantics } from "twc/apple-music";

export default function (context) {
  context.register("runtime.scriptable.passDataProvider.eventMusic", {
    Fill: async (entity) => {
      if (!entity["event.headliner"]) {
        return false;
      }

      const tags = await semantics({
        artists: [entity["event.headliner"], entity["event.support"]].filter(Boolean),
        playlists: entity["event.playlist"] ? [entity["event.playlist"]] : [],
        storefront: "fr",
        throwOnError: false
      });

      entity["event.artistIDs"] = tags.artistIDs.join(",");
      entity["event.playlistIDs"] = tags.playlistIDs.join(",");
      entity["event.performers"] = tags.performerNames.join(", ");
      return true;
    }
  });
}
```

The pass template's Apple Music fields then read these keys, for example `{{ event.artistIDs }}` in **artistIDs**. `performerNames` is not split on commas: the joined text is for display. To fill the **performerNames** field, add one template entry per performer.

With `throwOnError: false` a ticket is issued without Apple Music links when Apple Music is down and the names were never resolved. With the default `true`, the operation that ran the script fails instead, so no pass is built without its links. The choice depends on whether a missing link is acceptable.

## Checking the result

The pass data shows the IDs written by the script, and the Apple Wallet preview of the pass type in the admin console shows the recommendation card once the IDs are present. A lookup that finds nothing is explained by one of three causes: the name is spelled differently from Apple Music's (try `match: "best"` on a test, or search with `search` to see what exists), the storefront does not carry the item, or the item is too recent to be in the catalog yet.

## FAQ

<details>

<summary><strong>Why does `getArtistId` return `undefined` for an artist that exists?</strong></summary>

The default `exact` match compares the whole name, ignoring case and accents. A name with a suffix or a different spelling, for example a stage name with a prefix, is not an exact match. `search` lists what Apple Music returns, and `match: "best"` accepts the first ranked answer.

</details>

<details>

<summary><strong>Does the storefront change the ID?</strong></summary>

The storefront chooses which catalog is searched, and the name and the genres are given in its language. An item that exists in only some countries is found only in those storefronts.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/modules/apple-music.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
