musicbrainz-api

repository·master·Indexed 42 days ago

https://github.com/borewit/musicbrainz-api

A type-safe TypeScript client for the MusicBrainz API (v1.2.1) used for reading and submitting metadata. It features intelligent throttling to respect rate limits and includes a CoverArtArchiveApi class for fetching release and release-group cover art. Supports lookups by MBID or URL, Lucene-based search, and metadata submission via XML POST or form-data for ISRC codes and Spotify IDs.

Tokens
11.9K
Snippets
39
Records
48
Agent score
49%

What's inside musicbrainz-api

  1. Use include arguments to request extra entity information

    master

    You can use include arguments to request additional related data when performing lookups. These are categorized into subqueries, arguments that affect subqueries, miscellaneous arguments, and relationships.

    Subqueries

    Subqueries allow you to request specific related entities. For example, requesting an artist with the releases include will return the artist's releases.

    Arguments affecting subqueries

    These specify the depth or specific details of the subqueries, such as including discids for all media in releases or artist-credits for all releases and recordings.

    Relationships

    Relationships allow you to load links between the requested entity and a specific entity type (e.g., artist-rels loads relationships between an artist and other artists). For deeper traversal, use:

    • recording-level-rels
    • release-group-level-rels (releases only)
    • work-level-rels
    /* See reference records for full enumeration of include arguments and relationships */
  2. Use musicbrainz-api in CommonJS projects

    master

    The musicbrainz-api library is a pure ESM module. If you are working in a CommonJS environment, you have three options for importing it depending on your Node.js version and build tool:

    1. Node.js ≥ 22: You can use standard require() as Node.js now supports loading ESM modules via require.
    2. Standard CommonJS: Use a dynamic import() call within an async function.
    3. TypeScript CommonJS: Standard dynamic imports may be incorrectly converted to require() by the TypeScript compiler. In this case, use the load-esm package to ensure the module is loaded correctly.
    // Option 1: Node.js ≥ 22
    const { MusicBrainzApi } = require('musicbrainz-api');
    
    // Option 2: Standard CommonJS dynamic import
    async function run() {
      const { MusicBrainzApi } = await import('musicbrainz-api');
    };
    run();
    
    // Option 3: TypeScript CommonJS using load-esm
    import {loadEsm} from 'load-esm';
    
    async function run() {
      const { MusicBrainzApi } = await loadEsm<typeof import('musicbrainz-api')>('musicbrainz-api');
    };
    run();
  3. Install and configure musicbrainz-api

    master

    To use musicbrainz-api, import the MusicBrainzApi class and instantiate it with a configuration object.

    MusicBrainz requires all API clients to identify themselves via the User-Agent header. This library handles this automatically by requiring appName, appVersion, and appContactInfo in the configuration.

    Requirements:

    • Node.js version 16 or higher.
    • The package is a pure ECMAScript Module (ESM).
    import { MusicBrainzApi } from 'musicbrainz-api';
    
    const mbApi = new MusicBrainzApi({
        appName: 'my-app',
        appVersion: '0.1.0',
        appContactInfo: 'user@mail.org',
    });
  4. Browse Query Patterns

    master

    Browsing allows you to retrieve linked entities for a specific MusicBrainz ID. Each entity type has a specific query interface that follows a pattern: it combines IPagination with a OneOf constraint, ensuring you only provide one valid linking entity at a time.

    Examples of browse query types:

    • IBrowseArtistsQuery: Browse artists by area, collection, recording, release, release-group, or work.
    • IBrowseRecordingsQuery: Browse recordings by artist, collection, release, or work.
    • IBrowseReleasesQuery: Browse releases by area, artist, collection, label, track, track_artist, recording, or release-group.
    • IBrowseWorksQuery: Browse works by artist or collection.

    All browse queries support limit and offset for pagination.

  5. Extend HttpClient to manage cookies

    master

    The HttpClient includes hooks for cookie management. By default, getCookies() returns null and registerCookies() does nothing. To maintain a session, you can extend the HttpClient class and override these protected/public methods.

    • Override registerCookies(response: Response): To extract and store cookies from a response.
    • Override getCookies(): To retrieve stored cookies to be sent in subsequent requests.
    class MyAuthenticatedClient extends HttpClient {
      private storedCookies: string | null = null;
    
      protected override async registerCookies(response: Response): Promise<Cookie | undefined> {
        // Logic to extract cookies from response
        return super.registerCookies(response);
      }
    
      public async getCookies(): Promise<string | null> {
        return this.storedCookies;
      }
    }
  6. Configure MusicBrainzApi options

    master

    When instantiating MusicBrainzApi, you can provide several configuration options to control authentication, networking, and rate limiting.

    const config = {
        // Optional: MusicBrainz bot account credentials
        botAccount: {
            username: 'myUserName_bot',
            password: 'myPassword',
        },
    
        // Optional: API base URL (default: 'https://musicbrainz.org')
        baseUrl: 'https://musicbrainz.org',
    
        // Required: Application details
        appName: 'my-app',
        appVersion: '0.1.0',
        appContactInfo: 'user@mail.org',
    
        // Optional: Proxy settings (default: no proxy server)
        proxy: {
            host: 'localhost',
            port: 8888,
        },
    
        // Optional: Disable rate limiting (default: false)
        disableRateLimiting: false,
    
        // Optional: Set max number of request with X seconds
        //           (default: 15 requests every 18 seconds)
        rateLimit: [15, 18]
    };
    
    const mbApi = new MusicBrainzApi(config);
  7. Core MusicBrainz Entities

    master

    The library defines several primary entities that represent the MusicBrainz data model. Most entities implement IEntity (providing an id) and often ITypedEntity (providing id, type, and type-id).

    Key entities include:

    • IArtist: Represents a musical artist, including aliases, gender, and life span.
    • IRelease: Represents a specific release (e.g., a CD or digital album), including status, packaging, and media.
    • IReleaseGroup: A higher-level grouping for releases (e.g., an album version), containing artist credits and primary types.
    • IRecording: Represents a specific musical recording, including length, title, and associated releases.
    • IWork: Represents a musical composition or work.
    • ILabel: Represents a record label.
    • ISeries: Represents a collection of release groups.
    • IArea: Represents a geographic area (Country, City, etc.).
    • IPlace: Represents a specific location with coordinates.
  8. Submit ISRC via user form-data

    master

    Submit an ISRC using form-data. Caution: This should only be used on a test server as it may clear existing metadata. This requires a dedicated bot account and an active session via mbApi.login().

    const mbid_Formidable = '16afa384-174e-435e-bfa3-5591accda31c';
    const isrc_Formidable = 'BET671300161';
    
    const recording = await mbApi.lookup('recording', mbid_Formidable);
    
    // Authentication the http-session against MusicBrainz (as defined in config.baseUrl)
    const succeed = await mbApi.login();
    assert.isTrue(succeed, 'Login successful');
    
    // To submit the ISRC, the `recording.id` and `recording.title` are required
    await mbApi.addIsrc(recording, isrc_Formidable);
  9. Submit recording URLs and Spotify IDs

    master

    You can add URLs or Spotify IDs to a recording using a bot account. You must be logged in first.

    // Submit a generic URL
    const recording = await mbApi.lookup('recording', '16afa384-174e-435e-bfa3-5591accda31c');
    const succeed = await mbApi.login();
    await mbApi.addUrlToRecording(recording, {
      linkTypeId: LinkType.stream_for_free,
      text: 'https://open.spotify.com/track/2AMysGXOe0zzZJMtH3Nizb'
    });
    
    // Submit a Spotify ID directly
    await mbApi.addSpotifyIdToRecording(recording, '2AMysGXOe0zzZJMtH3Nizb');
  10. Submit ISRC code via XML POST

    master

    Submit ISRC metadata using the XML ISRC submission API. This requires using XmlMetadata to construct the payload and mbApi.post to send it.

    const mbid_Formidable = '16afa384-174e-435e-bfa3-5591accda31c';
    const isrc_Formidable = 'BET671300161';
    
    const xmlMetadata = new XmlMetadata();
    const xmlRecording = xmlMetadata.pushRecording(mbid_Formidable);
    xmlRecording.isrcList.pushIsrc(isrc_Formidable);
    await mbApi.post('recording', xmlMetadata);
  11. Lookup MusicBrainz entities by URL

    master

    The lookupUrl method allows you to look up entities using external URLs (like Spotify links) instead of MBIDs. The return type varies depending on whether you pass a single string or an array of strings.

    // Lookup a single URL
    const url = await mbApi.lookupUrl('https://open.spotify.com/track/2AMysGXOe0zzZJMtH3Nizb');
    
    // Lookup multiple URLs
    const urls = await mbApi.lookupUrl([
        'https://open.spotify.com/track/2AMysGXOe0zzZJMtH3Nizb',
        'https://open.spotify.com/track/78Teboqh9lPIxWlIW5RMQL'
    ]);
  12. Use the Cover Art Archive API

    master

    The library provides a CoverArtArchiveApi class to fetch cover art for releases and release groups.

    Fetching Release Cover Art

    • getReleaseCovers(releaseMbid): Returns all available cover art information for a release.
    • getReleaseCover(releaseMbid, type): Fetches a specific cover (e.g., 'front' or 'back').

    Fetching Release Group Cover Art

    • getReleaseGroupCovers(releaseMbid): Returns all available cover art for a release group.
    • getReleaseGroupCover(releaseMbid, type): Fetches a specific cover for a release group.
    import { CoverArtArchiveApi } from 'musicbrainz-api';
    
    const coverArtArchiveApiClient = new CoverArtArchiveApi();
    
    // Example: Fetching all covers for a release
    const coverInfo = await coverArtArchiveApiClient.getReleaseCovers('976e0677-a480-4a5e-a177-6a86c1900bbf');
    for(const image of coverInfo.images) {
        console.log(`Cover art front=${image.front} back=${image.back} url=${image.image}`);
    }
    
    // Example: Fetching a specific front cover for a release
    const frontCover = await coverArtArchiveApiClient.getReleaseCover('976e0677-a480-4a5e-a177-6a86c1900bbf', 'front');
    console.log(`Cover art url=${frontCover.url}`);