Nono.MA

[Solved] S3: Error occurred (404) when calling the HeadObject operation: Not Found

MARCH 28, 2022

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Define your object's bucket and key
s3_bucket = 'bucket-name'
s3_key = 'file/key.txt'

# Read an object's HEAD
s3_object_head = s3.head_object(
    Bucket=s3_bucket,
    Key=s3_key,
)

# Get the object's size
s3_object_size = s3_object_head['ContentLength']
print(f'Size is {s3_object_size} bytes.')

This code will throw an error if the object at key s3_key doesn't exist in bucket s3_bucket.

An error occurred (404) when calling the HeadObject operation: Not Found

Here's how to catch and handle that error.

import boto3
import botocore.exceptions

# Create an S3 client
s3 = boto3.client('s3')

# Define your object's bucket and key
s3_bucket = 'bucket-name'
s3_key = 'file/key.txt'

try:
  # Read the object's HEAD
  s3_object_head = s3.head_object(
      Bucket=s3_bucket,
      Key=s3_key,
  )

  # Get the object's size
  s3_object_size = s3_object_head['ContentLength']
  print(f'Size is {s3_object_size} bytes.')
except botocore.exceptions.ClientError as error:
  # Handle s3.head_object error
  if error.response['Error']['Code'] == '404':
    print(f'S3 object not found at s3://{s3_bucket}/{s3_key}.')
  else:
    print(error)

BlogError