Skip to main content
Known Participant
Nov 6, 2023 4:34 PM UTC

File Representation url returns 401

url=f'https://api.box.com/2.0/files/{file.file_id}?fields=representations'
                headers = {
                    "x-rep-hints" : "[extracted_text]",
                    "Authorization": f'Bearer {user.box_access_token}'
                }
                ext_text = requests.get(url,headers)
                print(ext_text.status_code)
                url_template = str(ext_text["representations"]["entries"][0]["content"]["url_template"])
                url = url_template.replace("{+asset_path}", "")
                resp = requests.get(url, headers={"Authorization": f"Bearer {user.box_access_token}"})
                resp.raise_for_status()
                print( resp.content)

The same call made through postman return success.

    17 replies

    MBennyAuthor
    Known Participant
    Nov 22, 2023 4:07 AM UTC

    @lsocha @ajankowski

    Thank you for the help. I have upraged my boxsdk to the latest version with that now I’m able to call the file representation API.

    But when calling the file collaborations using the box api doc as reference I get an error that get_collaborations is not defined for file.

    collaborations = client.file(file_id).get_collaborations()
    

    I checked the latest sdk file object and cound’t file get_collaborations() function. But the same is avaiable for group object in the sdk.

    Translate
    Box Employee
    Nov 22, 2023 12:23 PM UTC

    Hi @MBenny ,

    The File class inherits from the Item class, and that’s where the get_collaborations method is located.

    The code from the example :
    collaborations = client.file(file_id).get_collaborations()
    works fine on my local computer.

    1. @MBenny, could you let us know which version of the box-python-sdk you are using?

    2. Additionally, is the error you’re encountering a runtime error? Could you show it to us?

    3. Could you also prepare and send us the code that you are trying to run on your end?
      This will help us in further investigating the cause of the error.

    Regards,
    Artur

    Translate
    MBennyAuthor
    Known Participant
    Nov 22, 2023 1:24 PM UTC
    1. boxsdk==3.9.2


    3.

     def get_file_access(client, file_id):
        try:
            file_info = client.file(file_id).get_collaborations()
            Logging.log_info(f"Collaboration information fetched for file {file_id}")
            return file_info
        except BoxAPIException as error:
            Logging.log_errors('Error occurred : {}'.format(error.text))
    
    Translate
    Box Employee
    Nov 23, 2023 9:20 AM UTC

    Hi @MBenny,

    Your code doesn’t cause any errors for me. However, in your example, you catch the BoxAPIException, which is thrown by the SDK. But in this this Exception will not occur. This is because the get_collaborations() method doesn’t make a call, instead it returns an iterator that handles it.

    Could you invoke this method I prepared for you and let us know what you received?

    import boxsdk
    import requests
    
    def get_file_access(client, file_id):
        try:
            # Print boxsdk version and request version
            print(boxsdk.__version__)
            print(requests.__version__)
    
            file_info = client.file(file_id)
    
            # Print all attributes of file (ensure that get_collaborations is here)
            for attr in dir(file_info):
                print(attr)
    
            collaborations = client.file(file_id).get_collaborations()
    
            # Iterate through the collaborations by invoking the API call
            for collab in collaborations:
                target = collab.accessible_by
                print(f'{target.type.capitalize()} {target.name} is collaborated on the file')
    
            return file_info
        except Exception as error:
            print(f"Geneeric error occurred : {error}")
    
    
    Translate
    MBennyAuthor
    Known Participant
    Nov 23, 2023 1:32 PM UTC
    3.9.2
    2.31.0
    __annotations__
    __class__
    __contains__
    __delattr__
    __dict__
    __dir__
    __doc__
    __eq__
    __format__
    __ge__
    __getattribute__
    __getitem__
    __gt__
    __hash__
    __init__
    __init_subclass__
    __iter__
    __le__
    __lt__
    __module__
    __ne__
    __new__
    __reduce__
    __reduce_ex__
    __repr__
    __setattr__
    __sizeof__
    __str__
    __subclasshook__
    __weakref__
    _classification_template_key
    _construct_range_header
    _description
    _get_accelerator_upload_url
    _get_accelerator_upload_url_for_update
    _item_type
    _object_id
    _preflight_check
    _response_object
    _session
    _untranslate
    _untranslated_fields
    add_classification
    add_comment
    add_to_collection
    apply_watermark
    as_user
    clone
    collaborate
    collaborate_with_login
    content
    copy
    create_shared_link
    create_task
    create_upload_session
    delete
    delete_version
    delete_watermark
    download_to
    get
    get_all_metadata
    get_chunked_uploader
    get_classification
    get_collaborations
    get_comments
    get_download_url
    get_embed_url
    get_previous_versions
    get_representation_info
    get_shared_link
    get_shared_link_download_url
    get_tasks
    get_thumbnail
    get_thumbnail_representation
    get_type_url
    get_url
    get_watermark
    lock
    metadata
    move
    object_id
    object_type
    preflight_check
    promote_version
    remove_classification
    remove_from_collection
    remove_shared_link
    rename
    response_object
    session
    set_classification
    set_disposition_at
    translator
    unlock
    untranslated_fields
    update_classification
    update_contents
    update_contents_with_stream
    update_info
    validate_item_id
    with_shared_link
    Geneeric error occurred : Message: Not Found
    Status: 404
    Code: not_found
    Request ID: w3czn7hk5ckrm66r
    Headers: {'Date': 'Thu, 23 Nov 2023 13:14:17 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'x-envoy-upstream-service-time': '167', 'box-request-id': '1658eb2694b11157d20df9b0bd1e4ca', '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'}
    URL: https://api.box.com/2.0/files/1370017561274/collaborations
    Method: GET
    Context Info: {'errors': [{'reason': 'invalid_parameter', 'name': 'item', 'message': "Invalid value 'f_1370017561274'. 'item' with value 'f_1370017561274' not found"}]}
    

    I have created the client using the CCG method.

    from boxsdk.auth.ccg_auth import CCGAuth
    oauth = CCGAuth(
                    client_id='ruv56hnyr0beqk16eme1ovrbct6g9or2',
                    client_secret=REDACTED,
                    enterprise_id=REDACTED)
                    
    client = BoxClient(oauth)
    file_id='1370017561274'
    get_file_access(client, file_id)
    
    Translate
    Box Employee
    Nov 23, 2023 2:10 PM UTC

    Thanks for the reply @MBenny !

    In your logs we can see that the get_collaborations() method works and that API call was made correctly.

    However, you received a 404, and that’s because the client couldn’t find the file.
    This is happening because the client you created is of type Service Account and it doesn’t have access to user files.

    More about it here and here.

    To make the code works, create a client using a user account:

    auth = CCGAuth(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    user="YOUR_USER_ID"
    )

    More about it here.

    Hope this help!

    Translate
    MBennyAuthor
    Known Participant
    Dec 11, 2023 12:17 PM UTC

    {
    “type”: “error”,
    “status”: 404,
    “code”: “not_found”,
    “help_url”: “http://developers.box.com/docs/#errors”,
    “message”: “{"code":"2504"}”,
    “request_id”: “vo75hyhkq3zu2ar8”
    }

    please check if text representation is created for this excel file or not. As it returns this error when calling the API.

    @lsocha @rbarbosa @ajankowski

    Translate