Using MySpace REST API with OAuth and C#

In this example we will make a REST call to MySpace, get back 100 of our friends and display them on a web page. Because we’re accessing personal private information, you need to pass some authorization parameters with your REST call, and MySpace has adapted the OAuth authorization standard. Before I start explaining more about the code, make sure you already have a MySpace account, then follow the next few steps:

  1. Go to: http://developer.myspace.com/ and
  2. Click on Build on the top nav.
  3. Select Create on-site app button, and fill out your app info.
  4. When you get to the section for upload app xml, click on skip this step.
  5. Make a note of your OAuth Consumer Key and OAuth Consumer Secret because you will need it later.
  6. Under the Canvas Surface tab, select External IFrame option.
  7. Then you have to add the app, otherwise you may get 401 access denied error attempting to make a request.

Okay, hit save and you should be good for now. Let’s open up Visual Studio 2008 and begin!

  1. Create a Website called MySpaceApp or whatever you want.
  2. Copy this file OAuthBase.cs into your project
  3. Add using OAuth namespace at the top of Default.cs
  4. Declare variables for your consumer key, consumer secret and request server:
    1
    2
    3
    4
    5
    
    <code>
    protected string consumerKey = "http://www.myspace.com/123456789";
            protected string consumerSecret = "12abcd345678efghi90jk";
            protected string requestServer = "http://api.myspace.com";
    </code>
  5. Create a public MakeRequest() method returning a DataSet.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    <code>
    public DataSet MakeRequest(string restCall)
            {
                // Form the full REST request url
                Uri url = new Uri(requestServer + restCall);
                DataSet ds = new DataSet();
     
                // Instantiate OAuthBase and declare variables
                OAuthBase oAuth = new OAuthBase();
                string nonce = oAuth.GenerateNonce();
                string timeStamp = oAuth.GenerateTimeStamp();
                string normUrl = string.Empty;
                string normParams = string.Empty;
                string strRequest = string.Empty;
     
                // Create an OAuth signature
                string signature = oAuth.GenerateSignature(url,
                    consumerKey, consumerSecret, string.Empty, string.Empty,
                    "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
                    out normUrl, out normParams);
     
                // Construct the OAuth authenticated REST url
                strRequest = normUrl + "?" + normParams + "&" + UrlEncode("oauth_signature") + "=" + UrlEncode(signature);
     
                return MakeWebRequest(strRequest);
            }
    </code>
  6. Next create a MakeWebRequest() method returning a DataSet
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    <code>
    protected DataSet MakeWebRequest(string restCall)
            {
                // Make web request
                HttpWebRequest request = WebRequest.Create(restCall) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // In this example we are getting back XML
                    XmlTextReader xReader = new XmlTextReader(response.GetResponseStream());
     
                    DataSet ds = new DataSet();
                    ds.ReadXml(xReader);
                    xReader.Close();
     
                    return ds;
                }
            }
    </code>
  7. Finally create a GetFriendList() method that will make the REST request and bind it to a Repeater displaying all your friends.

    1
    2
    3
    4
    5
    6
    7
    
    <code>
        protected void GetFriendList()
        {
            rptFriends.DataSource = fb.MakeRequest("/v1/users/YOUR_USER_ID/friends.xml?page_size=100");
            rptFriends.DataBind();
        }
    </code>
  8. I also built this REST Test Tool that uses OAuthBase.cs that will help you create sample REST calls so you can validate the OAuth parameters.
[del.icio.us] [Digg] [Facebook] [LinkedIn] [MySpace] [StumbleUpon] [Twitter] [Windows Live] [Yahoo!] [Email]

Popularity: 100% [?]

