In this post, I will show you a tutorial on how you can easily combine these two services to build various applications.
I’ll present to you an initial project I built—very simple—just to explore the AWS console, understand the services, and see how we can use them together to build APIs easily.
The project is a serverless API using AWS Lambda and API Gateway, capable of receiving HTTP requests and processing different types of tasks based on JSON payloads.
At the end, I will answer the following question: What are the advantages of building serverless applications using AWS Lambda and API Gateway?
We will divide the process into phases, and each phase may have subphases:
Phase 1 – Create the Lambda function
Phase 2 – Test the function
Phase 3 – Create the API Gateway and connect it to Lambda
Phase 4 – Test the integration
Phase 1 – Create the Lambda Function
To start this phase, we define a permission policy.
1.1 Permission Policy:
This policy will grant your function permission to access the necessary AWS resources. In my project, since it is very basic, I used a default policy provided by AWS: AWSLambdaBasicExecutionRole. It grants the minimum essential permissions for a Lambda function to run and write logs to Amazon CloudWatch Logs.
1.2 Execution Role:
Here, you will create an execution role. In this role, you attach the permission policy created earlier and specify the service to which you want to grant these permissions.
This is where you associate the policy with the service.
1.3 Finally, Create the Lambda Function:
import json
def lambda_handler(event, context):
body = json.loads(event.get("body", "{}"))
tarefa = body.get("tarefa", "none")
mensagem = body.get("mensagem", "")
if tarefa == "log":
resposta = f"Log received: {mensagem}"
elif tarefa == "processar":
resposta = "Processing data..."
else:
resposta = "Task not recognized"
return {
"statusCode": 200,
"body": resposta
}
My function acts as a simple “router” that decides what to do based on the data it receives (the event parameter).
Data extraction: It looks inside the event (a Python dictionary) for the keys "tarefa" and "mensagem". If not found, it uses "none" and an empty string as default values.
Decision logic:
If the task is "log", it returns a confirmation message.
If it is "processar", it returns a fixed processing message.
Otherwise, it informs that the task was not recognized.
Standard response: It always returns a dictionary with statusCode: 200 (HTTP success) and the response text in the body.
In summary: it is a mini task router that responds differently depending on the command sent in the input JSON.
Phase 2 – Test the Function
Create a new test and send a JSON in the expected format. In my case:
{
"tarefa": "log",
"mensagem": "Final test"
}
Note: The function looks for "tarefa" and "mensagem" inside the event. If not found, it uses default values.
Phase 3 – Create the API Gateway
Here, we will create a public URL that acts as the trigger for our Lambda function.
3.1 Create API
When creating an API in API Gateway, you will see options such as:
REST API
WebSocket API
HTTP API
REST API Private
I built an HTTP API, which is a more modern, faster, and cheaper option compared to REST API.
3.2 Configure API
After choosing, define the name and integrations. I added my Lambda function.
3.3 Configure Routes
Routes consist of an HTTP method and a resource path (e.g., GET /pets). You can define methods like GET, POST, PUT, PATCH, HEAD, OPTIONS, and DELETE.
3.4 Define Stages
Stages are environments where your API is deployed. You must deploy to a stage for changes to take effect, unless auto-deploy is enabled. By default, HTTP APIs have a $default stage with automatic deployment.
Summary of Phase 3:
Create the API
Configure it
Configure routes
Define the stage
Click “Create”
Phase 4 – Testing the Integration between API Gateway and Lambda
Now, what you need to do is send requests to the created routes and check if the response is as expected. Remember, the requests are the trigger of the Lambda function, so when you send a request, it should invoke the function and return the result to us.
For this test, we can use curl and/or Postman. I tested with both—it’s the best way to make sure everything is working correctly.
Note:
Curl:
URL of your API
-H (header)
-d (body)
My example:
curl -X POST https://k07qfvf9ye.execute-api.sa-east-1.amazonaws.com/dev/executar-tarefas \
-H "Content-Type: application/json" \
-d "{\"tarefa\":\"log\",\"mensagem\":\"Final test\"}"
Expected result:
Log received: Final test
If it returns the expected result, congratulations—you have successfully completed your application.
Answering the initial question:
What is the advantage of building serverless applications with AWS Lambda and API Gateway?
The term “serverless” means that your code runs on servers, but you do not need to provision or manage these servers. With serverless computing, you can focus more on building and innovating new products and features instead of maintaining servers.
Another benefit of serverless computing is the ability to automatically scale applications. It adjusts the application’s capacity by modifying units of consumption, such as throughput and memory.
Let’s make the real advantages of serverless computing with AWS Lambda and API Gateway very clear:
1. Real Cost Savings (Pay-as-you-go)
Zero Cost When Idle: Unlike a server running 24/7, you only pay when someone uses your API. If no one uses it, you pay nothing.
Granular Billing: AWS Lambda charges per millisecond of execution and based on the amount of memory used.
Low-cost API Gateway: Amazon API Gateway offers competitive pricing, charging only for the number of requests received.
2. Infinite and Automatic Scalability
No Management: You don’t need to configure Auto Scaling Groups or Load Balancers manually.
Traffic Spikes: If your application goes viral, AWS instantly provisions thousands of Lambda executions to handle the demand and then scales everything back down automatically.
3. Reduced Complexity (Focus on Code)
Zero Maintenance: No need to worry about OS updates, kernel patches, or hardware issues.
Built-in Security: API Gateway handles complex tasks like DDoS protection, authentication (e.g., Cognito), access control, and SSL/TLS encryption natively.
4. Development Agility
Fast Deployment: You can deploy a new version of your business logic in seconds by simply uploading your code.
Modular Architecture: It makes it easier to build microservices, where each Lambda function solves a small, isolated problem, making the system easier to maintain.
And as shown above, AWS Lambda and API Gateway are easy to use, so you can quickly deploy your code. In summary, what we did was basically:
1 - Upload the code to Lambda and test it (Phase 1 and 2)
2 - Configure a trigger, meaning an event that will start the execution of your Lambda function (Phase 3), and test the integration of the services (Phase 4)
3 - The code runs only when the trigger is detected
4 - Pay only for the compute time you use
Finally, I swear I won't say anything more after this, I'll leave you with some examples of real-world uses of lambda to help you understand in which situations it's welcome and how it makes our lives easier.
Real-time image processing for a social media application
A social media company uses Lambda to process images uploaded by users. When a photo is uploaded, Lambda is triggered to resize the image, apply filters, and save it in an optimized format to storage. This event-driven, serverless approach makes sure that the application can handle high volumes of uploads without needing to manage infrastructure.
Why Lambda: It automatically scales based on uploads and charges only for the time spent processing each image.
Personalized content delivery for a news aggregator
A news aggregator uses Lambda to fetch and process news articles from multiple sources, then it tailors recommendations based on user preferences. When a user opens the application or performs a search, Lambda functions are triggered to retrieve data, run personalization logic, and return relevant content.
Why Lambda: It automatically scales with user traffic and reduces costs by running code only when users interact.
Real-time event handling for an online game
A gaming company uses Lambda to handle in-game events like player actions, game state changes, and real-time leader board updates. Each event (like scoring a point or unlocking an achievement) triggers a Lambda function that updates player data and game status.
Why Lambda: It handles thousands of events, in real-time, with no need to manage servers. Costs scale with usage, which is ideal for peak gaming times.
Thank you for your attention, and I hope I was able to help!
Top comments (0)