Building a REST API with AWS API Gateway and AWS Lambda in Python (AWS tutorial)
In this little tutorial you will learn how to build out this infrastructure on AWS.
Specifically we will:
- Create an AWS API gateway service that can forward and return our requests and responses
- Create a Serverless AWS Lambda that will process our request and send a response back
- Test our API manually with Postman
Let’s get started!
Step 1: Creating the API Gateway
Let’s create an API gateway
Now click on rest API
And give it a name
Now click on Create Resource
and create a new resource. I call mine tmp-resource
This is what it should look like now
Step 2: Creating the Lambda
Let’s create a new Lambda
Make sure to set the runtime to Python. Give it a nice name. I call mine tmp-lambda-jan
Great job! You now have a lambda running!
Paste this code in the body of the lambda (taken from here)
import json
# Example data
data = {
"items": [
{"id": 1, "name": "Item 1", "price": 10.99},
{"id": 2, "name": "Item 2", "price": 15.99},
{"id": 3, "name": "Item 3", "price": 20.99},
]
}
def lambda_handler(event, context):
# Determine the HTTP method of the request
http_method = event["httpMethod"]
# Handle GET request
if http_method == "GET":
# Return the data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
# Handle POST request
elif http_method == "POST":
# Retrieve the request's body and parse it as JSON
body = json.loads(event["body"])
# Add the received data to the example data
data["items"].append(body)
# Return the updated data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
# Handle PUT request
elif http_method == "PUT":
# Retrieve the request's body and parse it as JSON
body = json.loads(event["body"])
# Update the example data with the received data
for item in data["items"]:
if item["id"] == body["id"]:
item.update(body)
break
# Return the updated data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
# Handle DELETE request
elif http_method == "DELETE":
# Retrieve the request's body and parse it as JSON
body = json.loads(event["body"])
# Find the item with the specified id in the example data
for i, item in enumerate(data["items"]):
if item["id"] == body["id"]:
# Remove the item from the example data
del data["items"][i]
break
# Return the updated data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
else:
# Return an error message for unsupported methods
response = {
"statusCode": 405,
"body": json.dumps({"error": "Method not allowed"})
}
return response
And make sure to click on Deploy
Now you have updated the code in the lambda and re-deployed it! Good job!
Now all that is left is that we must hook the lambda into our API because as it stands right now the API is a bit empty.
Step 3: Adding the lambda and testing
Going back to our API we can now create a method
Use Method Type
ANY and set the lambda to the name that you just created.
This is what you should see right now.
There’s one important setting that you must change and that is the Lambda proxy integration must be set to true
What this setting does is that it allows your API gateway to actually forward the requests it gets. If you don’t set this to true then the Lambda won’t get the event that we need. Now you can deploy the API!
Create a new stage. Dev is fine.
Step 4: Testing
Now copy the Invoke URL
And use it to test it on postman.
If you for example, try to hit this URL
And you get
```json
{
"message": "Missing Authentication Token"
}
Make sure to use the right resource, which in my case is tmp-resource
and not my-resource
Try again… and boom!
Step 5: Cleanup
Remove the API
Remove the Lambda
Wrapping up
In this tiny tutorial we implemented a small system on the cloud that combines the AWS API Gateway and a Serverless AWS Lambda. I hope you had as much fun as I did making this tutorial. While the system itself is simple and straightforward, I urge and encourage you to try and experiment with different setups, because this is the first stepping stone to building systems on the cloud that scale.
Comments