15 comments

  1. Thank you so much for creating this tool..

    i’ve done the things as u’ve guided but i get an Unauthorized Error..(401)

    i’m using the same copy of u r code…it generates the same url as your Test application does..

    can you tell me how to fix this issue…?

  2. Hey Ashish, thanks for the kind words and sorry you’re getting a 401 error. I’ll try to further investigate this when I get home from work today.

  3. hi there..

    i read about myspace..they said in order to use your tool..

    i need to first Request Token..

    then Authorize and then Access Token and finally i can fire up my REST api calls..

    my friend it’s been a month..and this whole thing turn out be very complicated..

    i’m not asking 4 the code but asking for the correct flow if u can guide me..in the right direction..

  4. hi there again..please download my code

    this is the code which i’ve made so far..as you guided

    http://ashishtest.truecanvas.com/HeadAche.zip

    please help me with the code thing..

    please check if i’m doing anything wrong..

    please help..

  5. Hey Ashish,

    I checked out your code, so one thing I found out was that because MySpace’s defualt consumer key’s use forward slashes which need to be UrlEncoded. So in the GenerateSignature() method I just UrlEncoded the ConsumerKey. Here’s a link to my modified OAuthBase.cs file, please try using this one instead.

    http://stevenng.net/files/OAuthBase.cs

    Good luck and contact me if you have any more questions!

  6. Thank you so much STEVE…
    you are my Hero…application worked fine..
    i got the token back…

  7. Hi Steve,

    Please explain 7th point, not clear that “fb.MakeRequest(“/v1/users/YOUR_USER_ID/friends.xml?page_size=100″);”

    what is “fb”? and what is the string inside the “MakeRequest”? YOUR_USER_ID? and friends.xml?

    plase give the clear picture

  8. Under the Canvas Surface tab, select External IFrame option.?

  9. Hi,

    This is good post helps for beginners like me.
    When i tried to run this project i got an error at

    rptFriends.DataSource = fb.MakeRequest(“/v1/users/YOUR_USER_ID/friends.xml?page_size=100″);
    rptFriends.DataBind();

    saying “The IListSource does not contain any data sources”. But i saved the xml file got from the server and it contains my friend list.

    What is the error i am getting ?

    I have doubt in here. How i will get other users friends list ?
    As to my knowledge the other user need to add our application.
    How we will do that ?
    How we get users token and token_secrets which is used later to retrieve data whenever wanted ?
    What are the url’s for these requests ?
    Where i found the url’s used for different data retrieval for particular user ? egs: friends list, status, friends requests etc.

    Please reply me for this :-)

    Regards
    Akeeq

  10. Hello,

    I still have the 401 error. Here is the created URL by your code :
    http://api.myspace.com/v1/users/MyUserID/friends.xml?oauth_consumer_key=MyApIKEY&oauth_nonce=7215739&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1263895708&oauth_version=1.0&page_size=100&oauth_signature=NflU8%2b5oFHguiY90zmDKKjfE8z4%3d

    In the signature : NflU8%2b5oFHguiY90zmDKKjfE8z4%3d, we can see url encoded characters like %3d.

    Thanks

  11. Samuel_Cazell

    Thank you so much!

  12. Sharanya

    Hi,

    Could you please generate the code for Hi5 REST API with oAuth in C#?

    Thanks,
    Sharanya

  13. Hi,

    I am trying to develop the same application as per your instructions which are mentioned in this blog.
    I am using the http://stevenng.net/files/OAuthBase.cs class file.
    I am getting the following error
    “The remote server returned an error: (401) Unauthorized”
    at following line
    // Make web request
    Line 57: HttpWebRequest request = WebRequest.Create(restCall) as HttpWebRequest;
    Line 58: using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    Line 59: {
    Line 60: // In this example we are getting back XML

    Please help me to sort out this error.
    If possible please upload working code.

  14. When i use the basic oAuthBase.cs class i receive the 401 unauthorized error but when i use the updated oAuthBase.cs as mentioned by you in response to a comment by Ashish, the 401 error is removed but still the ResponseStream does not return anything. When i copy the request url and place it in the browser, i see the data being returned but its not workign in code. Can someone please suggest something.

    Btw, for the sake of simplicity, i m using MakeRequest(“/v1/users/myuserid”); instead of getting the friends.

  15. I’m using http://stevenng.net/files/OAuthBase.cs class file ..

    i have successfully done first 3 steps of user authentication but unable to compose url for access token (step4)…

    Authentication Process steps:
    Step 1: Get a request token. (http://api.myspace.com/request_token) Step 2: Redirect to a MySpace URL to authenticate the User. (http://api.myspace.com/authorize)
    Step 3: On successful authentication of the User, MySpace redirects the User back to the callback URL.
    Step 4: Obtain an “access token”. (http://api.myspace.com/access_token) — FACING PROBLEM at this step

    if anyone already done this before then please please paste your sample code …. i shall be very thankful to you for this kindness !!!

Leave a Reply