Skip to content

Instantly share code, notes, and snippets.

@phreakin
Created April 22, 2023 02:43
Show Gist options
  • Save phreakin/ffe93dbe7f6d02aa49d97aa7e6ba5118 to your computer and use it in GitHub Desktop.
Save phreakin/ffe93dbe7f6d02aa49d97aa7e6ba5118 to your computer and use it in GitHub Desktop.
Cheatsheet For MusicBrainz API with PHP

Cheatsheet For MusicBrainz API with PHP:

1. Obtain an API key from MusicBrainz by registering on their website.

2. Initialize a new cURL session using curl_init().

$curl = curl_init();

3. Set the API endpoint and any required options using curl_setopt(). For example, to search for a release by its MBID:

$mbid = '2f2c0f52-a651-46b1-9db5-abb6c197cde5';
$url = "http://musicbrainz.org/ws/2/release/$mbid?inc=artist-credits+labels";

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'User-Agent: MyMusicApp/1.0.0 ([email protected])',
    'Authorization: Bearer ' . $api_key
]);

4. Execute the request using curl_exec().

$response = curl_exec($curl);

5. Check for any errors or exceptions using curl_error() and handle them accordingly.

if(curl_error($curl)) {
    throw new Exception(curl_error($curl));
}

6. Obtain information about the response using curl_getinfo(), such as the HTTP status code.

$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

7. Close the cURL session using curl_close().

curl_close($curl);

8. Parse the response data using json_decode() or simplexml_load_string() if it is returned in JSON or XML format, respectively.

$data = json_decode($response);

9. Use try-catch blocks to catch any exceptions that occur during the request and handle them accordingly.

try {
    // Make API request
} catch (Exception $e) {
    // Handle exception
}

10. Always ensure that you are using the latest version of PHP and cURL library for the best security and performance when connecting to MusicBrainz API with PHP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment