I'm addicted to the specifications, so I'll leave a note.
It is assumed that S3 has already been created.
Create Lambda with a suitable name. Here, it is get_image
.
I also chose Python 3.8 as the runtime.
Then, register the following code in the function code.
import boto3
import base64
def get_img_from_s3():
s3 = boto3.client('s3')
bucket_name = 'BUCKET_NAME'
file_path = 'FILE_PATH'
responce = s3.get_object(Bucket=bucket_name, Key=file_path)
body = responce['Body'].read()
body = base64.b64encode(body)
return body
def lambda_handler(event, context):
img = get_img_from_s3()
return img
Pass the name of the S3 bucket to bucket_name
and the path of the S3 object (image) you want to read to file_name
, and read the object from S3.
After that, the read binary format object is encoded in base64 and returned.
The created Lambda does not have the access authority to S3, and if it is left as it is, the access will be denied, so give the access authority to S3.
First, open the Lambda access permission page you created.
Since the automatically created execution role is assigned here, open the page for this execution role.
Press the blue Attach Policy
button in the center of the page.
In this way, various policies come out.
Searching for S3
will bring up the policy for S3.
This time, the image is read from S3, so attach the policy ʻAmazonS3ReadOnlyAccess`.
Now you can read the files stored in S3 from Lambda.
This completes the Lambda settings.
Next, create API Gateway.
REST API was selected as the API type, and the API name was appropriately set to get_image
.
Next, I added a GET method and specified Lambda as the integration type and the Lambda function called get_image
created earlier as the Lambda function.
Now that the API Gateway has been created, set the method response.
First, Content-Type
was added to the response header, and ʻimage / png was added to the content type of the response body. (Since I read png this time, I chose ʻimage / png
.)
Next, set the integrated response.
By default, the content processing method is pass-through, but select Convert to binary (if necessary)
.
Also, let the mapping value of the header mapping be '*'
.
This completes the API Gateway settings.
Finally, when you test the API I was able to return the png binary like this!
When you actually deploy the API and access the URL, the image will be displayed.
Implementation by Node.js Introduction to Lambda + API Gateway. Image DL
Recommended Posts