### Install dropbox from source Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/README.rst Install the Dropbox SDK from source by cloning the repository and running pip install in the project directory. ```console $ git clone git://github.com/dropbox/dropbox-sdk-python.git $ cd dropbox-sdk-python $ pip install . ``` -------------------------------- ### Upload session batch example Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Complete example of using upload session start, append, and finish to upload a large file in chunks. Starts a session, appends each chunk with content hash, then finishes with overwrite mode. Prints the saved size and path. ```python import dropbox from dropbox import files dbx = dropbox.Dropbox("TOKEN") start = dbx.files_upload_session_start(b"", session_type=files.UploadSessionType.sequential) sid = start.session_id chunks = [b"part-one-", b"part-two", b"-three"] offset = 0 for chunk in chunks: dbx.files_upload_session_append_v2( chunk, files.UploadSessionCursor(sid, offset), content_hash=dropbox.content_hash.content_hash(chunk), ) offset += len(chunk) meta = dbx.files_upload_session_finish( b"", files.UploadSessionCursor(sid, offset), files.CommitInfo("/big.bin", mode=files.WriteMode.overwrite), ) print("saved", meta.size, "bytes as", meta.path_display) ``` -------------------------------- ### Install tox and run unit tests Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/CONTRIBUTING.md Install tox and run the unit test suite. Use this to verify changes locally. ```bash $ pip install tox $ tox ``` -------------------------------- ### DropboxOAuth2Flow full usage example Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/oauth.md Complete example using DropboxOAuth2Flow for a web app. It constructs a flow with a redirect URI and session, starts the flow, and in the callback handler exchanges the code and creates a Dropbox client. ```python from dropbox import DropboxOAuth2Flow from dropbox.oauth import BadStateException, CsrfException, NotApprovedException flow = DropboxOAuth2Flow( "APP_KEY", redirect_uri="https://example.com/callback", session=web_session, # your framework session dict csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret="APP_SECRET", token_access_type="offline", scope=["account_info.read"], ) authorize_url = flow.start(url_state="/dashboard") # ...in the callback handler: try: result = flow.finish(request.args) # query params dict dbx = Dropbox( oauth2_refresh_token=result.refresh_token, app_key="APP_KEY", app_secret="APP_SECRET", ) print("state returned:", result.url_state) except BadStateException: print("session expired; restart flow") except CsrfException: print("possible CSRF attack: 403") except NotApprovedException: print("user denied access") ``` -------------------------------- ### Downloader usage example Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/file-transfer.md Example of using Downloader to download a file sequentially with progress and retries, and in parallel with ranged requests. Demonstrates handling TransferError for hash mismatch. ```python from dropbox import Dropbox from dropbox.file_transfer import Downloader, File, DownloadOptions, DownloadProgress dbx = Dropbox("TOKEN") downloader = Downloader(dbx) def on_progress(p: DownloadProgress): print(f"{p.bytes_committed}/{p.total_bytes}") # Sequential with progress and retries result = downloader.download( "/large-file.bin", File("large-file.bin"), DownloadOptions(max_attempts=5, progress=on_progress), ) print("rev:", result.metadata.rev) # Parallel ranged download try: result = downloader.download( "/large-file.bin", File("large-file.bin"), DownloadOptions(parallel_downloads=4), ) except TransferError as e: print("transfer failed / hash mismatch:", e) ``` -------------------------------- ### Install dropbox via pip Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/README.rst Install the Dropbox SDK for Python using pip. Requires Python 3.11 or newer. ```console $ pip install dropbox ``` -------------------------------- ### DropboxOAuth2Flow start method signature Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/oauth.md Method signature for start, which generates and stores a CSRF token and returns the authorization URL. ```python def start(self, url_state=None): ``` -------------------------------- ### Uploader usage example Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/file-transfer.md Shows how to create an Uploader with a Dropbox client and upload a file with parallel uploads and retry options. The example uses FileUpload for a local file, but HTTPUpload can be used for a URL. It prints the uploaded file's path and size. ```python from dropbox import Dropbox from dropbox import files from dropbox.file_transfer import Uploader, FileUpload, UploadOptions dbx = Dropbox("TOKEN") uploader = Uploader(dbx) result = uploader.upload( FileUpload("large-file.bin"), # or HTTPUpload("https://...") files.CommitInfo("/large-file.bin", mode=files.WriteMode.overwrite), UploadOptions(parallel_uploads=4, max_attempts=5), ) print("uploaded:", result.metadata.path_display, result.metadata.size) ``` -------------------------------- ### Error handling for format_byte_range Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/http-helpers.md Error handling example demonstrating ValueError for end < start and TypeError for bool values. Shows how to catch these exceptions. ```python from dropbox._http import format_byte_range try: format_byte_range((500, 100)) # end < start except ValueError as e: print("invalid range:", e) try: format_byte_range((True, 100)) # bools rejected except TypeError as e: print("not an int range:", e) ``` -------------------------------- ### Download first 1 KiB with build_range_headers Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/http-helpers.md Example showing how to download the first 1 KiB of a file using build_range_headers as extra_headers to files_download. Includes assertions for format_byte_range output. ```python import dropbox from dropbox._http import build_range_headers, format_byte_range assert format_byte_range((0, 1023)) == "bytes=0-1023" assert format_byte_range((None, 1024)) == "bytes=-1024" dbx = dropbox.Dropbox("TOKEN") metadata, resp = dbx.files_download( "/big.bin", extra_headers=build_range_headers((0, 1023)), ) with open("first-1kb.bin", "wb") as f: f.write(resp.content) resp.close() ``` -------------------------------- ### DropboxOAuth2FlowNoRedirect start and finish method stubs Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/oauth.md Placeholder method signatures for the DropboxOAuth2FlowNoRedirect class. start() returns the authorization URL and finish(code) exchanges the code for tokens. ```python def start(self): ... def finish(self, code): ... ``` -------------------------------- ### files_upload usage example Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Example of uploading a file's contents using files_upload. Opens a local file, reads its bytes, and uploads to a Dropbox path with overwrite mode. Prints the returned metadata's revision and content hash. ```python import dropbox dbx = dropbox.Dropbox("TOKEN") with open("photo.jpg", "rb") as f: meta = dbx.files_upload(f.read(), "/backup/photo.jpg", mode=dropbox.files.WriteMode.overwrite) print(meta.rev, meta.content_hash) ``` -------------------------------- ### Paginating through folder entries with files_list_folder_continue Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Example of listing all entries under /docs with recursive=True and a limit of 200, then continuing with files_list_folder_continue while has_more is true. Prints the total number of entries. ```python result = dbx.files_list_folder("/docs", recursive=True, limit=200) entries = result.entries while result.has_more: result = dbx.files_list_folder_continue(result.cursor) entries += result.entries print(len(entries), "entries under /docs") ``` -------------------------------- ### files_list_folder(path, recursive=False, include_media_info=False, include_deleted=False, include_has_explicit_shared_members=False, include_mounted_folders=True, limit=None, shared_link=None, include_property_groups=None, include_non_downloadable_files=True, include_restorable_info=False) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Starts listing a folder. Returns a files.ListFolderResult containing entries, cursor, and has_more. If has_more is true, call files_list_folder_continue to fetch the next page. Raises ApiError with files.ListFolderError on failure. ```APIDOC ## files_list_folder ### Description Starts listing a folder. Returns a `files.ListFolderResult` with `entries` (list of `files.Metadata` subclasses: `FileMetadata`, `FolderMetadata`, `DeletedMetadata`), `cursor`, and `has_more`. When `has_more` is true call `files_list_folder_continue`. Raises `ApiError` with `files.ListFolderError`. Rate limiting is possible for concurrent identical calls. ### Method files_list_folder ### Parameters - **path** (string) - Required - The path to the folder to list. - **recursive** (boolean) - Optional - If true, list subfolders recursively. Default: False. - **include_media_info** (boolean) - Optional - If true, include media info. Default: False. - **include_deleted** (boolean) - Optional - If true, include deleted files. Default: False. - **include_has_explicit_shared_members** (boolean) - Optional - If true, include explicit shared members. Default: False. - **include_mounted_folders** (boolean) - Optional - If true, include mounted folders. Default: True. - **limit** (integer) - Optional - Maximum number of entries to return. - **shared_link** (object) - Optional - Shared link to list. - **include_property_groups** (object) - Optional - Property groups to include. - **include_non_downloadable_files** (boolean) - Optional - If true, include non-downloadable files. Default: True. - **include_restorable_info** (boolean) - Optional - If true, include restorable info. Default: False. ### Returns `files.ListFolderResult` with `entries`, `cursor`, and `has_more`. ### Raises `ApiError` with `files.ListFolderError`. ### Example ```python result = dbx.files_list_folder("/docs", recursive=True, limit=200) entries = result.entries while result.has_more: result = dbx.files_list_folder_continue(result.cursor) entries += result.entries print(len(entries), "entries under /docs") ``` ``` -------------------------------- ### DropboxOAuth2FlowNoRedirect full usage example Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/oauth.md Complete example using DropboxOAuth2FlowNoRedirect for a CLI app. It creates a flow with PKCE and offline access, prints the authorization URL, prompts for the code, and finishes the flow printing the access token, refresh token, expiration, and account ID. ```python from dropbox import DropboxOAuth2FlowNoRedirect flow = DropboxOAuth2FlowNoRedirect( "APP_KEY", use_pkce=True, token_access_type="offline", scope=["files.content.write"] ) print("Go to:", flow.start()) code = input("Enter authorization code: ").strip() try: result = flow.finish(code) except Exception as e: print("OAuth failed:", e) raise print(result.access_token, result.refresh_token, result.expires_at, result.account_id) ``` -------------------------------- ### files_upload_session_start(f, close=False, session_type=None, content_hash=None) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Starts an upload session. `f` is initial bytes (often `b""`); `close=True` finishes a single-call session; `session_type` is `files.UploadSessionType.sequential` (default) or `files.UploadSessionType.concurrent`; `content_hash` verifies the initial payload. ```APIDOC ## [UPLOAD] files/upload_session/start ### Description Starts an upload session. `f` is initial bytes (often `b""`); `close=True` finishes a single-call session; `session_type` is `files.UploadSessionType.sequential` (default) or `files.UploadSessionType.concurrent`; `content_hash` verifies the initial payload. ### Method UPLOAD ### Endpoint files/upload_session/start ### Arguments #### `f` (bytes) - Required - Initial bytes to upload. #### `close` (bool) - Optional - Default: `False` - If `True`, finishes a single-call session. #### `session_type` (files.UploadSessionType) - Optional - Default: `None` - Either `files.UploadSessionType.sequential` or `files.UploadSessionType.concurrent`. #### `content_hash` (Nullable[str]) - Optional - Default: `None` - Content hash of the initial payload for verification. ### Returns `files.UploadSessionStartResult` (contains `session_id`). ``` -------------------------------- ### file_properties_templates_get_for_user Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets a property template for a user. ```APIDOC ## file_properties_templates_get_for_user ### Description Gets a property template for a user. ### Method POST ### Endpoint file_properties/templates/get_for_user ### Parameters #### Request Body - template_id (string) - Required - The ID of the template. ### Response #### Success Response (200) - result (object) - The result of the operation. #### Response Example {} ``` -------------------------------- ### Download file with basic and range requests Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Example of downloading a file with the Dropbox SDK. The basic download writes the response content to a file and closes the response. The range download uses extra_headers with a Range header and catches ApiError to handle 'range/not_satisfiable' errors. ```python import dropbox dbx = dropbox.Dropbox("TOKEN") # Basic download metadata, resp = dbx.files_download("/docs/report.pdf") with open("report.pdf", "wb") as f: f.write(resp.content) resp.close() # Range download with error handling try: meta, resp = dbx.files_download("/big.bin", extra_headers={"Range": "bytes=0-1023"}) with open("chunk.bin", "wb") as f: f.write(resp.content) resp.close() except dropbox.exceptions.ApiError as e: if "range/not_satisfiable" in repr(e.error): print("server does not support the range") ``` -------------------------------- ### files_upload_session_start method signature Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Signature for starting an upload session. f is initial bytes (often b""); close=True finishes a single-call session; session_type is files.UploadSessionType.sequential (default) or files.UploadSessionType.concurrent; content_hash verifies the initial payload. Returns files.UploadSessionStartResult (session_id). ```python def files_upload_session_start(self, f, close=False, session_type=None, content_hash=None): ``` -------------------------------- ### files_list_folder method signature Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Signature for the files_list_folder method, which starts listing a folder. Returns files.ListFolderResult with entries, cursor, and has_more. Raises ApiError with files.ListFolderError. Rate limiting is possible for concurrent identical calls. ```python def files_list_folder( self, path, recursive=False, include_media_info=False, include_deleted=False, include_has_explicit_shared_members=False, include_mounted_folders=True, limit=None, shared_link=None, include_property_groups=None, include_non_downloadable_files=True, include_restorable_info=False, ): ``` -------------------------------- ### Update generated code Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/CONTRIBUTING.md Run these commands to update the generated code. Requires installing dependencies and initializing submodules. Stone updates must be made by updating requirements.txt. ```bash $ pip install -r requirements.txt $ git submodule init $ git submodule update --remote --recursive $ python generate_base_client.py ``` -------------------------------- ### Run backup-and-restore-sample.py Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/example/back-up-and-restore/README.md Run the backup and restore sample script from the example/backup-and-restore directory. After running, the file my-file-backup.txt should appear in the Dropbox account associated with the access token. ```bash python backup-and-restore-sample.py ``` -------------------------------- ### Build documentation locally Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/CONTRIBUTING.md Build the documentation locally. The output will be placed in the build/html directory. ```bash $ tox -e docs ``` -------------------------------- ### File target usage with prepare, write_at, commit, and abort Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/file-transfer.md Shows how to use the File target to download data to a file. It prepares with a DownloadInfo, writes data at an offset, commits to finalize, and aborts on TransferError. ```python target = File("/data/large.bin") try: target.prepare(DownloadInfo(size=1024)) target.write_at(b"x" * 1024, 0) target.commit() except TransferError as e: target.abort(e) ``` -------------------------------- ### Initialize Dropbox client with shared session Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/dropbox.md Shows basic client creation with a user token and sharing a connection pool across two clients using dropbox.create_session. ```python import dropbox # Basic user-token client dbx = dropbox.Dropbox("YOUR_ACCESS_TOKEN") print(dbx.users_get_current_account()) # Sharing one connection pool across two clients session = dropbox.create_session(max_connections=16) dbx1 = dropbox.Dropbox("TOKEN_A", session=session) dbx2 = dropbox.Dropbox("TOKEN_B", session=session) ``` -------------------------------- ### files_get_preview(path, rev=None) / files_get_preview_to_file(download_path, path, rev=None) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Renders a preview of a file. The `_to_file` variant downloads the preview to a local file. Returns file metadata and response. ```APIDOC ## files_get_preview(path, rev=None) / files_get_preview_to_file(download_path, path, rev=None) ### Description Renders a preview of a file (download style). Returns `(files.FileMetadata, response)` or metadata for the `_to_file` variant. ### Method files_get_preview / files_get_preview_to_file ### Parameters - **path** (string) - Required - The path to the file. - **rev** (string) - Optional - The revision of the file to preview. - **download_path** (string) - Required for `_to_file` variant - The local path to save the preview. ### Return Type `(files.FileMetadata, response)` or metadata for the `_to_file` variant. ### Source `dropbox/base.py:1800,1838` ``` -------------------------------- ### file_requests_get Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets a file request. ```APIDOC ## file_requests_get ### Description Gets a file request. ### Method POST ### Endpoint file_requests/get ### Parameters #### Request Body - id (string) - Required - The ID of the file request. ### Response #### Success Response (200) - result (object) - The result of the operation. #### Response Example {} ``` -------------------------------- ### ListFolderGetLatestCursorResult Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/types.md Result of getting the latest cursor for a folder. ```APIDOC ## ListFolderGetLatestCursorResult ### Description Result of getting the latest cursor for a folder. ### Fields - **cursor** (str) - The latest cursor. ``` -------------------------------- ### account_get_photo Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets a user's account photo. ```APIDOC ## account_get_photo ### Description Gets a user's account photo. ### Method POST ### Endpoint account/get_photo ### Parameters #### Request Body - dbx_account_id (string) - Required - The account ID of the user. - size (object) - Optional - The size of the photo. - circle_crop (boolean) - Optional - Whether to crop the photo to a circle. - expect_account_photo (boolean) - Optional - Whether to expect an account photo. ### Response #### Success Response (200) - result (object) - The result of the operation. #### Response Example {} ``` -------------------------------- ### Run integration tests Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/CONTRIBUTING.md Set required environment variables and run integration tests. Requires a refresh token, app key, app secret, team token, and access token. If you lack these, rely on CI integration tests. ```bash $ export DROPBOX_REFRESH_TOKEN={fill in refresh token} $ export DROPBOX_APP_KEY={fill in app key} $ export DROPBOX_APP_SECRET={fill in app secret} $ export DROPBOX_TEAM_TOKEN={fill in team token} $ export DROPBOX_TOKEN={fill in access token} $ tox -e test_integration ``` -------------------------------- ### Downloader class constructor Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/file-transfer.md Initializes a Downloader instance with a Dropbox-like client that must expose files_download. ```python class Downloader(object): def __init__(self, client): self.client = client ``` -------------------------------- ### Basic client with error handling Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Initializes a Dropbox client with an access token and uploads a file, handling AuthError for bad tokens and ApiError for file conflicts. Uses dropbox.files.WriteMode.overwrite. ```python import dropbox from dropbox.exceptions import ApiError, AuthError dbx = dropbox.Dropbox("YOUR_ACCESS_TOKEN") try: metadata = dbx.files_upload(b"hello world", "/hello.txt", mode=dropbox.files.WriteMode.overwrite) print(metadata.rev) except AuthError as e: print("Bad token:", e) except ApiError as e: if e.error.is_path() and e.error.get_path().is_conflict(): print("File conflict:", e.request_id) ``` -------------------------------- ### UploadSessionStartResult Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/types.md Result of starting an upload session, containing the session identifier. ```APIDOC ## UploadSessionStartResult ### Description Result of starting an upload session, containing the session identifier. ### Fields - **session_id** (str) - The session identifier. ``` -------------------------------- ### users_get_account_batch(account_ids) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets multiple accounts. This method corresponds to the 'users/get_account_batch' endpoint. ```APIDOC ## users_get_account_batch(account_ids) ### Description Gets multiple accounts. ### Method POST ### Endpoint users/get_account_batch ### Parameters #### Request Body - **account_ids** (list) - Required - List of account IDs to retrieve. ### Response #### Success Response (200) Returns multiple account details. ``` -------------------------------- ### account_get_photo_to_file Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets a user's account photo and saves it to a local file. ```APIDOC ## account_get_photo_to_file ### Description Gets a user's account photo and saves it to a local file. ### Method POST ### Endpoint account/get_photo ### Parameters #### Path Parameters - download_path (string) - Required - The local file path to save the photo to. #### Request Body - dbx_account_id (string) - Required - The account ID of the user. - size (object) - Optional - The size of the photo. - circle_crop (boolean) - Optional - Whether to crop the photo to a circle. - expect_account_photo (boolean) - Optional - Whether to expect an account photo. ### Response #### Success Response (200) - result (object) - The result of the operation. - response (object) - The response metadata. #### Response Example {} ``` -------------------------------- ### Set Dropbox access token Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/example/back-up-and-restore/README.md Set your Dropbox access token in backup-and-restore-sample.py before running the sample. Replace the empty string with your own token obtained from the Dropbox account you want to use. ```python TOKEN = '' ``` -------------------------------- ### users_get_current_account() Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets the current user's account. This method corresponds to the 'users/get_current_account' endpoint. ```APIDOC ## users_get_current_account() ### Description Gets the current user's account. ### Method POST ### Endpoint users/get_current_account ### Parameters None ### Response #### Success Response (200) Returns the current user's account details. ``` -------------------------------- ### users_get_space_usage() Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets the current user's space usage. This method corresponds to the 'users/get_space_usage' endpoint. ```APIDOC ## users_get_space_usage() ### Description Gets the current user's space usage. ### Method POST ### Endpoint users/get_space_usage ### Parameters None ### Response #### Success Response (200) Returns the current user's space usage. ``` -------------------------------- ### Dropbox constructor (__init__) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Constructor for the Dropbox client. Accepts OAuth2 tokens, retry settings, session, headers, timeout, and other options. Raises BadInputException for invalid combinations of parameters. ```python def __init__( self, oauth2_access_token=None, max_retries_on_error=4, max_retries_on_rate_limit=None, user_agent=None, session=None, headers=None, timeout=DEFAULT_TIMEOUT, oauth2_refresh_token=None, oauth2_access_token_expiration=None, app_key=None, app_secret=None, scope=None, ca_certs=None, auto_content_hash=True, ): ``` -------------------------------- ### users_get_account(account_id) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets a user's account details. This method corresponds to the 'users/get_account' endpoint. ```APIDOC ## users_get_account(account_id) ### Description Gets a user's account details. ### Method POST ### Endpoint users/get_account ### Parameters #### Request Body - **account_id** (string) - Required - The account ID of the user. ### Response #### Success Response (200) Returns the account details. ``` -------------------------------- ### openid_userinfo Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets fresh user claims (OpenID Connect) for the access token's scopes. ```APIDOC ## openid_userinfo ### Description Gets fresh user claims (OpenID Connect) for the access token's scopes. ### Method POST ### Endpoint openid/userinfo ### Parameters None ### Response #### Success Response (200) - result (object) - The result of the operation. #### Response Example {} ``` -------------------------------- ### sharing_get_shared_links Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets a list of shared links. This method is part of the sharing namespace and maps to the 'sharing/get_shared_links' endpoint. ```APIDOC ## sharing_get_shared_links ### Description Gets a list of shared links. ### Method POST ### Endpoint sharing/get_shared_links ### Parameters - **path** (string) - Optional - The path to filter by. ``` -------------------------------- ### Dropbox Constructor Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Creates a Dropbox client instance with the given OAuth2 credentials and configuration options. ```APIDOC ## Dropbox Constructor ### Description Initializes a Dropbox client for making API requests on behalf of a user. ### Method Constructor ### Signature ```python def __init__( self, oauth2_access_token=None, max_retries_on_error=4, max_retries_on_rate_limit=None, user_agent=None, session=None, headers=None, timeout=DEFAULT_TIMEOUT, oauth2_refresh_token=None, oauth2_access_token_expiration=None, app_key=None, app_secret=None, scope=None, ca_certs=None, auto_content_hash=True, ) ``` ### Parameters - `oauth2_access_token` (str) - Optional - OAuth2 access token for making client requests. - `max_retries_on_error` (int) - Optional - Number of retries on 5xx errors. Default: 4. - `max_retries_on_rate_limit` (Optional[int]) - Optional - Number of retries on 429 errors; `None` means always retry. - `user_agent` (str) - Optional - Custom user agent prefix; the SDK appends `/OfficialDropboxPythonSDKv2/<__version__>`. - `session` (requests.sessions.Session) - Optional - Shared session/connection pool. - `headers` (dict) - Optional - Additional headers added to every request. - `timeout` (Optional[float]) - Optional - Max seconds to wait for any single packet; `None` waits forever. Default: 100. - `oauth2_refresh_token` (str) - Optional - Refresh token used to obtain new access tokens. - `oauth2_access_token_expiration` (datetime) - Optional - Expiration of `oauth2_access_token`. - `app_key` (str) - Optional - App key; required for token refresh and app auth. - `app_secret` (str) - Optional - App secret; required for token refresh unless PKCE was used. - `scope` (list) - Optional - Scopes requested on refresh; empty list is rejected. - `ca_certs` (str) - Optional - Path to PEM CA certificate bundle. - `auto_content_hash` (bool) - Optional - When uploading `bytes`, compute and send `content_hash` so the server verifies integrity. Default: True. ### Raises - `BadInputException` if none of `oauth2_access_token`, `oauth2_refresh_token`, or (`app_key` and `app_secret`) is set; `headers` is not a dict; `oauth2_refresh_token` is set without `app_key`; `scope` is not a non-empty list; `session` is not a `requests.sessions.Session`. ### Example ```python from dropbox import Dropbox dbx = Dropbox(oauth2_access_token='YOUR_ACCESS_TOKEN') ``` ``` -------------------------------- ### sharing_get_shared_link_metadata Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets metadata for a shared link. This method is part of the sharing namespace and maps to the 'sharing/get_shared_link_metadata' endpoint. ```APIDOC ## sharing_get_shared_link_metadata ### Description Gets metadata for a shared link. ### Method POST ### Endpoint sharing/get_shared_link_metadata ### Parameters - **url** (string) - Required - The shared link URL. - **path** (string) - Optional - The path to the file. - **link_password** (string) - Optional - The password for the link. ``` -------------------------------- ### DropboxOAuth2Flow.__init__() Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/oauth.md Constructor for web apps with a redirect URI. Adds redirect_uri, session, and csrf_token_session_key parameters after consumer_key. ```APIDOC ## DropboxOAuth2Flow.__init__() ### Description Constructor for web apps with a redirect URI. Adds two parameters after `consumer_key`. ### Parameters #### Constructor Parameters - **consumer_key** (string) - Required - The Dropbox app key. - **redirect_uri** (string) - Required - Pre-registered HTTPS URI (localhost URIs may be HTTP). - **session** (dict-like) - Required - The web session used to store the CSRF token. - **csrf_token_session_key** (string) - Required - Session key for the CSRF token (e.g. `"dropbox-auth-csrf-token"`). - **consumer_secret** (string) - Optional - The Dropbox app secret. - **locale** (string) - Optional - Locale for error messages. - **token_access_type** (string) - Optional - Type of token access (e.g., "offline"). - **scope** (list) - Optional - List of OAuth scopes. - **include_granted_scopes** (string) - Optional - How to include granted scopes. - **use_pkce** (boolean) - Optional - Whether to use PKCE. - **timeout** (number) - Optional - Timeout for requests. - **ca_certs** (string) - Optional - Path to CA certificates. ### Request Example ```python from dropbox import DropboxOAuth2Flow flow = DropboxOAuth2Flow( "APP_KEY", redirect_uri="https://example.com/callback", session=web_session, csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret="APP_SECRET", token_access_type="offline", scope=["account_info.read"], ) ``` ``` -------------------------------- ### sharing_get_folder_metadata Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets metadata for a shared folder. This method is part of the sharing namespace and maps to the 'sharing/get_folder_metadata' endpoint. ```APIDOC ## sharing_get_folder_metadata ### Description Gets metadata for a shared folder. ### Method POST ### Endpoint sharing/get_folder_metadata ### Parameters - **shared_folder_id** (string) - Required - The ID of the shared folder. - **actions** (list) - Optional - A list of actions to include. ``` -------------------------------- ### Catch TLS and authentication errors with pinned certs Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/dropbox.md Shows how to create a client with custom CA certificates and timeout, and catch dropbox.SSLError and dropbox.exceptions.AuthError. ```python import dropbox try: dbx = dropbox.Dropbox( "YOUR_ACCESS_TOKEN", ca_certs="/etc/ssl/certs/ca-certificates.crt", timeout=30, ) dbx.check_user("hello") except dropbox.SSLError as e: # TLS certificate verification failed print("TLS error:", e) except dropbox.exceptions.AuthError as e: # Invalid access token (HTTP 401) print("auth error:", e) ``` -------------------------------- ### sharing_get_file_metadata Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets metadata for a shared file. This method is part of the sharing namespace and maps to the 'sharing/get_file_metadata' endpoint. ```APIDOC ## sharing_get_file_metadata ### Description Gets metadata for a shared file. ### Method POST ### Endpoint sharing/get_file_metadata ### Parameters - **file** (string) - Required - The file to get metadata for. - **actions** (list) - Optional - A list of actions to include. ``` -------------------------------- ### sharing_get_file_metadata_batch Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Gets metadata for multiple shared files. This method is part of the sharing namespace and maps to the 'sharing/get_file_metadata/batch' endpoint. ```APIDOC ## sharing_get_file_metadata_batch ### Description Gets metadata for multiple shared files. ### Method POST ### Endpoint sharing/get_file_metadata/batch ### Parameters - **files** (list) - Required - A list of files to get metadata for. - **actions** (list) - Optional - A list of actions to include. ``` -------------------------------- ### format_byte_range(byte_range) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/http-helpers.md Formats a (start, end) tuple as an HTTP Range header value, or None when byte_range is None. Raises ValueError or TypeError for invalid inputs. ```APIDOC ## format_byte_range(byte_range) ### Description Formats a `(start, end)` tuple as an HTTP `Range` header value, or `None` when `byte_range` is `None`. ### Function Signature ```python def format_byte_range(byte_range): """Format a byte range as an HTTP Range header value.""" ``` ### Parameters - **byte_range** (tuple or None) - Required - A `(start, end)` tuple where each element is a non-negative integer or `None`. `None` returns `None`. ### Return Value - **str or None** - The formatted HTTP Range header value, or `None` if `byte_range` is `None`. ### Valid Range Forms | Input | Output | |-------|--------| | `None` | `None` | | `(start, None)` | `"bytes=-"` (open-ended suffix) | | `(None, end)` | `"bytes=-"` (last `end` bytes) | | `(start, end)` | `"bytes=-"` | ### Exceptions | Exception | Condition | |-----------|-----------| | `ValueError` | `byte_range` is not a 2-element tuple; both `start` and `end` are `None`; a value is negative; `end < start`. | | `TypeError` | A value is a `bool` or not an `int` (values must be non-negative integers). | ### Example ```python from dropbox._http import format_byte_range assert format_byte_range((0, 1023)) == "bytes=0-1023" assert format_byte_range((None, 1024)) == "bytes=-1024" ``` ``` -------------------------------- ### Sharing a session and using a context manager Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Creates a shared session with custom connection settings and uses two Dropbox clients within context managers to ensure proper cleanup. ```python import dropbox session = dropbox.create_session(max_connections=8, proxies={"https": "http://proxy.local:8080"}) with dropbox.Dropbox("TOKEN_A", session=session) as dbx_a: with dropbox.Dropbox("TOKEN_B", session=session) as dbx_b: print(dbx_a.check_user("a"), dbx_b.check_user("b")) ``` -------------------------------- ### Dropbox.with_path_root() Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Returns a clone of the client with a Dropbox-API-Path-Root header set to the given PathRoot. ```APIDOC ## Dropbox.with_path_root() ### Description Returns a clone of the client with `Dropbox-API-Path-Root: ` added to its headers. `path_root` must be a `dropbox.common.PathRoot` instance, otherwise `ValueError` is raised. ### Method with_path_root ### Signature ```python def with_path_root(self, path_root): ``` ### Parameters - `path_root` (dropbox.common.PathRoot) - Required - The path root to set. ### Returns - A new `Dropbox` instance with the path root header set. ### Raises - `ValueError` if `path_root` is not a `dropbox.common.PathRoot` instance. ``` -------------------------------- ### as_user method Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Returns a Dropbox client that acts as the given team member by adding the Dropbox-API-Select-User header. ```python def as_user(self, team_member_id): ``` -------------------------------- ### Uploader class constructor Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/file-transfer.md Initializes an Uploader instance with a client that must expose files_upload_session_start, files_upload_session_append_v2, and files_upload_session_finish. ```python class Uploader(object): def __init__(self, client): self.client = client ``` -------------------------------- ### Reliable file transfer with dropbox.file_transfer Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/README.rst Use dropbox.file_transfer for reliable file transfers with retry, progress, validation, and optional parallel ranged transfers. This example downloads and uploads a file with parallel downloads and uploads enabled. ```python import dropbox from dropbox import files from dropbox.file_transfer import ( DownloadOptions, File, FileUpload, Uploader, UploadOptions, Downloader, ) dbx = dropbox.Dropbox("YOUR_ACCESS_TOKEN") Downloader(dbx).download( "/large-file.bin", File("large-file.bin"), DownloadOptions(parallel_downloads=4), ) Uploader(dbx).upload( FileUpload("large-file.bin"), files.CommitInfo("/large-file.bin", mode=files.WriteMode.overwrite), UploadOptions(parallel_uploads=4), ) ``` -------------------------------- ### Dropbox.clone() Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/client.md Creates a new copy of the client with the same defaults, overridden by any given argument. ```APIDOC ## Dropbox.clone() ### Description Creates a new copy of the client with the same defaults, overridden by any given argument. Every constructor parameter can be passed; only the `auto_content_hash` parameter may explicitly receive `False` (all others fall back to the source instance when falsy). ### Method clone ### Signature ```python def clone( self, oauth2_access_token=None, max_retries_on_error=None, max_retries_on_rate_limit=None, user_agent=None, session=None, headers=None, timeout=None, oauth2_refresh_token=None, oauth2_access_token_expiration=None, app_key=None, app_secret=None, scope=None, auto_content_hash=None, ) ``` ### Parameters - `oauth2_access_token` (str) - Optional - OAuth2 access token for making client requests. - `max_retries_on_error` (int) - Optional - Number of retries on 5xx errors. - `max_retries_on_rate_limit` (Optional[int]) - Optional - Number of retries on 429 errors. - `user_agent` (str) - Optional - Custom user agent prefix. - `session` (requests.sessions.Session) - Optional - Shared session/connection pool. - `headers` (dict) - Optional - Additional headers added to every request. - `timeout` (Optional[float]) - Optional - Max seconds to wait for any single packet. - `oauth2_refresh_token` (str) - Optional - Refresh token used to obtain new access tokens. - `oauth2_access_token_expiration` (datetime) - Optional - Expiration of `oauth2_access_token`. - `app_key` (str) - Optional - App key. - `app_secret` (str) - Optional - App secret. - `scope` (list) - Optional - Scopes requested on refresh. - `auto_content_hash` (bool) - Optional - When uploading `bytes`, compute and send `content_hash`. ### Returns - A new instance of the same class (`self.__class__`). ``` -------------------------------- ### DropboxOAuth2Flow.start(url_state=None) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/oauth.md Generates a CSRF token, stores it in the session, and returns the authorization URL. Optionally appends url_state after a pipe. ```APIDOC ## DropboxOAuth2Flow.start(url_state=None) ### Description Generates a CSRF token (16 random bytes, base64-url-encoded), stores it in `session[csrf_token_session_key]`, and returns the authorization URL. If `url_state` is given, it is appended after `|` and returned verbatim by `finish`. ### Method GET ### Endpoint `https://www.dropbox.com/oauth2/authorize` ### Parameters #### Query Parameters - **url_state** (string) - Optional - State to be appended to the authorization URL after a pipe. ### Request Example ```python from dropbox import DropboxOAuth2Flow flow = DropboxOAuth2Flow( "APP_KEY", redirect_uri="https://example.com/callback", session=web_session, csrf_token_session_key="dropbox-auth-csrf-token", consumer_secret="APP_SECRET", token_access_type="offline", scope=["account_info.read"], ) authorize_url = flow.start(url_state="/dashboard") ``` ### Response #### Success Response (200) - **authorization_url** (string) - The Dropbox authorization URL with CSRF token and optional url_state. #### Response Example ``` https://www.dropbox.com/oauth2/authorize?...&state=...|/dashboard ``` ``` -------------------------------- ### RootInfo (struct), TeamRootInfo(RootInfo), UserRootInfo(RootInfo) Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/types.md Data structures representing root information for a user or team account, received from users_get_current_account().root_info. ```APIDOC ## RootInfo (struct) ### Description Base struct for root information. Received from `users_get_current_account().root_info` / `FullAccount.root_info`. ### Fields - `root_namespace_id` (str) - Required - The root namespace ID. - `home_namespace_id` (str) - Required - The home namespace ID. ## TeamRootInfo(RootInfo) ### Description Extends `RootInfo` with team-specific information. ### Additional Fields - `home_path` (str) - Required - The home path for the team. ## UserRootInfo(RootInfo) ### Description Extends `RootInfo` with user-specific information. ### Additional Fields - `home_path` (Nullable[str]) - Optional - The home path for the user. ### Usage ```python from dropbox.common import RootInfo, TeamRootInfo, UserRootInfo # Access root info from account account = client.users_get_current_account() root_info = account.root_info print(root_info.root_namespace_id) ``` ``` -------------------------------- ### Paginated search with files_search_v2 and files_search_continue_v2 Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Searches for 'budget' in the /docs folder and iterates through all matches using the cursor. Prints each match's name until has_more is false. ```python res = dbx.files_search_v2("budget", options=files.SearchOptions(path="/docs")) while True: for m in res.matches: entry = m.metadata print(entry.name) if not res.has_more: break res = dbx.files_search_continue_v2(res.cursor) ``` -------------------------------- ### check_app Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md App authentication echo test; app key/secret auth. ```APIDOC ## check_app ### Description App authentication echo test; app key/secret auth. ### Method POST ### Endpoint check/app ### Parameters #### Query Parameters - query (string) - Optional - The query string to echo back. ### Response #### Success Response (200) - result (object) - The result of the operation. #### Response Example {} ``` -------------------------------- ### files_search_v2 method signature Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base-files.md Current search method. options is a files.SearchOptions, match_field_options a files.SearchMatchFieldOptions. Returns files.SearchV2Result with matches, has_more, and cursor. Use files_search_continue_v2 for pagination. Max 10,000 matches. ```python def files_search_v2(self, query, options=None, match_field_options=None, include_highlights=None): ``` -------------------------------- ### file_properties_templates_list_for_user Source: https://github.com/dropbox/dropbox-sdk-python/blob/main/_autodocs/api-reference/base.md Lists property templates for a user. ```APIDOC ## file_properties_templates_list_for_user ### Description Lists property templates for a user. ### Method POST ### Endpoint file_properties/templates/list_for_user ### Parameters None ### Response #### Success Response (200) - result (object) - The result of the operation. #### Response Example {} ```