Downloading a file from S3 using API Gateway & AWS Lambda

Karthik Subramanian
3 min readAug 30, 2022

--

In my last post I showed how we can create and store a csv file in an S3 bucket. Let us now see how we can get the status of a request & get a downloadable link to the csv for completed requests.

The Get Status lambda

Under the src directory, create a new file called “get_status.py” with the below code -

Add the new file to Dockerfile -

Update the template.yaml file and add a new resource -

Testing locally

We can test the endpoint locally, but before that we need to update the env.json and include the S3 bucket name -

Build and start the api locally -

sam build
sam local start-api --env-vars ./tests/env.json

You should see an output like -

Trigger a new request & grab the request id from the DB (since the post will fail without an SQS queue defined). Then test the get status call -

Deploying the code

Just like before, we need to specify an image repository for the new lambda function. Update the samconfig.toml file and add another item to the image_repositories list for GetStatusFunction -

image_repositories = ["CreateFunction=541434768954.dkr.ecr.us-east-2.amazonaws.com/serverlessarchexample8b9687a4/createfunction286a02c8repo",
"ProcessFunction=541434768954.dkr.ecr.us-east-2.amazonaws.com/serverlessarchexample8b9687a4/createfunction286a02c8repo",
"GetStatusFunction=541434768954.dkr.ecr.us-east-2.amazonaws.com/serverlessarchexample8b9687a4/createfunction286a02c8repo"]

Deploy the code to aws -

sam build
sam deploy

The output should look like this -

Grab the get-status endpoint url and try making a request through postman for one of the completed orders from before -

Cmd+Click on the download_link to download the csv file from S3.

And thats it! The SAM CLI has enabled us to leverage infrastructure-as-code to deploy our entire architecture to any aws account within minutes!

Source Code

Here is the source code for the project created here.

Next: Part 7: AWS Lambda & ECR nuances

--

--