We Want to Hear From You! What Do You Want to See on the Community? Tell us here!
Forum Discussion
rahulj1
3 years agoExplorer | Level 4
Access Shared Folder with API
Hi Team,
can any one please help me to get access in shared folder to extract the meta data like subfolder size and file count.
I was unable to locate the shared folder through api always it says, lookup not found:
Error: ApiError('e266db43b6334ae9bacaa86ee7c566b4', ListFolderError('path', LookupError('not_found', None)))
Below is my folder structure in dropbox:
trying with below code to get all of root folder but I am getting only App folder
#Code I am using to get all the folder
dbx = dropbox.Dropbox(access_token)
try:
folder = ''
response = dbx.files_list_folder(folder)
# If no AuthError is raised, it means the scope is working correctly
print("Scope is working correctly.")
print(response)
except dropbox.exceptions.AuthError as e:
print(f"AuthError: {e}")
as output I am receiving only one folder which is Apps folder
Output: entries=[FolderMetadata(id='id:CUbXpRMh8dwAAAAAAAAACg', name='Apps', parent_shared_folder_id=NOT_SET, path_display='/Apps', path_lower='/apps', preview_url=NOT_SET, property_groups=NOT_SET, shared_folder_id=NOT_SET, sharing_info=NOT_SET)], has_more=False)
9 Replies
- Greg-DB3 years ago
Dropbox Community Moderator
I see you're trying to access the contents of a folder in your "team space". By default, API calls operate in the "member folder" of the connected account, not the "team space". You can configure API calls to operate in the "team space" instead though. To do so, you'll need to set the "Dropbox-API-Path-Root" header. You can find information on this in the Team Files Guide. With the Python SDK, you would do so using the with_path_root method.
- rahulj13 years agoExplorer | Level 4
I have tried with this below code snippet still I am getting error
from json import JSONDecodeErrorimport requestsimport dropboxfrom dropbox.exceptions import AuthError, ApiError# Authenticate your appaccess_token = 'My Access Token'dbx = dropbox.DropboxTeam(access_token)def get_user_id(email๐try:# Get the list of team membersmembers = dbx.team_members_list()# Find the user with the specified emailfor member in members.members:if member.profile.email == email:return member.profile.team_member_idexcept AuthError as e:print('Error authenticating with Dropbox API:', e)return Nonedef list_files_in_folder(folder_path๐try:# Set the API endpoint URL# Set the request headersheaders = {'Authorization': f'Bearer {access_token}','Content-Type': 'application/json','Dropbox-API-Select-User': user_id # Replace user_id with the desired user's ID}# Set the request parametersdata = {'path': folder_path,'recursive': True}# Send the requestresponse = requests.post(url, headers=headers, json=data)response_data = response.json()print(response.text)# Process the entries in the folderfor entry in response_data['entries']:print(entry['name']) # Print the name of the file or folderif entry['.tag'] == 'folder':# Recursively list files in subfolderslist_files_in_folder(entry['path_display'])except AuthError as e:print('Error authenticating with Dropbox API:', e)except ApiError as e:print('Error listing folder:', e)except JSONDecodeError as e:print('Error decoding JSON response:', e)# Set the folder pathfolder_path = ' ' # Replace with the actual folder path# Get the user ID for a specific emailuser_email = ' User Name' # Replaced with the desired user's emailuser_id = get_user_id(user_email)# List files in the folder for the specific userlist_files_in_folder(folder_path)Still getting below error{"error_summary": "path/not_found/.", "error": {".tag": "path", "path": {".tag": "not_found"}}}
{"error_summary": "path/not_found/.", "error": {".tag": "path", "path": {".tag": "not_found"}}} - Greg-DB3 years ago
Dropbox Community Moderator
rahulj1 Please review my previous message. In order to access the team space, you'll need to set the "Dropbox-API-Path-Root" header, which can be done in the Python SDK using the with_path_root method. In your latest code, you still don't seem to be using the "Dropbox-API-Path-Root" header or with_path_root method.
Also, in this latest code I see you've implemented some of your own code for performing the HTTP request to /2/files/list_folder, however that is not necessary as it is provided natively by the official Dropbox SDK, via the files_list_folder method, like you had in your original code.
Here's a very basic example of how you might use with_path_root and files_list_folder with the Dropbox Python SDK.
import dropbox dbx = dropbox.Dropbox(ACCESS_TOKEN) root_namespace_id = dbx.users_get_current_account().root_info.root_namespace_id path = "" print(dbx.with_path_root(dropbox.common.PathRoot.root(root_namespace_id)).files_list_folder(path))
(This is assuming a user-linked access token, more like your original code sample.)
- rahulj13 years agoExplorer | Level 4
While I am trying with Root path, I am getting below error
BadInputError('8b261218809945cb828cd56a177f8df2', 'Error in call to API function "users/get_current_account": This API function operates on a single Dropbox account, but the OAuth 2 access token you provided is for an entire Dropbox Business team. Since your API app key has team member file access permissions, you can operate on a team member\'s Dropbox by providing the "Dropbox-API-Select-User" HTTP header or "select_user" URL parameter to specify the exact user <https://www.dropbox.com/developers/documentation/http/teams>.') - DB-Des3 years ago
Dropbox Community Moderator
Hi rahulj1
You are still trying to call a user endpoint using a team token, that's why you are receiving errors.
The following code snippet should help you get the information you are looking for:
import dropbox dbx = dropbox.DropboxTeam("ACCESS_TOKEN").as_user("TEAM_MEMBER_ID") root_namespace_id = dbx.users_get_current_account().root_info.root_namespace_id path = "" print(dbx.with_path_root(dropbox.common.PathRoot.root(root_namespace_id)).files_list_folder(path))
In the above code, you can use the team token you have used previously, and call the .as_user() method with the team_member_id, to retrieve the data.
- rahulj13 years agoExplorer | Level 4
Hi Deb,
Thanks for some how it works with user ID of team member, but I don't know how I can utilize the output to get folder size and file count
ListFolderResult(cursor='AAEy9LSRRFtili8gf8rcZ29hN4PQliBGohGDpBAbKUyJeRJ65mH93FzWh0YFgxfN214N0YM2V7m3lxP_hIQLEepf-Fyqao9Cncw5Hzi-0zCnVhS1-HyQnFVtim3RFt1eWuc9T9DniZ0idfexWLym-8G77lbzL0dVLD0AYg_zkW_cNcFOJ4gEun-DRkNbAcFHBtmjq1IrflOpNKDkrEoGTZXP3eQLgY2AqU1kep_okDhwS1cmNQdMPdT1wG51Et08dqIUtJSt_aXEXC8Ydc77mMdR', entries=[FolderMetadata(id='id:WKNO8Vu_-TsAAAAAAAAAEw', name='Pivotal Brand Team Folder', parent_shared_folder_id='3494645729', path_display='/Pivotal Brand Team Folder', path_lower='/pivotal brand team folder', preview_url=NOT_SET, property_groups=NOT_SET, shared_folder_id='1143758326', sharing_info=FolderSharingInfo(no_access=False, parent_shared_folder_id='3494645729', read_only=False, shared_folder_id='1143758326', traverse_only=False)), FolderMetadata(id='id:WKNO8Vu_-TsAAAAAAAAAJg', name='Rahul Jaiswal', parent_shared_folder_id='3494645729', path_display='/Rahul Jaiswal', path_lower='/rahul jaiswal', preview_url=NOT_SET, property_groups=NOT_SET, shared_folder_id=NOT_SET, sharing_info=FolderSharingInfo(no_access=False, parent_shared_folder_id='3494645729', read_only=False, shared_folder_id=NOT_SET, traverse_only=False))], has_more=False)
- DB-Des3 years ago
Dropbox Community Moderator
files_list_folder
andfiles_list_folder_continue
return the size of files only, not the size of the folder. You could list all of the contents of a folder usingfiles_list_folder
andfiles_list_folder_continue
and then add up the files and file sizes, for all of the files in the folder, to get a file count and size, respectively. - rahulj13 years agoExplorer | Level 4
Hi,
Thanks for your response.
Could you please provide sample code snippet to extract size and count from a team folder?
- Greg-DB3 years ago
Dropbox Community Moderator
rahulj1 You'll need to write and test your own code to suit your particular use case, but it might look something like this:
import dropbox dbx = dropbox.DropboxTeam(ACCESS_TOKEN).as_user(TEAM_MEMBER_ID) root_namespace_id = dbx.users_get_current_account().root_info.root_namespace_id dbx = dbx.with_path_root(dropbox.common.PathRoot.root(root_namespace_id)) total_file_size = 0 total_file_count = 0 def handle_entries(entries): size = 0 count = 0 for entry in entries: if (isinstance(entry, dropbox.files.FileMetadata)): size += entry.size count += 1 return size, count folder_path = "" res = dbx.files_list_folder(path=folder_path, recursive=True) add_file_size, add_file_count = handle_entries(res.entries) total_file_size += add_file_size total_file_count += add_file_count while res.has_more: res = dbx.files_list_folder_continue(cursor=res.cursor) add_file_size, add_file_count = handle_entries(res.entries) total_file_size += add_file_size total_file_count += add_file_count print("total file size: " + str(total_file_size)) print("total file count: " + str(total_file_count))
About Dropbox API Support & Feedback
Find help with the Dropbox API from other developers.6,035 PostsLatest Activity: 7 years ago
The Dropbox Community team is active from Monday to Friday. We try to respond to you as soon as we can, usually within 2 hours.
If you need more help you can view your support options (expected response time for an email or ticket is 24 hours), or contact us on X or Facebook.
For more info on available support options for your Dropbox plan, see this article.
If you found the answer to your question in this Community thread, please 'like' the post to say thanks and to let us know it was useful!