An Introduction to the Dropbox API for Python
A few weeks ago, my girlfriend came home frustrated about work. She’s currently on co-op at an organization that develops curricula for developing countries. She writes textbooks and lessons for students - usually math. That day, she had been tasked with renaming the thousands of image files that they add to the textbooks from one naming convention to another. She had spent nearly her entire day doing it and still had much more to do. Why don’t you just write a python script to change the file names instead of doing it by hand?, I asked. It turns out these image files take up multiple terabytes of space on a Dropbox account - it wouldn’t be feasible to download these files, run a script on them, and then upload them again. Luckily, theres a Dropbox API for python.
Installing the API
It’s easiest to install the Dropbox API using pip. Short for Python Installs Python, pip is similar to ruby’s bundler - it will download and install python packages for you, automatically fetching their dependencies as well. To install pip:
- Download and run get-pip.py as an administrator.
- Edit the PATH environment variable to include the pip install directory. By default pip installs in
[Python Dir]/Scripts/
.
Once pip is installed, you can simply run pip install dropbox
from an administrator command prompt to install the Dropbox API. To verify that it was installed correctly, open a python command prompt and run import dropbox
- if you don’t get any errors you’re good to go.
Create a Dropbox Application
Dropbox requires that you register any application using their services through their developer console. To generate a new app key and secret:
- Log into the Dropbox Developer Console
- Click “Create App”.
- Check Dropbox API App.
- Can your app be limited to its own folder? - No
- What types of files does your app need access to? - All file types
- Provide an app name and aggree to the terms of service
- Click Create App
Copy down the App Key and App Secret from the settings page of your new app - these uniquely identify your application. Dropbox applications use OAuth 2.0 to allow access to a user’s files. This means that your application must request access (and be approved) to a user’s account.
Setup a Template for your Scripts
The API tutorial guides you through the process of setting up your first script and provides some examples of commmonly used functionality. Here’s a template script that you can use to get started:
Once you add your App Key and Secret, you can use this as a template, adding your scripting below it. When launched, it will prompt you to visit the authorization link in a web browser and ask you for the authorization code that this provides. You can add your scripting below this authorization step.
As an example, here’s a script to replace all underscores with dashes in file names in your /test/
directory:
For more details on the Dropbox API’s functionality, check out the documentation.