There are a large number of music platforms available on the internet which allows users to stream music, create playlists, get music recommendations, and much more. Many of these platforms provide REST APIs that expose their functionality. Developers can then use these APIs to integrate the desired music functionality into their applications. One such music API is the Shazam API. In this article, we will be taking a close look at the Shazam API and learn about its features.
About Shazam
At its core, Shazam is a music recognition application. Sometimes, you may hear a great song on your car radio or in a restaurant but may not know which song it is. You can use the Shazam mobile application in such situations. Shazam listens to a short sample of the song using the microphone of your mobile phone and identifies it for you. It provides information like the song title and the song artist. In addition, it also has many other great features like providing music recommendations, listing the top music charts, searching for songs, and much more!
What is Shazam API
The Shazam API provides REST API endpoints that expose all of Shazam’s features. So, it provides endpoints that allow detecting a song based on raw music data, searching for a song based on a phrase, providing song recommendations, listing the top tracks by country, and so on.
Who is the Shazam API for
The target audience for the Shazam API is typically developers working on music or entertainment applications. Such developers can use the Shazam API endpoints to provide music-related services to their users through mobile/web/desktop applications.
The Shazam API can also be used by developers in the data analytics domain for building music-related analytical applications. The song detection endpoint (which can be used to identify song titles based on raw music data) can be run on song databases, radio channels, and other music sources. The data obtained can then be analyzed to identify trends, generate reports, create recommendations, etc.
How does the Shazam API work
Like any other REST API, the Shazam API provides REST endpoints which are simple URLs. These can be consumed by a REST client in any programming language. To invoke an endpoint, a client application needs to specify the endpoint URL, request parameters (parameters required by the endpoint), and authentication information (an API key). The Shazam API then processes the request and returns an appropriate response. By default, the response is in JSON format.
How to use the Shazam API
You can use RapidAPI to connect to the Shazam API. Not only does RapidAPI list all of Shazam’s endpoints, but it also provides code snippets in popular programming languages. These can be used by an application developer as required.
To use RapidAPI to connect to the Shazam API, you need to follow the steps given below.
Step 1 – Signing Up
The first step is to create a RapidAPI account as described below.
Step 1a – Enter the Shazam RapidAPI URL (https://rapidapi.com/apidojo/api/shazam) in a browser. Click on the Log In/Sign Up button in the top right corner. This redirects to the following authentication page:
Step 1b – Authenticate yourself using any of the methods shown on the page. I will choose to log in with Google. Upon successful authentication, the following page is displayed:
Step 2 – Subscribing to the Shazam API
Next, you need to subscribe to the Shazam API. There is a free plan available that allows 500 requests per month.
To subscribe to the Shazam API, you need to do the following:
Step 2a – Click on the Pricing tab. This displays the following screen:
Step 2b – Select the Basic (Free) plan. This displays the following screen:
Step 3 – Executing an endpoint
RapidAPI allows executing an endpoint method and viewing the response. This feature is particularly useful since it enables developers to inspect an endpoint response without having to write any code.
To execute an endpoint, you need to do the following:
Step 3a – Click on the EndPoints tab. All the available endpoints are displayed on the left:
Step 3b – Click the endpoint that you would like to execute. I have selected the auto-complete endpoint. Click the Test Endpoint button:
Step 3c – View the response in the Results tab:
Step 4 – Obtaining a code snippet
RapidAPI provides code snippets in several programming languages. You can copy the code snippet in the desired programming language and use it in your application.
For example, to obtain a code snippet in Kotlin, you need to do the following:
Step 4a – Click on Kotlin -> OkHttp in the Code Snippets tab:
Step 4b – Copy the Kotlin code shown and use it as desired:
Shazam API EndPoints
Let us now take a detailed look at the Shazam API endpoints.
auto-complete
The auto-complete endpoint returns song suggestions based on a phrase or an artist. It accepts a String parameter corresponding to a search term (can be a word, phrase, or artist name) and returns song titles/artist names that contain the specified term. It also accepts an optional parameter corresponding to a locale that specifies a language code. By default, its value is en-US. The JSON object returned contains an array (having a maximum of 10 values) consisting of the search results.
search
The search endpoint searches and returns songs and artists that match the specified term. It accepts a String parameter corresponding to a search term (can be a word, phrase, or artist name). In addition, it also accepts optional parameters corresponding to limit (a numeric value that specifies the number of results to return), offset (the offset from where to start the returned result), and locale (language code). The limit parameter has a default value of 5, however, users can specify any other value (the maximum being 5). The offset parameter can be used for pagination purposes. It has a default value of 0.
The JSON object returned contains two arrays. The first array corresponds to song tracks. Each track object in this array has information like song title, subtitle, artist name, etc. The second array corresponds to artists. Each object in this array has information like artist name, link to artist’s image, etc. Note that the size of both arrays is determined by the limit parameter.
Though the search and auto-complete endpoints appear similar, they are quite different. The auto-complete endpoint merely returns suggested song titles or artist names (which are simple string values) while the search endpoint returns complete song and artist information.
songs/list-artist-top-tracks
The songs/list-artist-top-tracks endpoint lists the top tracks of the specified artist. It accepts a String parameter corresponding to the id of an artist. This id can be obtained from the JSON response returned by the /search or the /songs/detect endpoint. It also accepts an optional parameter corresponding to the locale. The JSON object returned contains an array of the top 20 tracks of the specified artist. Each track object in this array has information like song title, subtitle, artist name, etc.
songs/list-recommendations
The songs/list-recommendations endpoint returns a list of tracks that are related to a particular track. It accepts a String parameter corresponding to the track key. Each song track has a key. This key can be obtained from the JSON response returned by the /search or the /songs/detect endpoint. It also accepts an optional parameter corresponding to the locale. The JSON object returned contains an array of the top 20 tracks that are related to the specified track. Each track object in this array has information like song title, subtitle, artist name, etc.
songs/get-details
The songs/get-details endpoint returns details of a particular song. It accepts a String parameter corresponding to the track key (which can be obtained from the JSON response returned by the /search or the /songs/detect endpoint as mentioned earlier) and an optional locale parameter. The JSON object returned contains song information like the song title, subtitle, artist name, applications in which the song can be played, URLs to share the track on social media platforms, and much more.
songs/detect
The songs/detect endpoint detects a song from raw sound data. It is a POST method. A Base64 encoded byte array corresponding to the song to be detected needs to be specified in the request body. The byte array should be less than 500 KB. The JSON object returned contains song information like song title, subtitle, artist name, etc.
songs/get-count
The songs/get-count endpoint returns the total number of times that a particular song is detected by the /songs/detect endpoint. It accepts a String parameter corresponding to the track key (which can be obtained from the JSON response returned by the /search or the /songs/detect endpoint as mentioned earlier) and an optional parameter locale parameter. The JSON object returned contains a numeric value that indicates the total number of times that the song is detected.
charts/list
The charts/list endpoint returns charts of the top 200 songs by country, city, and genre. It does not accept any parameters. The JSON object returned contains two arrays. The first array corresponds to countries. Each object in this array corresponds to a country and has information like the country name and an id of a country chart which lists the top songs in the country. The country object in turn includes two arrays. The first is a city array and corresponds to each city within the country. Each city object has the city name and an id of a city chart. The second array in the country object is a genre array and corresponds to genres. Each genre object has the genre name and an id of the genre chart. Along with the countries array, the JSON object returns another array corresponding to global genres. Each genre object has the genre name and an id of the genre chart.
charts/track
The charts/track endpoint returns a list of the popular songs in a particular chart. By default, it does not accept any parameters and returns the top 20 songs in the global music chart. It can optionally accept a listId parameter (String value corresponding to the id of a chart whose top songs should be retrieved), pageSize (a numeric value that specifies the number of responses per page), startFrom (the offset from where to start the returned result) and locale (language code). listid can be obtained from the JSON response returned by the /charts/list endpoint. The pageSize parameter has a default value of 20, however, users can specify any other value (the maximum being 20). The startFrom parameter can be used for pagination purposes. It has a default value of 0. The JSON object returned contains an array of track objects. corresponds to song tracks. Each track object in this array has information like song title, subtitle, artist name, etc.
How to use the Shazam API with Java
Let us now understand how to use the Shazam API with Java. Before you start writing code, please ensure that you have Java (version 8 or above) and Maven installed.
Since a REST API exposes its endpoints as HTTP URLs, any HTTP client can be used to invoke it. There are several HTTP clients available for Java. Let us now see how to use some of these clients with the Shazam API. All the examples shown below invoke the auto-complete endpoint.
Using the OkHttp client
OkHttp is a simple and efficient HTTP client for Java and Android.
It requires the following Maven dependency:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency>
You can then use it to invoke an API endpoint as shown below:
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://shazam.p.rapidapi.com/auto-complete?term=kiss%20the&locale=en-US") .get() .addHeader("x-rapidapi-key", "your api key here") .addHeader("x-rapidapi-host", "shazam.p.rapidapi.com") .build(); Response response = client.newCall(request).execute(); int status = response.code(); System.out.println("Response Status is:"+status); ResponseBody body = response.body(); System.out.println("Body is:"+body.string());
This code first creates an OKHttpClient. It then creates a Request object with the URL of the auto-complete API endpoint and the headers required for authentication. Next, it executes the request and obtains a Response object. Finally, it prints the response code and response body. This code produces the following output:
Response Code is:200 Body is:{"hints":[{"term":"kiss the girl"},{"term":"kiss the rain"},{"term":"kiss the sky"},{"term":"i kiss the scars on her skin"},{"term":"kiss the ring"},{"term":"kiss the sun goodbye"},{"term":"kiss the crystal flake"},{"term":"kiss the bride"},{"term":"kiss the sky presented by paul hardcastle"},{"term":"kiss the anus of a black cat"}]}
Using the Unirest client
Unirest is another simple lightweight HTTP client for Java.
It requires the following Maven dependency:
<dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency>
You can then write code as shown below:
HttpResponse<String> response = Unirest .get("https://shazam.p.rapidapi.com/search?term=kiss%20the%20rain&locale=en-US&offset=0&limit=5") .header("x-rapidapi-key", "your api key here") .header("x-rapidapi-host", "shazam.p.rapidapi.com").asString(); int status = response.getStatus(); System.out.println("Response status is:" + status); String body = response.getBody(); System.out.println("Body is:" + body);
As can be seen from the code above, the Unirest client requires less code as compared to the OKHttpClient. You simply need to create a request using the Unirest.get method with the desired API endpoint and appropriate headers. The asString method then needs to be invoked which returns a HttpResponse object of type String. This code produces the same output as before.
Just like OkHttp and Unirest, there are other clients like AsyncHttp and java.net.HttpClient which can also be used to invoke the Shazam API via Java. RapidAPI provides code snippets that demonstrate how these clients can be used in case you would like to try these out.
How to use the Shazam API with other programming languages
You can also invoke the Shazam API endpoints using other programming languages like Python, PHP, Ruby, Javascript, NodeJS, etc. Let us take a look at a few code samples. As before, all the examples shown below invoke the auto-complete endpoint.
Using Shazam API with Python
There are several HTTP client libraries available for Python like http.client, Requests, and Unirest. The following code demonstrates how you can invoke an API endpoint using the Requests library:
import requests url = "https://shazam.p.rapidapi.com/auto-complete" querystring = {"term":"kiss the","locale":"en-US"} headers = { 'x-rapidapi-key': "your api key here", 'x-rapidapi-host': "shazam.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)
Using Shazam API with PHP
Like Python, PHP also has many HTTP client libraries like cURL, HTTP v1, HTTP v2, and Unirest. The code below demonstrates invoking an API endpoint using the cURL library:
<?php $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://shazam.p.rapidapi.com/auto-complete?term=kiss%20the&locale=en-US", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => [ "x-rapidapi-host: shazam.p.rapidapi.com", "x-rapidapi-key: your api key here" ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
Using Shazam API with Ruby
Ruby has two main HTTP client libraries. These are net::http and Unirest. The following code demonstrates how an API endpoint can be invoked using the net::http client:
require 'uri' require 'net/http' require 'openssl' url = URI("https://shazam.p.rapidapi.com/auto-complete?term=kiss%20the&locale=en-US") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["x-rapidapi-key"] = 'your api key here' request["x-rapidapi-host"] = 'shazam.p.rapidapi.com' response = http.request(request) puts response.read_body
Using Shazam API with Javascript
Like the other programming languages, Javascript also has many HTTP client libraries like jQuery, fetch, XMLHttpRequest, and Axios. The code below demonstrates invoking an API endpoint using the fetch library:
fetch("https://shazam.p.rapidapi.com/auto-complete?term=kiss%20the&locale=en-US", { "method": "GET", "headers": { "x-rapidapi-key": "your api key here", "x-rapidapi-host": "shazam.p.rapidapi.com" } }) .then(response => { console.log(response); }) .catch(err => { console.error(err); });
What are the benefits of the Shazam API
Simple and Easy to Use – The biggest benefit of the Shazam API is its simplicity and ease of use. The API endpoints are not only straightforward, but they require very few parameters most of which are self-explanatory.
Minimalistic – By providing only a handful of endpoints that cover the most essential features for music developers, the Shazam API saves developers from having to browse through tons of API methods in search of the appropriate method.
Pagination support – API endpoints like search and charts/track which can return a large number of results support pagination. This not only improves the end-user experience by reducing the page loading time but also frees developers from the overhead of implementing pagination on their own.
Other Music APIs
There are many other Music APIs available on RapidAPI. Some of these are as follows:
- Spotify – Spotify is a popular music platform that allows users to play music, create and save playlists, follow artists, and much more. The Spotify API exposes these Spotify features as REST endpoints. So, developers can fetch data from the Spotify music catalog and manage user’s playlists/saved music data.
- iTunes – The iTunes store is a digital music store available on Apple devices. The iTunes API can be used to add iTunes and Mac store search functionality to an application.
- AudioDB – AudioDB is a community database of audio metadata like song, artist, album information. The AudioDB API can be used to retrieve this information and use it as desired.
- Youtube to Mp3 Download – This API can be used to convert a Youtube video to mp3 format.
- Deezer – Deezer is an online music platform that allows users to search for music, create playlists, get information about songs, artists, albums, etc. The Deezer API provides endpoints that expose these Deezer features.
Summary
So, to summarize, Shazam is a music application that provides features like music detection, obtaining music recommendations, obtaining the top tracks, and much more. The Shazam API provides REST endpoints that expose these features. In this article, we saw how to connect to the Shazam API using RapidAPI. We also took a look at all the Shazam API endpoints. Finally, we saw how to invoke the Shazam API in various programming languages.
Leave a Reply