Dropbox API and RestSharp for a C# developer

The Dropbox API has foiled my development of “Droppedboxx” for some time now. Mainly because the on site documentation is average for anyone not planning on developing for the iphone (dropbox, you used to be cool). Being a C# developer this was bad news for me but I decided to give it a go anyway and after a few weeks of failed attempts and a few emails to support about my issues I realised the API documentation on the dropbox website is slightly wrong.

So now that I have it working I thought i’d share this with my fellow .NET developers (and anyone else who will care to listen).

What you will need (What i used):

  • RestSharp (What would i do without you…)
  • Oauth Library for C# (this one seems the easiest to use with RestSharp)
  • Access to the Dropbox API and an APIKey/Secret for your app

I guess I should start with the Setup of it, I started this as a Windows Mobile application but I switched to a .NET library so I could test it easier and also use RestSharp (might open source the library if I get around to it).

 

Login, this is possibly the easiest method if you have the right URL (the API documentation give you the wrong URL). We should be using “https://api.getdropbox.com/0/token” Code you say?

Update: Got some helpful advice about using the request.Resource property with parameters instead of a string.format.

public UserLogin Login(string email, string password)
{
    var restClient = new RestClient("https://api.getdropbox.com");
    var request = new RestRequest(Method.GET);
    request.Resource = "{version}/token";
    request.AddParameter("version", _version, ParameterType.UrlSegment);

    request.AddParameter("oauth_consumer_key", _apiKey);

    request.AddParameter("email", email);
    request.AddParameter("password", password);

    var response = restClient.Execute<UserLogin>(request);

    _userLogin = response.Data;

    return response.Data;
}

Seems pretty easy right? Most of thats RestSharp (with the JSONDeserializer), I then have the UserLogin class which is returned by this function.

public class UserLogin
{
    public string Token { get; set; }
    public string Secret { get; set; }
}

And now your user is logged in, you will then want to store the Users Token and Secret (storing UserLogin object would probably be better) as its used for the rest of the requests. I’ll just show you how to get the User Info as the other requests differ from the login (that is where we’ll need the Oauth stuff).

 

Account/Info, I’ll start with the Response classes this time…

public class AccountInfo
{
    public string Country { get; set; }
    public string Display_Name { get; set; }
    public QuotaInfo Quota_Info { get; set; }
    public string Uid { get; set; }
}

public class QuotaInfo
{
    public string Shared { get; set; }
    public string Quota { get; set; }
    public string Normal { get; set; }
}

These are the classes for RestSharp to Deserialize the JSON to. Pretty simple, this is straight off the API Documentation site. Now for the actual request…

public AccountInfo Account_Info()
{
    var restClient = new RestClient("http://api.dropbox.com");
    OAuthBase oAuth = new OAuthBase();
    string nonce = oAuth.GenerateNonce();
    string timeStamp = oAuth.GenerateTimeStamp();
    string normalizedUrl;
    string normalizedRequestParameters;
    string sig = oAuth.GenerateSignature(new Uri(string.Format("{0}/{1}/account/info", restClient.BaseUrl, _version)),
        _apiKey, _appsecret,
        _userLogin.Token, _userLogin.Secret,
        "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
    sig = HttpUtility.UrlEncode(sig);

    var request = new RestRequest(Method.GET);
    request.Resource = string.Format("{0}/account/info", _version);
    request.AddParameter("oauth_consumer_key", _apiKey);
    request.AddParameter("oauth_token", _userLogin.Token);
    request.AddParameter("oauth_nonce", nonce);
    request.AddParameter("oauth_timestamp", timeStamp);
    request.AddParameter("oauth_signature_method", "HMAC-SHA1");
    request.AddParameter("oauth_version", "1.0");
    request.AddParameter("oauth_signature", sig);

    var response = restClient.Execute<AccountInfo>(request);

    return response.Data;
}

Now, this request has a different Base Url to the Login function and this uses OAuth. So firstly we create an instance of the RestSharp client and the OAutheBase classes. The OAuthBase class then handles all of the oauth parameters that we need to make the Request (nonce, timestamp, etc.). GenerateSignature is the main 1 that rolls up the request path and the tokens/secrets into a hash for extra security. As for the dropbox part of this, we dont need any extra parameters as we are just getting the logged in users Account Info. Then its just a matter of adding these parameters to the RestRequest object, notice the oauth_token is actually the UserLogin.Token that we got from our Login method?

 

Stay tuned for more, Tales of interest!

 

Update: I have added a Part 2 to this post.

17 comments on “Dropbox API and RestSharp for a C# developer

  1. Loving the RestSharp blog posts!

    Someone has contributed an OAuthAuthenticator but I haven’t yet merged it in to the codebase. Soon!

  2. Thanks John,
    I was wondering about the OAuth thing in RestSharp. I didnt really plan on doing this with RestSharp as it was for a Windows Mobile app but since I couldnt figure it out I attempted it with RestSharp.

  3. Benjii says:

    nice work dk!

  4. Letteer says:

    Hey dk I’m working on a project using dropbox and c# .net, I’m having problems trying to put it all together using restsharp, trying to use OAuth as well…
    Send me an e-mail if you can help, Thanks!

  5. Nozzl says:

    Any chance you’d put source code up for the above? Or – have you done the code for uploading? Would love to see it :)

  6. admin says:

    Hey guys,
    I have put what code I have onto github for those of you having problems with this code.
    This is using my fork of RestSharp that has the OAuth Authenticator.
    http://github.com/dkarzon/DropNet

  7. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #607

  8. nice work dude. love to see the OAuth stuff in rest sharp proper.

  9. Pingback: progg.ru

  10. Pingback: Пятничные ссылки #3 | .NET разработка от devlanfear

  11. Very infomative, great job.

  12. mike2nl says:

    this will be dream stuff it is complete and ready. Congrats

  13. Brandon says:

    Posting OAuthAuthenticator was a big help! The one issue I have found is if you are setting an oauth_callback url, that parameter gets double encoded and you are not able to generate a request token. I fixed it by not urlencoding parameters in Authenticate() (since the RestSharp call will then re-encode them again later), but just UrlEncoding the values when generating the signature string.

  14. Uwe says:

    Would be great if the Upload method would allow for chunked uploads or at least for upload directly from file.

    I fear that uploading a 200 MB file (e.g.) eats up unnecessarily much RAM.

  15. andy says:

    Hi can someone please help med with API. I need to connect drop box to a C# project with API

  16. Samir says:

    I followed your example code and when I executed the function
    public AccountInfo Account_Info()

    var response = restClient.Execute(request);

    In the above line , response.Data comes null.

    What mistake I am making ?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>