DEV Community

Karthik Subramanian for AWS Community Builders

Posted on • Updated on • Originally published at Medium

Building a REST API with AWS API Gateway & Lambda

In my last post I covered the overall architecture we are building and how to get setup with SAM CLI locally & deploy the app to AWS.

Setting up a virtual environment

Since we will be using python to build our app, lets create a virtual environment where we can install all our dependencies.

Create a new virtual environment
python -m venv venv

Activate the environment
source venv/bin/activate

Install the dependencies
pip install -r src/requirements.txt

Customize the application

Rename the folder “hello_world” to “src”

Rename app.py to create.py

In the Dockerfile, update the reference to app.py and remove the CMD statement. The Dockerfile should look like this -

FROM public.ecr.aws/lambda/python:3.9
COPY create.py ${LAMBDA_TASK_ROOT}
COPY requirements.txt ${LAMBDA_TASK_ROOT}
RUN python3.9 -m pip install -r requirements.txt -t .
Enter fullscreen mode Exit fullscreen mode

Update the contents of template.yml to the following -

We now update create.py to accept a POST request and return a request ID for tracking.

Build & test the app

Build the app with the following command -
sam build

Test the app locally, run the following command to expose the endpoint -
sam local start-api

You should see the following output -

Local Start API output

We can now test the endpoint by making a POST request using POSTMAN with the request body -

{
   "url": "https://www.google.com/search?q=random+search"
}
Enter fullscreen mode Exit fullscreen mode

The response back should contain the url and a request_id -

Postman response

Deploy the app

Deploy the app to AWS using the following command -
sam deploy --guided

If you followed the steps from my previous post, you should already have a samconfig.toml file generated. Delete that file before running the above command so that we can setup our deploy config from scratch.

Choose the following options in the interactive session -

SAM Deploy Options

If the deployment succeeded, you should see the following output -

SAM Deploy Success

This will create the samconfig.toml file again with the configs stored. For subsequent deployments you can simply run sam deploy to deploy the app.

Testing the deployed app

Use the API URL from the output and test the POST call from postman.

Postman Test

Note: The url should be copied from the output as-is. The url is case-sensitive and any trailing spaces can also result in a 403 response.

Source Code

Here is the source code for the project created here.

Next: Part 3: Storing AWS SQS messages to DynamoDB with AWS Lambda

Top comments (0)