Skip to main content

If I have an id but I don’t know is it a file or folder id, what is the easiest way to find it out?


In another words, how to get type (file or folder) by object id?

Hi 👋



Thanks for posting in the forum.



I’m not sure it is possible to make a request in that way, since our endpoints are silo’d by object type. I’m curious, how do you get the object id without the type too?



You might be able to use the search endpoint… but I’m not sure that it will work perfectly or in a scalable way.



Alex, Box Developer Advocate 🥑


Hi Alex,


here is the thing.


I have a box cli shell script that I can use to list directory structure and show all files and folders in it with their ids.


When I find id if I would like to delete it I am executing mybox delete --item-id <file_or_folder_id> which does something like this:



   try:

item = box.folder_by_id(folder_id=item_id)

except BoxAPIException:

try:

item = box.file_by_id(file_id=item_id)

except BoxAPIException:

print(f"{item_id=} is neither file nor folder")



For given id, I would like to know upfront is it a file or folder so I can call folder_by_id() or file_by_id() which will provide to me item object on which I can use item.delete() to delete the id.



Regards,



Zoran


Hi,



If you have a python script and getting the item, the item object includes its type, so does the file and folder object.



Here is a sample script:



BASE_FOLDER_ID = "0"  # 0 is the root folder



def get_folder_by_id(client, folder_id) -> Folder:

"""Get the details of a folder"""

folder = client.folder(folder_id).get()

return folder



def get_file_by_id(client, file_id) -> File:

"""Get the details of a file"""

file = client.file(file_id).get()

return file



def main():

"""

Simple script to demonstrate how to use the Box SDK

with oAuth2 authentication

"""

client = get_client(conf)

base_folder = get_folder_by_id(client, BASE_FOLDER_ID)



base_folder_items = base_folder.get_items()

print(f"List of items in {base_folder.name}:")

for item in base_folder_items:

print(f"[{item.type}] {item.name}")

if item.type == "folder":

folder = get_folder_by_id(client, item.id)

elif item.type == "file":

file = get_file_by_id(client, item.id)



if folder:

print(f"A Folder also has a type: {folder.name} is a {folder.type}")



if file:

print(f"A File also has a type: {file.name} is a {file.type}")





if __name__ == "__main__":

main()



Let us know if this helps.



Cheers


@rbarbosa you are perfectly right if we are not considering that I am talking about bash shell script.



After I execute mybox tree --folder-id (folder_id is 0 by default) I will get directory tree with ids.


Please notice that now I am in shell again and I don’t have access to File or Folder object(s).



The only thing I have is output of the previous command.


So, using id I have to get File or Folder object to process it further.



Procedure with nested try’s I have showed above works, but I think it is ugly.



Furthermore, how can I get rid of the error message produced by api:



"GET https://api.box.com/2.0/folders/3452345234" 404 316

{'Date': 'Fri, 18 Aug 2023 05:02:58 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'x-envoy-upstream-service-time': '217', 'box-request-id': '07fe8727d7ba3ce1cc6bc415b0b9e9801', 'cache-control': 'no-cache, no-store', 'strict-transport-security': 'max-age=31536000', 'Via': '1.1 google', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}

{'code': '---ound',

'context_info': {'errors': s{'message': "Invalid value 'd_3452345234'. 'item' "

"with value 'd_3452345234' not found",

'name': 'item',

'reason': 'invalid_parameter'}]},

'help_url': 'http://developers.box.com/docs/#errors',

'message': 'Not Found',

'request_id': 'dzbe1bhh0t9nmcju',

'status': 404,

'type': 'error'}



I produced this error intentionally by providing a fake id to my delete function.


The message in my last except block is enough for explaining to the user what is going on.



Regards,



Zoran


Hi @zljmob



The nested try would work, and I don’t see a way around it.



If you want to reduce the level of the Box API logging the you can do something like:



import logging

logging.basicConfig(level=logging.INFO)

logging.getLogger("boxsdk").setLevel(logging.CRITICAL)



Beware that you might get other errors than the 404 not found, for example a 403 if the token expired, and also the 404 might mean that the file is not accessible to the specific user.



The following example implements the nested try per your example, and adds a conversion from folder to item and file to item.



Item is the type of “generic” object you get from a folder.get_items(), and supports files, folders and web links.



"""main.py"""



import logging



from boxsdk import BoxAPIException

from app.config import AppConfig



from app.box_client import get_client_jwt

from boxsdk.object.item import Item

from boxsdk.object.folder import Folder

from boxsdk.object.file import File



logging.basicConfig(level=logging.INFO)

logging.getLogger("boxsdk").setLevel(logging.CRITICAL)



conf = AppConfig()





def folder_to_item(folder: Folder) -> Item:

"""

Converts a BoxSDK Folder object to a BoxSDK Item object

"""

return Item(session=folder._session, object_id=folder.object_id, response_object=folder.response_object)





def file_to_item(file: File) -> Item:

"""

Converts a BoxSDK Folder object to a BoxSDK Item object

"""

return Item(session=file._session, object_id=file.object_id, response_object=file.response_object)





def get_box_object_by_id(client, id) -> Item:

"""

Get a Box object by ID

"""

try:

folder = client.folder(id).get()

return folder_to_item(folder)

except BoxAPIException as box_api_exception:

if box_api_exception.status != 404:

# logging.error(box_api_exception)

raise box_api_exception

try:

file = client.file(id).get()

return file_to_item(file)

except BoxAPIException as box_api_exception:

# logging.error(box_api_exception)

raise box_api_exception





def main():

"""

Simple script to demonstrate how to use the Box SDK

with oAuth2 authentication

"""



client = get_client_jwt(conf)



# who am i?

me = client.user(user_id="me").get()

print(f"Hello {me.name}")



print("=== FOLDER LIST ===")

items = client.folder("0").get_items()

for item in items:

print(f"Type: {item.type} ID: {item.id} Name: {item.name}")

if item.type == "folder":

folder_id = item.id

if item.type == "file":

file_id = item.id

print("==================")



if file_id:

item = get_box_object_by_id(client, file_id)

print(f"Item: {item.name} is a {item.type}")



if folder_id:

item = get_box_object_by_id(client, folder_id)

print(f"Item: {item.name} is a {item.type}")



# Object exists but it is not available to this user

object_id = "1175214645880"

item = get_box_object_by_id(client, object_id)

print(f"Item: {item.name} is a {item.type}")



# Object does not exists

object_id = "1234"

item = get_box_object_by_id(client, object_id)

print(f"Item: {item.name} is a {item.type}")





if __name__ == "__main__":

main()





Cheers


Reply