97

I am trying to understand when I should use a Resource and when I should use a Client.

The definitions provided in boto3 docs don't really make it clear when it is preferable to use one or the other.

aquil.abdullah
  • 2,909
  • 2
  • 20
  • 37

1 Answers1

102

boto3.resource is a high-level services class wrap around boto3.client.

It is meant to attach connected resources under where you can later use other resources without specifying the original resource-id.

import boto3
s3 = boto3.resource("s3")
bucket = s3.Bucket('mybucket')

# now bucket is "attached" the S3 bucket name "mybucket"
print(bucket)
# s3.Bucket(name='mybucket')

print(dir(bucket))
#show you all class method action you may perform

OTH, boto3.client are low level, you don't have an "entry-class object", thus you must explicitly specify the exact resources it connects to for every action you perform.

It depends on individual needs. However, boto3.resource doesn't wrap all the boto3.client functionality, so sometime you need to call boto3.client , or use boto3.resource.meta.client to get the job done.

taras
  • 5,922
  • 10
  • 36
  • 48
mootmoot
  • 11,805
  • 5
  • 45
  • 44
  • 2
    Thanks, this helps a little, the documentation itself is a bit vague, but I guess the key is that clients map to specific API calls that you can make. – aquil.abdullah Sep 02 '16 at 13:05
  • 1
    Im initializing my client by passing credentials as parameters to the client. import boto3 client = boto3.client( 's3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY ). Can i do something similar for resource? im not able to find this in the documentation. – Naveen Jan 04 '18 at 22:52
  • @Naveen It is not recommend to pass hard coded API key. If you insist, you may use boto3.session and instantiate your resource from the session. There is plenty of example around. – mootmoot Jan 05 '18 at 08:29
  • 8
    The example didn't show anything that shows the difference. – Nabin Feb 11 '18 at 01:45
  • 4
    Anyone need comprehensive example, please take a look here : https://stackoverflow.com/questions/42809096/difference-in-boto3-between-resource-client-and-session/42818143#42818143 – mootmoot May 07 '18 at 06:56
  • 1
    Does anyone have good suggestions on the documentation over the "resource" interfaces? The BOTO3 docs focus mainly on the low-level "client" interfaces. – gye May 11 '20 at 20:30
  • 1
    How 'expensive' is to create a resource object? Is it OK for each function that needs it to create one (for example, `dynamodb = boto3.resource("dynamodb")`), or is it a better practice to pass `dynamodb` as a parameter? – Lovro Nov 25 '20 at 22:04