Hi @MBenny
Interesting. Look like a permission issue.
However you seem to have a file object which I assume you got using the client object, under the same security context.
You don’t say however where is it failing in your script, is it the first get or the second?
Cheers
ext_text = requests.get(url,headers)
This is where it get 401
I have all the necessary permissions in the access token. As using the same token in the postman API returns the values.
@rbarbosa
I refactored the code to use make_request from the Client object.
res = get_file_information(client,file.file_id)
if res:
for entry in res['representations']['entries']:
if entry['representation'] == 'extracted_text':
extracted_text_url = entry['info']['url']
break
resp = client.make_request(
method='GET',
url=extracted_text_url,
)
rs = resp.json()
url_template = rs["content"]["url_template"]
updated_url = url_template.replace("{+asset_path}","")
headers = {
"x-rep-hints" : "[extracted_text]",
"Authorization": f'bearer {user.box_access_token}',
'responseType': 'text'
}
ext_text = requests.get(updated_url,headers)
print(ext_text)
When I use the requests.get I still get the 401 error. But if I use the make_request of the Client object then I get the following error
Non-json response received, while expecting json response.
Sorry @MBenny I didn’t explain my self properly.
In your script are you getting the file object under the same security context?
You code looks fine.
In fact you can compare with this article:
And sample code:
Cheers
I have tried the sample code in the github but when I look into the File object in the installed sdk. I couldn’t find the ‘get_representation_info’ function, hence when I run the script I get the following error Error occurred : ‘get_representation_info’
Yes, Everything is under the same secuirty context.
Also I checked with the make_request function it returns a session response, Which is a BoxSession, inside which they expect_json_response=True is set, Hence when the response is of text type they invoke the following error ‘Non-json response received, while expecting json response.’
@rbarbosa I have followed the installation of sdk from the following commands https://developer.box.com/guides/tooling/sdks/python/#installation
Yet, some functions inside objects and authentications are not reflected in the installed sdk module.
Hey - I sent this over to our Python SDK team - they should reply soon! Thanks.
Hi,
@MBenny can you tell, which version of Python SDK do you use? get_representation_info
method was introduced in Box Python SDK v2.1.0. Is it possible that you’re using older version than that? I’ve run your code in the most recent v3.9.2 and it worked without any trouble. Can you confirm that the same issue occurs with the most recent version? Can you share the result of the code below?
import boxsdk
import requests
print(boxsdk.__version__)
print(requests.__version__)
@lsocha , @rbarbosa
print(boxsdk.__version__)
AttributeError: module 'boxsdk' has no attribute '__version__'
This is response
Hi @MBenny,
You can also check the version with the following command:
pip freeze | grep 'boxsdk'
The latest version is 3.9.2, so if yours is different, please upgrade the package with the following command:
pip install boxsdk --upgrade
Then try calling the get_representation_info function again according to the example in the documentation https://github.com/box/box-python-sdk/blob/main/docs/usage/files.md#get-file-representations
Hope this help!
@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.
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.
@MBenny, could you let us know which version of the box-python-sdk you are using?
Additionally, is the error you’re encountering a runtime error? Could you show it to us?
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
- 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))
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}")
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)
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!
{
“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