### Install Musicbrainzngs from Source Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/installation.rst Installs the musicbrainzngs library system-wide after cloning the source code. This method is useful for developers who want to modify or contribute to the library. ```bash python setup.py install ``` -------------------------------- ### Install Musicbrainzngs using Pip Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/installation.rst Installs the latest stable version of the musicbrainzngs library from the Python Package Index using pip. ```bash pip install musicbrainzngs ``` -------------------------------- ### Get Label Details by ID - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Fetches detailed information about a record label using its unique ID. This example demonstrates how to include aliases in the query results. The output includes the label's name, type, country, and a list of its aliases. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") label_id = "022fe361-596c-43a0-8e22-bad712bb9548" result = musicbrainzngs.get_label_by_id( label_id, includes=["aliases"] ) label = result["label"] print(f"Name: {label['name']}") print(f"Type: {label.get('type', 'Unknown')}") print(f"Country: {label.get('country', 'Unknown')}") if "alias-list" in label: print("Aliases:") for alias in label["alias-list"]: print(f" - {alias['alias']}") ``` -------------------------------- ### Download Front Cover Art (Python) Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Downloads the front cover art for a given release ID, with options to get the full-size image or a thumbnail of a specified size. It handles potential ResponseErrors, including 404 for missing covers. ```Python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") release_id = "b4b04cbf-118a-3944-9545-38a0a88ff1a2" try: # Get full size front cover image_data = musicbrainzngs.get_image_front(release_id) with open("cover_front.jpg", "wb") as f: f.write(image_data) print("Saved full-size front cover") # Get thumbnail (250px) thumbnail = musicbrainzngs.get_image_front(release_id, size="250") with open("cover_front_250.jpg", "wb") as f: f.write(thumbnail) print("Saved 250px thumbnail") except musicbrainzngs.ResponseError as e: if e.cause.code == 404: print("No front cover available") else: print(f"Error: {e}") ``` -------------------------------- ### Get Artist Details by ID with Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves detailed information about an artist using their MusicBrainz ID. It prints the artist's name, sort name, type, and country. Includes error handling for API requests and an example of fetching related release groups. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") artist_id = "b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d" # The Beatles try: result = musicbrainzngs.get_artist_by_id(artist_id) artist = result["artist"] print(f"Name: {artist['name']}") print(f"Sort Name: {artist['sort-name']}") print(f"Type: {artist.get('type', 'Unknown')}") print(f"Country: {artist.get('country', 'Unknown')}") except musicbrainzngs.WebServiceError as e: print(f"Error: {e}") # Get artist with release groups (albums and EPs only) result = musicbrainzngs.get_artist_by_id( artist_id, includes=["release-groups"], release_type=["album", "ep"] ) for rg in result["artist"]["release-group-list"]: print(f"{rg['title']} ({rg.get('type', 'Unknown')})") ``` -------------------------------- ### Search Release Groups with Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Demonstrates searching for release groups, which are conceptual album groupings. Includes examples of both free-text search and strict search, specifying query, artist, and limit parameters. It prints the title, type, and ID of each found release group. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") # Search using a free-text query result = musicbrainzngs.search_release_groups("the clash london calling") for rg in result['release-group-list']: print(f"Title: {rg['title']}") print(f"Type: {rg.get('type', 'Unknown')}") print(f"ID: {rg['id']}") print("---") # Strict search (all terms must match) result = musicbrainzngs.search_release_groups( query="london calling", artist="the clash", strict=True, limit=10 ) ``` -------------------------------- ### Browse Releases by Artist - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Browses releases associated with a specific artist, with options to filter by release type and status, and to include related entities like labels. This example demonstrates fetching the first 100 official album releases and includes logic for paginating through all available releases. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") artist_id = "b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d" # The Beatles # Get first 100 official album releases result = musicbrainzngs.browse_releases( artist=artist_id, release_type=["album"], release_status=["official"], includes=["labels"], limit=100, offset=0 ) print(f"Total releases: {result.get('release-count', 'Unknown')}") for release in result["release-list"]: print(f"{release['title']} ({release.get('date', 'Unknown')})") # Paginate through all releases all_releases = [] offset = 0 limit = 100 while True: result = musicbrainzngs.browse_releases( artist=artist_id, limit=limit, offset=offset ) releases = result["release-list"] all_releases.extend(releases) if len(releases) < limit: break offset += limit print(f"Total fetched: {len(all_releases)} releases") ``` -------------------------------- ### Get Release Details by ID with Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Fetches detailed information about a specific music release using its ID. The code displays the release title, date, status, and barcode. It also includes logic to print the track listing for each medium within the release. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") release_id = "b4b04cbf-118a-3944-9545-38a0a88ff1a2" # Revolver result = musicbrainzngs.get_release_by_id( release_id, includes=["artists", "recordings", "labels"] ) release = result["release"] print(f"Title: {release['title']}") print(f"Date: {release.get('date', 'Unknown')}") print(f"Status: {release.get('status', 'Unknown')}") print(f"Barcode: {release.get('barcode', 'N/A')}") # Print track listing if "medium-list" in release: for medium in release["medium-list"]: print(f"\n--- Medium {medium.get('position', '?')} ({medium.get('format', 'Unknown')}) ---") for track in medium.get("track-list", []): recording = track.get("recording", {}) length_ms = recording.get("length", 0) length_str = f"{length_ms // 60000}:{(length_ms % 60000) // 1000:02d}" if length_ms else "Unknown" print(f"{track.get('position', '?')}. {recording.get('title', 'Unknown')} ({length_str})") ``` -------------------------------- ### GET /release/{id} Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieve detailed information about a specific release, including track listings and associated metadata. ```APIDOC ## GET /release/{id} ### Description Fetches comprehensive details for a release, such as title, date, status, and track lists. ### Method GET ### Endpoint /release/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique MusicBrainz ID of the release. ### Request Example musicbrainzngs.get_release_by_id("b4b04cbf-118a-3944-9545-38a0a88ff1a2") ### Response #### Success Response (200) - **release** (object) - Detailed release information including medium-list and track-list. #### Response Example { "release": { "title": "Revolver", "date": "1966-08-05", "status": "Official" } } ``` -------------------------------- ### Get Cover Art List using MusicBrainzNGS Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Retrieves a list of cover art images for a given release ID from the Cover Art Archive. It allows checking for approved front images. Note that large images are downloaded directly into memory. ```python import musicbrainzngs release_id = "46a48e90-819b-4bed-81fa-5ca8aa33fbf3" data = musicbrainzngs.get_cover_art_list(release_id) for image in data["images"]: if "Front" in image["types"] and image["approved"]: print(f"{image['thumbnails']['large']} is an approved front image!") break ``` -------------------------------- ### Search Artists using MusicBrainzNGS Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Initiates a search for artists on MusicBrainz when their IDs are unknown. This function is the starting point for discovering MusicBrainz IDs. ```python import musicbrainzngs # Example search for artists named 'Nirvana' results = musicbrainzngs.search_artists(artist="Nirvana") for artist in results["artist-list"]: print(f"Artist: {artist['name']} (ID: {artist['id']})") ``` -------------------------------- ### GET /isrc/{isrc} Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves recordings associated with a specific ISRC code. ```APIDOC ## GET /isrc/{isrc} ### Description Retrieves recordings that match an ISRC code. ### Method GET ### Endpoint /isrc/{isrc} ### Parameters #### Path Parameters - **isrc** (string) - Required - The ISRC code. ### Response #### Success Response (200) - **isrc** (object) - Contains the recording-list associated with the ISRC. ``` -------------------------------- ### GET /search/recordings Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Search for musical recordings based on title, artist, and other metadata. ```APIDOC ## GET /search/recordings ### Description Searches the MusicBrainz database for recordings matching the provided criteria. ### Method GET ### Endpoint /search/recordings ### Parameters #### Query Parameters - **recording** (string) - Optional - The title of the recording. - **artist** (string) - Optional - The name of the artist. - **limit** (integer) - Optional - The maximum number of results to return. ### Request Example musicbrainzngs.search_recordings(recording="Hey Jude", artist="The Beatles", limit=5) ### Response #### Success Response (200) - **recording-list** (array) - A list of recording objects containing title, id, and length. #### Response Example { "recording-list": [ { "title": "Hey Jude", "id": "b1a9c0e9-d987-4042-ae91-78d6a3267f69", "length": 431000 } ] } ``` -------------------------------- ### Get Cover Art Listing - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves a list of available cover art images for a given release ID. It provides details for each image, including ID, types, approval status, and thumbnail URLs. Includes error handling for cases where no cover art is found. Requires the musicbrainzngs library. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") release_id = "46a48e90-819b-4bed-81fa-5ca8aa33fbf3" try: data = musicbrainzngs.get_image_list(release_id) print(f"Release URL: {data['release']}") for image in data["images"]: print(f"\nImage ID: {image['id']}") print(f"Types: {', '.join(image['types'])}") print(f"Approved: {image['approved']}") print(f"Front: {image['front']}") print(f"Back: {image['back']}") if "thumbnails" in image: print("Thumbnails:") for size, url in image["thumbnails"].items(): print(f" {size}: {url}") except musicbrainzngs.ResponseError as e: if e.cause.code == 404: print("No cover art available for this release") else: print(f"Error: {e}") ``` -------------------------------- ### GET /browse/release Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Browse releases linked to a specific artist or label with pagination support. ```APIDOC ## GET /browse/release ### Description Browse releases linked to a specific artist, label, or other entity. ### Method GET ### Endpoint /browse/release ### Parameters #### Query Parameters - **artist** (string) - Optional - Filter by artist ID. - **limit** (int) - Optional - Number of results to return. - **offset** (int) - Optional - Pagination offset. ### Response #### Success Response (200) - **release-list** (array) - List of matching releases. - **release-count** (int) - Total number of releases found. ``` -------------------------------- ### Get Recording Details by ID with Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves detailed information about a specific music recording using its ID. The code displays the recording title, length, and any associated ISRCs. It also lists the first five releases the recording appears on. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") recording_id = "b1a9c0e9-d987-4042-ae91-78d6a3267f69" result = musicbrainzngs.get_recording_by_id( recording_id, includes=["artists", "releases", "isrcs"] ) recording = result["recording"] print(f"Title: {recording['title']}") print(f"Length: {recording.get('length', 'Unknown')} ms") if "isrc-list" in recording: print(f"ISRCs: {', '.join(recording['isrc-list'])}") if "release-list" in recording: print("\nAppears on releases:") for rel in recording["release-list"][:5]: print(f" - {rel['title']}") ``` -------------------------------- ### GET /artist/{id} Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/api.rst Fetches a specific artist entity from the MusicBrainz database by its unique identifier. ```APIDOC ## GET /artist/{id} ### Description Retrieves detailed information about an artist using their MusicBrainz ID. ### Method GET ### Endpoint /artist/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique MusicBrainz ID of the artist. #### Query Parameters - **includes** (list) - Optional - List of additional data to include in the response. ### Request Example musicbrainzngs.get_artist_by_id("5b11f4ce-a62d-471e-81fc-a69a8278c7da") ### Response #### Success Response (200) - **artist** (dict) - The artist entity data. #### Response Example { "artist": { "id": "5b11f4ce-a62d-471e-81fc-a69a8278c7da", "name": "Nirvana" } } ``` -------------------------------- ### Getting Cover Art List Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Retrieves a list of cover art images for a given release ID from the Cover Art Archive. ```APIDOC ## Getting Cover Art List ### Description Fetches a listing of available cover art images for a specific release from the Cover Art Archive API. ### Method `musicbrainzngs.get_cover_art_list(release_mbid)` ### Endpoint `/coverart/release/{release_mbid}` ### Parameters - **release_mbid** (string) - Required - The MusicBrainz ID of the release. ### Request Example ```python import musicbrainzngs release_id = "46a48e90-819b-4bed-81fa-5ca8aa33fbf3" data = musicbrainzngs.get_cover_art_list(release_id) for image in data.get("images", []): if "Front" in image.get("types", []) and image.get("approved", False): print(f"Approved front image thumbnail: {image['thumbnails']['large']}") break ``` ### Response #### Success Response (200) Returns a dictionary containing a list of images associated with the release. - **images** (list of dict) - A list of image objects. - **thumbnails** (dict) - Contains URLs for different thumbnail sizes. - **large** (string) - URL for the large thumbnail. - **types** (list of string) - Types of the image (e.g., "Front"). - **approved** (boolean) - Indicates if the image is approved. #### Response Example ```json { "release": "46a48e90-819b-4bed-81fa-5ca8aa33fbf3", "images": [ { "image": "...", "thumbnails": { "large": "https://coverart.musicbrainz.org/...?size=large" }, "approved": true, "types": ["Front", "Back"] } ] } ``` ``` -------------------------------- ### GET /release-group/{id} Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves detailed information about a specific release group using its unique MusicBrainz ID. ```APIDOC ## GET /release-group/{id} ### Description Retrieves information about a release group, including associated artists and releases. ### Method GET ### Endpoint /release-group/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The MusicBrainz ID of the release group. #### Query Parameters - **includes** (list) - Optional - Entities to include in the response (e.g., "artists", "releases"). ### Response #### Success Response (200) - **release-group** (object) - The release group details. #### Response Example { "release-group": { "id": "f52bc6a1-c848-49e6-85de-f8f53459a624", "title": "Example Title", "release-list": [] } } ``` -------------------------------- ### Get Releases in Collection - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves all releases within a specified collection, handling pagination to ensure all releases are fetched. It requires the collection ID and uses the musicbrainzngs library for the API call. Displays release titles and IDs. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") musicbrainzngs.auth("username", "password") collection_id = "4137a646-a104-4031-b549-da4e1f36a463" # Get releases with pagination offset = 0 limit = 25 all_releases = [] while True: result = musicbrainzngs.get_releases_in_collection( collection_id, limit=limit, offset=offset ) collection = result["collection"] releases = collection.get("release-list", []) all_releases.extend(releases) if len(releases) < limit: break offset += limit for release in all_releases: print(f"{release['title']} ({release['id']})") ``` -------------------------------- ### Get Releases by Disc ID - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Fetches releases associated with a given disc ID. This function can return either detailed release information or a CD stub if the exact release is not found but a stub exists. It handles potential 'ResponseError' exceptions, specifically for 404 Not Found errors. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") discid = "kKOqMEuRDSeW_.K49SUEJXensLY-" try: result = musicbrainzngs.get_releases_by_discid( discid, includes=["labels", "recordings"] ) if "disc" in result: disc = result["disc"] print(f"Sectors: {disc['sectors']}") print(f"Tracks: {disc.get('offset-count', 'Unknown')}") for release in disc["release-list"]: print(f"\nTitle: {release['title']}") print(f"ID: {release['id']}") print(f"Barcode: {release.get('barcode', 'N/A')}") elif "cdstub" in result: stub = result["cdstub"] print(f"CD Stub - Artist: {stub['artist']}, Title: {stub['title']}") except musicbrainzngs.ResponseError as e: if e.cause.code == 404: print("Disc not found") else: print(f"Error: {e}") ``` -------------------------------- ### Get Release Group Details by ID - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves detailed information about a specific release group using its ID. It includes fetching associated artists and releases. The output displays the release group's title, type, first release date, and a list of its associated releases with their titles and dates. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") rg_id = "f52bc6a1-c848-49e6-85de-f8f53459a624" result = musicbrainzngs.get_release_group_by_id( rg_id, includes=["artists", "releases"] ) rg = result["release-group"] print(f"Title: {rg['title']}") print(f"Type: {rg.get('type', 'Unknown')}") print(f"First Release Date: {rg.get('first-release-date', 'Unknown')}") if "release-list" in rg: print("\nReleases:") for rel in rg["release-list"]: print(f" - {rel['title']} ({rel.get('date', 'Unknown')})") ``` -------------------------------- ### Get Artist by ID using MusicBrainzNGS Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Retrieves MusicBrainz data for a specific artist using their ID. The data is returned as a dictionary. This function can also include related entities like release groups and filter by release type. ```python import musicbrainzngs from musicbrainzngs import WebServiceError artist_id = "c5c2ea1c-4bde-4f4d-bd0b-47b200bf99d6" try: result = musicbrainzngs.get_artist_by_id(artist_id, includes=["release-groups"], release_type=["album", "ep"]) artist = result["artist"] print(f"Artist Name: {artist['name']}") print(f"Sort Name: {artist['sort-name']}") if "release-group-list" in artist: for release_group in artist["release-group-list"]: print(f" - {release_group['title']} ({release_group['type']})") except WebServiceError as exc: print(f"Something went wrong with the request: {exc}") ``` -------------------------------- ### Initialize and Configure MusicBrainz NGS Client Source: https://github.com/alastair/python-musicbrainzngs/blob/master/README.rst This snippet demonstrates how to import the musicbrainzngs module, authenticate if submitting data, set a user agent as required by MusicBrainz API rules, and optionally configure a different hostname for connecting to services like the beta server. ```python import musicbrainzngs # If you plan to submit data, authenticate musicbrainzngs.auth("user", "password") # Tell musicbrainz what your app is, and how to contact you # (this step is required, as per the webservice access rules # at http://wiki.musicbrainz.org/XML_Web_Service/Rate_Limiting ) musicbrainzngs.set_useragent("Example music app", "0.1", "http://example.com/music") # If you are connecting to a different server musicbrainzngs.set_hostname("beta.musicbrainz.org") ``` -------------------------------- ### Search for Artists and Releases Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Demonstrates how to perform searches for artists using specific criteria and how to execute simple queries for release groups. ```python import musicbrainzngs # Search for artists result = musicbrainzngs.search_artists(artist="xx", type="group", country="GB") for artist in result['artist-list']: print(u"{id}: {name}".format(id=artist['id'], name=artist["name"])) # Simple query for release groups musicbrainzngs.search_release_groups("the clash london calling") ``` -------------------------------- ### Browse Releases with Pagination Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Shows how to fetch large lists of entities by utilizing limit and offset parameters to handle pagination effectively. ```python label = "71247f6b-fd24-4a56-89a2-23512f006f0c" limit = 100 offset = 0 releases = [] page = 1 result = musicbrainzngs.browse_releases(label=label, includes=["labels"], release_type=["album"], limit=limit) page_releases = result['release-list'] releases += page_releases while len(page_releases) >= limit: offset += limit page += 1 result = musicbrainzngs.browse_releases(label=label, includes=["labels"], release_type=["album"], limit=limit, offset=offset) page_releases = result['release-list'] releases += page_releases ``` -------------------------------- ### Configure Logging for musicbrainzngs Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/api.rst This snippet demonstrates how to initialize the Python logging module and set the specific log level for the musicbrainzngs library. It allows developers to control the verbosity of library output within their application. ```python import logging logging.basicConfig(level=logging.DEBUG) # optionally restrict musicbrainzngs output to INFO messages logging.getLogger("musicbrainzngs").setLevel(logging.INFO) ``` -------------------------------- ### GET /discid/{discid} Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves releases associated with a specific physical disc ID. ```APIDOC ## GET /discid/{discid} ### Description Retrieves releases that match a specific disc ID. ### Method GET ### Endpoint /discid/{discid} ### Parameters #### Path Parameters - **discid** (string) - Required - The disc ID to search for. ### Response #### Success Response (200) - **disc** (object) - The disc metadata and associated releases. #### Response Example { "disc": { "sectors": 12345, "release-list": [] } } ``` -------------------------------- ### GET /search/artists Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/api.rst Performs a search for artists based on specific fields or a custom Lucene query. ```APIDOC ## GET /search/artists ### Description Searches for artists matching the provided criteria. Supports fuzzy matching and strict query modes. ### Method GET ### Endpoint /search/artists ### Parameters #### Query Parameters - **query** (string) - Optional - A custom Lucene query string. - **limit** (int) - Optional - Number of results to return (default 25, max 100). - **offset** (int) - Optional - Number of results to skip for pagination. - **strict** (bool) - Optional - If True, requires all query elements to match. ### Request Example musicbrainzngs.search_artists(artist="Nirvana", limit=10) ### Response #### Success Response (200) - **artist-list** (list) - A list of matching artist entities. #### Response Example { "artist-list": [ {"id": "5b11f4ce-a62d-471e-81fc-a69a8278c7da", "name": "Nirvana"} ] } ``` -------------------------------- ### Error Handling Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Demonstrates how to handle various exception classes raised by the musicbrainzngs library. ```APIDOC ## Error Handling ### Description This section details how to handle different types of errors that can occur when using the musicbrainzngs library, including network issues, authentication failures, and invalid requests. ### Exception Classes - **musicbrainzngs.UsageError**: Raised for misuse of the API (e.g., missing useragent). - **musicbrainzngs.AuthenticationError**: Raised for authentication failures (HTTP 401). - **musicbrainzngs.NetworkError**: Raised for network or connection problems. - **musicbrainzngs.ResponseError**: Raised for bad responses from the server (e.g., 404 Not Found, 400 Bad Request). - **musicbrainzngs.WebServiceError**: A general base class for web service errors. ### Example Usage ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") def safe_get_artist(artist_id): try: result = musicbrainzngs.get_artist_by_id(artist_id) return result["artist"] except musicbrainzngs.UsageError as e: print(f"Usage error: {e}") return None except musicbrainzngs.AuthenticationError as e: print(f"Authentication failed: {e}") return None except musicbrainzngs.NetworkError as e: print(f"Network error: {e}") return None except musicbrainzngs.ResponseError as e: if hasattr(e, 'cause') and hasattr(e.cause, 'code'): if e.cause.code == 404: print("Artist not found") elif e.cause.code == 400: print("Invalid artist ID format") else: print(f"Server error {e.cause.code}: {e}") return None except musicbrainzngs.WebServiceError as e: print(f"Web service error: {e}") return None artist = safe_get_artist("b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d") if artist: print(f"Found: {artist['name']}") ``` ``` -------------------------------- ### Enable debug logging Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Configures Python's logging module to capture detailed request information from the musicbrainzngs library. ```python import musicbrainzngs import logging logging.basicConfig(level=logging.DEBUG) logging.getLogger("musicbrainzngs").setLevel(logging.INFO) musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") result = musicbrainzngs.search_artists(artist="The Beatles", limit=1) ``` -------------------------------- ### Set User Agent for MusicBrainzNGS Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Sets a unique user agent for your application to identify it to the MusicBrainz webservice. This is required for all requests. Failure to set a user agent will raise a UsageError. ```python import musicbrainzngs # Set useragent based on application name, version, and contact info musicbrainzngs.set_useragent("MyMusicApp", "1.0", "contact@example.com") ``` -------------------------------- ### Submit Barcode Data Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Explains how to authenticate and submit barcode data to the MusicBrainz test server. ```python musicbrainzngs.set_hostname("test.musicbrainz.org") musicbrainzngs.auth("test", "mb") barcodes = { "174a5513-73d1-3c9d-a316-3c1c179e35f8": "5099749534728", "838952af-600d-3f51-84d5-941d15880400": "602517737280" } musicbrainzngs.submit_barcodes(barcodes) ``` -------------------------------- ### Getting Artist Data by ID Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/usage.rst Retrieve detailed information about an artist using their MusicBrainz ID. Supports including related data like release groups. ```APIDOC ## Getting Artist Data by ID ### Description Fetches detailed information for a specific artist using their MusicBrainz ID. You can also include related entities and filter certain types of releases. ### Method `musicbrainzngs.get_artist_by_id(id, includes=None, release_type=None, ...)` ### Endpoint `/ws/2/artist/` ### Parameters - **id** (string) - Required - The MusicBrainz ID of the artist. - **includes** (list of strings) - Optional - Specifies related entities to include (e.g., `['release-groups']`). - **release_type** (list of strings) - Optional - Filters the type of releases to include (e.g., `['album', 'ep']`). ### Request Example ```python import musicbrainzngs from musicbrainzngs import WebServiceError artist_id = "c5c2ea1c-4bde-4f4d-bd0b-47b200bf99d6" try: result = musicbrainzngs.get_artist_by_id(artist_id, includes=["release-groups"], release_type=["album", "ep"]) artist = result["artist"] print(f"Artist Name: {artist['name']}") print(f"Sort Name: {artist['sort-name']}") for rg in artist.get("release-group-list", []): print(f"- {rg['title']} ({rg['type']})") except WebServiceError as exc: print(f"Something went wrong: {exc}") ``` ### Response #### Success Response (200) Returns a dictionary containing artist information, potentially including a list of release groups. - **artist** (dict) - Contains artist details. - **name** (string) - The artist's name. - **sort-name** (string) - The artist's sortable name. - **release-group-list** (list of dict) - A list of release group dictionaries (if requested). #### Response Example ```json { "artist": { "id": "c5c2ea1c-4bde-4f4d-bd0b-47b200bf99d6", "name": "Example Artist", "sort-name": "Artist, Example", "release-group-list": [ { "id": "...", "title": "Example Album", "type": "album" } ] } } ``` ``` -------------------------------- ### Clone Musicbrainzngs Repository from GitHub Source: https://github.com/alastair/python-musicbrainzngs/blob/master/docs/installation.rst Clones the musicbrainzngs library source code from its GitHub repository using git. This allows for direct access to the latest code or for contributing to the project. ```bash git clone git://github.com/alastair/python-musicbrainzngs.git ``` -------------------------------- ### Configure Server Hostname - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Allows setting a custom MusicBrainz server hostname, which is useful for development, testing with specific servers, or connecting to mirror instances. HTTPS can be enabled. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") # Use test server for development musicbrainzngs.set_hostname("test.musicbrainz.org", use_https=True) # Or use beta server musicbrainzngs.set_hostname("beta.musicbrainz.org", use_https=True) ``` -------------------------------- ### Configure User Agent - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Sets the required User-Agent header for all MusicBrainz API requests. This identifies your application and must be called before any other API calls. ```python import musicbrainzngs # Set useragent (REQUIRED before any API calls) musicbrainzngs.set_useragent( "MyMusicApp", # Application name "1.0", # Application version "contact@example.com" # Contact email or URL ) ``` -------------------------------- ### Browse Recordings by Artist - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Fetches a list of recordings associated with a specific artist ID. It includes details like artist credits and ISRCs, and displays the recording title and duration. Requires the musicbrainzngs library and a user agent to be set. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") artist_id = "b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d" # The Beatles result = musicbrainzngs.browse_recordings( artist=artist_id, includes=["artist-credits", "isrcs"], limit=50 ) print(f"Total recordings: {result.get('recording-count', 'Unknown')}") for recording in result["recording-list"]: length_ms = int(recording.get("length", 0)) duration = f"{length_ms // 60000}:{(length_ms % 60000) // 1000:02d}" if length_ms else "N/A" print(f"{recording['title']} ({duration})") ``` -------------------------------- ### Get Recordings by ISRC - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Retrieves recording information based on an ISRC (International Standard Recording Code). The function can include details about artists and releases associated with the recording. It iterates through the results to print the title and ID of each matching recording. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") isrc = "GBAYE0601477" # Example ISRC result = musicbrainzngs.get_recordings_by_isrc( isrc, includes=["artists", "releases"] ) if "isrc" in result and "recording-list" in result["isrc"]: for recording in result["isrc"]["recording-list"]: print(f"Title: {recording['title']}") print(f"ID: {recording['id']}") print("---") ``` -------------------------------- ### Download Back Cover Art (Python) Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Downloads the back cover art for a release ID with a specified size. It includes error handling for cases where the back cover is not found or other web service errors occur. ```Python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") release_id = "b4b04cbf-118a-3944-9545-38a0a88ff1a2" try: # Get back cover in 500px size image_data = musicbrainzngs.get_image_back(release_id, size="500") with open("cover_back.jpg", "wb") as f: f.write(image_data) print("Saved back cover") except musicbrainzngs.ResponseError as e: if e.cause.code == 404: print("No back cover available") else: print(f"Error: {e}") ``` -------------------------------- ### Enable Debug Logging Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Configures the musicbrainzngs library to output detailed debug messages for API requests. ```APIDOC ## Logging Configuration ### Description This section explains how to enable debug logging for the musicbrainzngs library to monitor API requests and responses, which is useful for troubleshooting. ### Enable Debug Logging To enable debug logging, you need to configure Python's built-in `logging` module. ### Example Usage ```python import musicbrainzngs import logging # Enable debug logging for all messages logging.basicConfig(level=logging.DEBUG) # Optionally, set musicbrainzngs logger to INFO level to reduce verbosity # logging.getLogger("musicbrainzngs").setLevel(logging.INFO) musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") # API calls made after this point will generate debug logs result = musicbrainzngs.search_artists(artist="The Beatles", limit=1) print(result) ``` ``` -------------------------------- ### Submit Release Barcodes (Python) Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Submits barcode data for releases to the MusicBrainz test server. Requires authentication and uses a dictionary mapping release IDs to their barcodes. Includes error handling for submission failures. ```Python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") # Use test server for development! musicbrainzngs.set_hostname("test.musicbrainz.org", use_https=True) musicbrainzngs.auth("test_username", "test_password") barcodes = { "174a5513-73d1-3c9d-a316-3c1c179e35f8": "5099749534728", "838952af-600d-3f51-84d5-941d15880400": "602517737280" } try: musicbrainzngs.submit_barcodes(barcodes) print("Barcodes submitted successfully") except musicbrainzngs.WebServiceError as e: print(f"Submission failed: {e}") ``` -------------------------------- ### Submit User Tags (Python) Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt This snippet is intended for submitting user-generated tags (folksonomy) for various MusicBrainz entities. It requires setting user agent, hostname to the test server, and authentication credentials. ```Python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") musicbrainzngs.set_hostname("test.musicbrainz.org", use_https=True) musicbrainzngs.auth("test_username", "test_password") # Example usage for submit_tags would go here, e.g.: # entity_id = "some-entity-id" # tags = {"tag1": 1, "tag2": 2} # tag: weight # musicbrainzngs.submit_tags(entity_id, tags) ``` -------------------------------- ### List User Collections - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Fetches all collections belonging to an authenticated user. It requires user credentials for authentication and displays the name, ID, editor, type, and item count for each collection. Uses the musicbrainzngs library. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") musicbrainzngs.auth("username", "password") result = musicbrainzngs.get_collections() for collection in result["collection-list"]: print(f"Name: {collection['name']}") print(f"ID: {collection['id']}") print(f"Editor: {collection['editor']}") print(f"Type: {collection.get('type', 'Unknown')}") if "entity-type" in collection: entity_type = collection["entity-type"] count_key = f"{entity_type}-count" print(f"Items: {collection.get(count_key, 'Unknown')}") print("---") ``` -------------------------------- ### Submit tags for multiple entity types Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Demonstrates how to submit tags for artists, recordings, and release groups to the MusicBrainz database. It uses a try-except block to handle potential WebServiceError exceptions. ```python try: musicbrainzngs.submit_tags( artist_tags={ "b10bbbfc-cf9e-42e0-be17-e2c3e1d2600d": ["rock", "british invasion", "60s"] }, recording_tags={ "b1a9c0e9-d987-4042-ae91-78d6a3267f69": ["love song", "classic"] }, release_group_tags={ "f52bc6a1-c848-49e6-85de-f8f53459a624": ["psychedelic rock"] } ) print("Tags submitted successfully") except musicbrainzngs.WebServiceError as e: print(f"Tag submission failed: {e}") ``` -------------------------------- ### Download Release Group Cover Art (Python) Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Downloads the representative front cover image for a release group using its ID and a specified size. Includes error handling for retrieval issues. ```Python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") release_group_id = "f52bc6a1-c848-49e6-85de-f8f53459a624" try: image_data = musicbrainzngs.get_release_group_image_front( release_group_id, size="500" ) with open("release_group_cover.jpg", "wb") as f: f.write(image_data) print("Saved release group cover") except musicbrainzngs.ResponseError as e: print(f"Error getting release group cover: {e}") ``` -------------------------------- ### Search Works with Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Searches for musical works (compositions) based on work title and artist. The code prints the title, ID, and type of each matching work. It also demonstrates setting a user agent for the API. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") result = musicbrainzngs.search_works( work="Yesterday", artist="Lennon", limit=5 ) for work in result['work-list']: print(f"Title: {work['title']}") print(f"ID: {work['id']}") print(f"Type: {work.get('type', 'Unknown')}") print("---") ``` -------------------------------- ### Set Authentication Credentials - Python Source: https://context7.com/alastair/python-musicbrainzngs/llms.txt Configures username and password for API requests that require authentication, such as submitting data or accessing user collections. Ensure set_useragent is called first. ```python import musicbrainzngs musicbrainzngs.set_useragent("MyApp", "1.0", "contact@example.com") # Authenticate for submission and collection access musicbrainzngs.auth("your_username", "your_password") ```