Click here to Skip to main content
15,881,938 members
Articles / Programming Languages / C#

Grooveshark API Tutorial .NET Code

Rate me:
Please Sign up or sign in to vote.
4.82/5 (7 votes)
22 Feb 2015CPOL2 min read 7.7K   15  
Grooveshark makes available methods for accessing and interacting with Grooveshark data. All methods require a web services key and you must sign your requests with a secret key.

Grooveshark, a subsidiary of Escape Media Group, is an online music streaming service based in the United States. It has a search engine, streaming service, and recommendation application. Users can stream and upload music that can be played immediately or added to a playlist.

Grooveshark makes available methods for accessing and interacting with Grooveshark data. All methods require a web services key and you must sign your requests with a secret key. The API is not public, but you can request both keys from the following URL: http://developers.grooveshark.com/api

Official Grooveshark API Tutorial: http://developers.grooveshark.com/tuts/public_api

How to Test the Grooveshark Service Methods?

You can use the official Sandbox API Service form to test your keys or observe sample requests and responses.

Image 1

The basic service methods are free to call if you have the previously mentioned keys. However, the service calls have hour limit. If you want to use the advanced service methods or perform more requests, you should consider upgrading your subscription, you can find more information on the Grooveshark website.

Because the API is not public, you cannot find any official NuGet packages or any kind of ready-to-use SDK in .NET or any other language. If you want to use the API in code, you should write your own code for performing requests, serialize and deserialize the responses. The official tutorial doesn’t provide you an example how to do the task. I’m writing the current post because the usage of the API is a little bit strange.

How to Create a Valid Grooveshark API Request in .NET Code?

Grooveshark team will provide you two keys:

  • key: your_secret_key
  • secret: 65696444026437dab33d09ca1123

In order to perform requests the service we use a library called “RestSharp”. You can find it at the following URL: http://restsharp.org/.

Next, add it to your project using their official NuGet package.

After that, add a using to it in your service class.

C#
using RestSharp;

If you need to serialize or deserialize objects to JSON, you should add a reference to System.Web.Extensions DLL.

C#
using System.Web.Script.Serialization;

Grooveshark API Example (Key: key, Secret: secret):

POST URL

<a href="http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77" rel="noreferrer" style="display: inline !important; removed: help;">http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77</a>

POST payload

{"method":'addUserFavoriteSong",'parameters":{"songID":30547543},"header":{"wsKey":'key","sessionID":'df8fec35811a6b240808563d9f72fa2'}}

Sample Request Parameters Object
C#
/// <summary>
    /// Contains all needed parameters for valid Grooveshark request
    /// </summary>
    public class RequestParameters
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RequestParameters"/> class.
        /// </summary>
        public RequestParameters()
        {
            parameters = new Dictionary<string, object>();
            header = new Dictionary<string, string>();
        }

        /// <summary>
        /// Gets or sets the method.
        /// </summary>
        /// <value>
        /// The method.
        /// </value>
        public string method { get; set; }

        /// <summary>
        /// Gets or sets the header.
        /// </summary>
        /// <value>
        /// The header.
        /// </value>
        public Dictionary<string, string> header { get; set; }

        /// <summary>
        /// Gets or sets the parameters.
        /// </summary>
        /// <value>
        /// The parameters.
        /// </value>
        public Dictionary<string, Object> parameters { get; set; }
    }

After the request parameters object is initialized, we serialize it to JSON format. Next, we encrypt the JSON using HMAC MD5 encryption with the secret key. We use the obtained hash code as a query parameter in the POST URL.

Important Note: The MD5 hash should be used in lower case, otherwise you will receive an exception when the request is performed!

HMAC MD5 Encryption Methods
C#
/// <summary>
    /// Contains Methods For Text Encryption
    /// </summary>
    public static class Encryptor
    {
        /// <summary>
        /// Encrypts string using MD5s encrypt.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="secret">The secret.</param>
        /// <returns>encrypted md5 hash</returns>
        public static string Md5Encrypt(string message, string secret = "")
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(secret);

            HMACMD5 hmacmd5 = new HMACMD5(keyByte);

            byte[] messageBytes = encoding.GetBytes(message);
            byte[] hashmessage = hmacmd5.ComputeHash(messageBytes);
            string result = ByteToString(hashmessage);

            return result;
        }

        /// <summary>
        /// Bytes to string.
        /// </summary>
        /// <param name="buff">The buff.</param>
        /// <returns>byty array string representation</returns>
        private static string ByteToString(byte[] buff)
        {
            string sbinary = "";

            for (int i = 0; i < buff.Length; i++)
            {
                sbinary += buff[i].ToString("X2");
            }
            return (sbinary);
        }  
    }
Sample Request Object Initialization
C#
RequestParameters requestParameters = new RequestParameters();
requestParameters.method = "authenticate";
requestParameters.parameters.Add("login", userName);
requestParameters.header.Add("wsKey", this.key);
requestParameters.header.Add("sessionID", sessionID);
JSON Encryption and Request Execution
C#
var jsonSerializer = new JavaScriptSerializer();
string json = jsonSerializer.Serialize(requestParameters);
string encryptedJson = Encryptor.Md5Encrypt(json, this.secret);
string serviceUrl = this.baseServiceUrl;
if (useHttps)
{
   serviceUrl = this.baseServiceUrl.Replace("<a href="http://" rel="noreferrer" style="display: inline !important; removed: help;">http://</a>", "<a href="https://" rel="noreferrer" style="display: inline !important; removed: help;">https://</a>");
}
var client = new RestClient(serviceUrl);
var request = new RestRequest(String.Format("/ws3.php?sig={0}", encryptedJson.ToLower()), Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(requestParameters);

RestResponse response = (RestResponse)client.Execute(request);

ResponseParameters responseParameters = jsonSerializer.Deserialize<ResponseParameters>(response.Content);

The response is returned again in JSON format, so you can deserialize it to your custom object.

Sample Response Object
C#
public class ResponseParameters
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ResponseParameters"/> class.
        /// </summary>
        public ResponseParameters()
        {
            result = new Dictionary<string, object>();
            header = new Dictionary<string, string>();
        }

        /// <summary>
        /// Gets or sets the header.
        /// </summary>
        /// <value>
        /// The header.
        /// </value>
        public Dictionary<string, string> header { get; set; }

        /// <summary>
        /// Gets or sets the result.
        /// </summary>
        /// <value>
        /// The result.
        /// </value>
        public Dictionary<string, Object> result { get; set; }
    }

The post- Grooveshark API Tutorial .NET Code appeared first on Automate The Planet.

This article was originally posted at http://automatetheplanet.com/grooveshark-api-tutorial

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Automate The Planet
Bulgaria Bulgaria
CTO and Co-founder of Automate The Planet Ltd, inventor of BELLATRIX Test Automation Framework, author of "Design Patterns for High-Quality Automated Tests: High-Quality Test Attributes and Best Practices" in C# and Java. Nowadays, he leads a team of passionate engineers helping companies succeed with their test automation. Additionally, he consults companies and leads automated testing trainings, writes books, and gives conference talks. You can find him on LinkedIn every day.

Comments and Discussions

 
-- There are no messages in this forum --