How to use Dropbox API with python

The Dropbox API makes it easy to upload, download, share, and delete files using python and is ideal for adding automation.

You can clone the GitHub repo having common Dropbox functions from here.

Installation:

Open the terminal and install python SDK via the PyPI package manager.

pip install dropbox

Integration:

from dropbox_toolkit.dbx_toolkit import DropboxToolkit
import json


f = open ('dropbox_credentials/credentials.json', 'r')  
credentials = json.loads(f.read())
dbx = DropboxToolkit(credentials)

Note: Place your Dropbox credentials in the dropbox_credentials/credentials.json file.

Get a list of files in a Dropbox folder:

To list all files in a folder you can use the list_file( ) method. This function takes the dropbox folder path as input and returns all files available in that folder.

dbx.list_files('/Dropbox folder path')

Get a list of folders in a Dropbox:

The above method list_files() returns a list of files only. If you want to list all files and folders, you can use the list_folders() method.

dbx.list_folders('/path')

The path can be a folder if you want to list all sub-folders and files from that folder, or you can use only double quotes ' ' to list all files/folders available in the App folder of your Dropbox account.

Download a file from Dropbox:

To download a file from dropbox you can simply use the download_file() method. The function takes two arguments dropbox_file_path is the path of the file you wanted to download and file_name is the name of the file. for example image.jpg.

dbx.download_file('/dropbox_file_path', 'file_name')

For example: dbx.download_file('/folder1/dummy_image.jpg**', 'downloads/image.jpg')

Upload a file to Dropbox:

To upload a file you need to use the upload_file() method. The function takes two arguments files and the path of Dropbox where you want to upload a file.

dbx.upload_file('local_file_path', '/dropbox_file_path')

For example : dbx.upload_file('dummy_image.jpg', '/folder1/dummy_image.jpg**')**

Delete a file from Dropbox:

You can use the delete_file() method to delete files from dropbox. Just need to enter the file path you want to delete.

dbx.delete_file('/path')

For example : dbx.delete_file('/folder1/dummy_image.jpg**')**

Create a folder in Dropbox:

Enter the path containing the folder name you want to create.

dbx.create_folder('path')

For example:

Suppose you have a subfolder folder2 having a parent directory folder1, you want to create a folder named new_folder then the path will be /folder1/folder2/new_folder.

dbx.create_folder('/folder1/folder2/new_folder')