Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when boto3 client.put_object() is unsuccessful?

The boto3 documentation for client.put_object() does not say anything about error handling. My question is when that function is unsuccessful does it always raise an exception or does it sometimes return a False or None value?

like image 596
Hortplus-Millar Avatar asked Sep 15 '25 00:09

Hortplus-Millar


1 Answers

The short answer is : Yes, it' ll throw an error class botocore.exceptions.ClientError when the api call is failed due to any issues.

The boto3 s3 API call put_object will return a dict object as the response if it is successful else nothing will be returned.

>>> import boto3

>>>
>>> s3_client = boto3.client('s3')
>>>
>>> s3_response = s3_client.put_object(Bucket='mybucket', Key='/tmp/new-pb.yml')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/botocore/client.py", line 312, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/lib/python2.7/site-packages/botocore/client.py", line 601, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
>>>
>>> print s3_response
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 's3_response' is not defined
>>>

Try calling the API call inside a try-except block captures ClientError when the method is failed so that it could be safely handled to avoid the unexpected behavior of script if edge cases or not covered.

Hope this will be helpful for you.

like image 188
S.K. Venkat Avatar answered Sep 17 '25 13:09

S.K. Venkat