amazon-web-servicesboto3

When to use a boto3 client and when to use a boto3 resource?


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.


Solution

  • 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.