Dropbox REST API Part 2: API Requests
January 8, 2012
In the previous article, Dropbox REST API Part 1: Authentication, I showed you how you can obtain an access token using the Dropbox REST API and OAuth.
Once you have an access token, you can use it to access the main Dropbox REST API. Let’s demonstrate this by using some of the API’s requests such as retrieving account information and file (and directory) metadata.
It’s actually surprisingly easy. In the next part we’ll explore other options such as creating, deleting and moving folders.
Let’s get started…
I took the source code from the first article (#62) in this series and structured it a bit differently, but in essence it still performs the same functionality. In this post I’ll only list the source code necessary to retrieve account information and file/folder metadata. You can check out how to retrieve an access token by reading the previous article and/or checking out the source code of this post.
Using the refactored code retrieving account information is very simple.
var accessToken = ...; var api = new DropboxApi("your API key", "your API secret", accessToken); var account = api.GetAccountInfo();
I created a class called DropboxApi. When creating an instance of this class you pass it your API key and secret (consumer key and secret) and an access token. By calling the GetAccountInfo() method you can retrieve information about the user’s Dropbox account.
The GetAccountInfo() method executes the following code:
public Account GetAccountInfo() { var uri = new Uri(new Uri(DropboxRestApi.BaseUri), "account/info"); var json = GetResponse(uri); return ParseJson<Account>(json); }
The DropboxRestApi.BaseUri returns the base URL for the REST API, namely https://api.dropbox.com/1. To retrieve the account information you need to append account/info to it. Thus behind the scenes a request is sent to:
https://api.dropbox.com/1/account/info
You need to sign this request using your consumer key, secret and access token. If you don’t sign the request you’ll receive the error “Invalid OAuth request”.
During the authentication phase you already saw how to sign a request using OAuth. Well…you can reuse that same code. Just check out the previous article to see how signing requests works.
To make it easy I moved this code into its own class called OAuth. Using this class you can sign a request using just two lines of code:
var oauth = new OAuth(); var requestUri = oauth.SignRequest( uri, "API key", "API secret", accessToken);
Just create a new instance of the OAuth class and call the SignRequest(…) method. Pass in the URI you wish to sign, your API key and secret and your access token.
This will transform:
https://api.dropbox.com/1/account/info
into something like this:
The GetAccountInfo() method does this by calling the GetResponse(…) method. This method signs the request, sends it and returns the response.
private string GetResponse(Uri uri) { var oauth = new OAuth(); var requestUri = oauth.SignRequest( uri, _consumerKey, _consumerSecret, _accessToken); var request = (HttpWebRequest) WebRequest.Create(requestUri); request.Method = WebRequestMethods.Http.Get; var response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); return reader.ReadToEnd(); }
The Dropbox REST API returns it responses in JSON format. Here’s an example response containing account information:
{
"referral_link": "https://www.dropbox.com/referrals/r1a2n3d4m5s6t7",
"display_name": "John P. User",
"uid": 12345678,
"country": "US",
"quota_info": {
"shared": 253738410565,
"quota": 107374182400000,
"normal": 680031877871
},
"email": "john@example.com"
}
It contains some general information about the user (id, name, e-mail address…) and his allocated quota. Using the Json.NET library we can easily deserialize this data into a .NET object. Let’s create a simple Account class into which we can deserialize this data.
[JsonObject(MemberSerialization.OptIn)] public class Account { [JsonProperty(PropertyName = "uid")] public int Id { get; internal set; } [JsonProperty(PropertyName = "referral_link")] public string ReferralLink { get; internal set; } [JsonProperty(PropertyName = "display_name")] public string DisplayName { get; internal set; } [JsonProperty(PropertyName = "email")] public string Email { get; internal set; } [JsonProperty(PropertyName = "country")] public string Country { get; internal set; } [JsonProperty(PropertyName = "quota_info")] public Quota Quota { get; internal set; } }
The Quota type is equally simple.
[JsonObject(MemberSerialization.OptIn)] public class Quota { [JsonProperty(PropertyName = "quota")] public long Total { get; internal set; } [JsonProperty(PropertyName = "shared")] public long Shared { get; internal set; } [JsonProperty(PropertyName = "normal")] public long Normal { get; internal set; } }
Don’t forget to install NuGet and to download the Json.NET library.
The last line of code of the GetAccountInfo() method deserializes the JSON data by calling the ParseJson(…) method;
private static T ParseJson<T>(string json) where T : class, new() { var jobject = JObject.Parse(json); return JsonConvert.DeserializeObject<T>(jobject.ToString()); }
Just parse the JSON data and use the JsonConvert type to deserialize it into the type specified by the generic T parameter. As long as the type specified by T has been decorated with the correct Json.NET attributes it will deserialize without a problem.
By now you’ve seen how to retrieve the account information. It’s consists out of 3 steps, namely:
- Compose the URI for the request
- Sign and send the request
- Parse the response (JSON) into a .NET object
Most (if not all) of the Dropbox API requests can be dealt with in the same fashion. For instance, retrieving a list of files/folders that are stored in our Dropbox can be done in the same way.
var api = new DropboxApi(ConsumerKey, ConsumerSecret, accessToken); var publicFolder = api.GetFiles("dropbox", "Public"); foreach (var file in publicFolder.Contents) { Console.WriteLine(file.Path); }
Here I retrieve a list of files/folders that are stored in my public Dropbox folder. The first parameter specified the root. Valid values are sandbox and dropbox. The second parameter specifies the path of the file or folder relative to the root.
Retrieving a list of files/folders supports many more parameters, but to keep things simple I’ve chosen to only support these two parameters. For a complete list check out the Dropbox REST API documentation:
https://www.dropbox.com/developers/reference/api#metadata
Apart from the URI and the return value (T) the GetFiles(…) methods looks identical to the GetAccountInfo() method.
public File GetFiles(string root, string path) { var uri = new Uri(new Uri(DropboxRestApi.BaseUri), String.Format("metadata/{0}/{1}", root, path)); var json = GetResponse(uri); return ParseJson<File>(json); }
The URI is composed, then the request is signed and send. Last, but not least the response (JSON) is parsed and converted to a .NET object of the type File.
The following listing contains a small part of the File type. It contains the metadata for a file or folder at a given path. If it is a directory (IsDirectory property) then the metadata will also include a listing of metadata for the folder’s contents (Contents property).
[JsonObject(MemberSerialization.OptIn)] public class File { [JsonProperty(PropertyName = "size")] public string Size { get; internal set; } [JsonProperty(PropertyName = "rev")] public string Revision { get; internal set; } [JsonProperty(PropertyName = "is_dir")] public bool IsDirectory { get; internal set; } [JsonProperty(PropertyName = "root")] public string Root { get; internal set; } [JsonProperty(PropertyName = "path")] public string Path { get; internal set; } [JsonProperty(PropertyName = "contents")] public IEnumerable<File> Contents { get; internal set; } //... }
Example output:
Retrieving metadata works in exactly the same way as retrieving account information. With this code you are now armed to implement other Dropbox API requests. In the next part of this series I’ll explore some other requests concerning file operations (create, move and delete a folder).
Check out the Dropbox REST API documentation if you want to explore it further.
https://www.dropbox.com/developers/reference/api
You can download the source code accompanying this article from the download page. If you have any questions or suggestions please drop me an e-mail or submit a comment.




January 8, 2012 at 17:22000000
[...] Dropbox REST API Part 2: API Requests (Christophe Geers) [...]
January 9, 2012 at 15:19000000
[...] Dropbox REST API Part 2: API Requests (Christophe Geers) [...]
January 30, 2012 at 17:30000000
Hi again, i was testing this and i have doubt with the path of the getFiles method:
For example if we want to access the Public folder of the Dropbox, we can do it by this:
var publicFolder = api.GetFiles(“dropbox”, “Public”);
But i can’t access for example the folder (dropbox/Apps/My App), what wold be the right path for that folder?
January 30, 2012 at 17:33000000
That would be:
var apps = api.GetFiles(“dropbox”, “Apps/My App”);
if I’m not mistaken…
January 30, 2012 at 17:50000000
I have try that and it doesn’t work.
January 30, 2012 at 17:59000000
Getting the error 400 when the getFiles executes the getResponse method, at : var response = request.GetResponse();
February 1, 2012 at 8:11000000
Yes, it threw the same exception in my side when getting files or folder. Any idea? Our app is on the development status.
February 1, 2012 at 9:31000000
According to the Dropbox REST API documentation:
http://www.dropbox.com/developers/reference/api
an error code of 400 means
“Bad input parameter. Error message should indicate which one and why.”
Can you inspect the exception and see which message it returns? It should tell you which input parameter is incorrect. You can always copy the generated URL and paste in the browser’s address bar. You should then see the error message.
Since my sample only uses the root and the path and none of the optional parameters you are likely trying to retrieve the metadata for a path that does not exist.
Note that the sandbox environment is not a copy of the dropbox environment. It does not contains the same files, directories.
Just try it without a path first. Only try to get the metadata for the root.
var root = api.GetFiles(“dropbox”, “”);
or
var root = api.GetFiles(“sandbox”, “”);
Then you can dig deeper and specify a path by using the returned metadata.
February 5, 2012 at 18:58000000
i found this error please reply soon
The remote server returned an error: (403) Forbidden at line 1 (marks as one)
private string GetResponse(Uri uri)
{
var oauth = new OAuth();
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken);
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Post;
// 1 var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
February 5, 2012 at 19:17000000
403 Forbidden usually from an invalid app key pair or other permanent error. Check your app key + secret and access token.
Your application is probably not authorized or you are using an invalid access token. Hence you are not granted access, thus the 403: Forbidden error.