DEV Community

Karthik Subramanian for AWS Community Builders

Posted on • Edited on • Originally published at Medium

Downloading a file from S3 using API Gateway & AWS Lambda

Downloading a file from S3 using API Gateway & AWS Lambda

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 -

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 -

env.json

Build and start the api locally -

sam build
sam local start-api --env-vars ./tests/env.json
Enter fullscreen mode Exit fullscreen mode

You should see an output like -

Console output

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 -

postman

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"]
Enter fullscreen mode Exit fullscreen mode

Deploy the code to aws -

sam build
sam deploy
Enter fullscreen mode Exit fullscreen mode

The output should look like this -

console output

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

postman

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

Top comments (0)