Overview
This article explains how to check whether an S3 object exists using Python.
boto3 provides two API levels: resource and client. I’ll cover both methods.
I used this approach when developing a LINE Bot where I needed to check if a user’s configuration file existed in S3.
resource vs client: Which Should You Use?
boto3 has two API levels:
| API | Characteristics | Best For |
|---|---|---|
resource |
High-level API, object-oriented | Simple operations, readability |
client |
Low-level API, closer to AWS API | Fine-grained control, performance |
Conclusion: For simple existence checks, I recommend using client’s head_object. Here’s why:
head_objectonly retrieves object metadata, making it lightweightresource’sload()internally callshead_objectanywayclientis closer to the AWS API with more predictable behavior
Using boto3.client (Recommended)
|
|
Key Points
head_objectretrieves only metadata without downloading the object content- Non-404 errors (e.g., 403: Access Denied) should be re-raised for proper handling
- Wrapping in a function makes it easier to test
Using boto3.resource
If you prefer an object-oriented approach, this method also works:
|
|
Common Pitfalls
1. Confusing Permission Errors with 404
If you lack permissions to access the S3 bucket, you’ll get a 403 error. Catching only 404 and treating it as “doesn’t exist” will mask permission issues.
|
|
2. Using list_objects is Inefficient
You could use list_objects with prefix search, but it becomes slow with many objects.
For single object existence checks, use head_object.
Summary
- Use
head_objectto check S3 object existence - Handle non-404 errors properly (they may indicate permission issues)
- Both
resourceandclientwork, butclientis simpler