Skip to main content
CloudIntermediate16 min readUpdated March 2025

Building APIs with Lambda & API Gateway

Create a serverless REST API with AWS Lambda and API Gateway in both Python and JavaScript, with no servers to patch or scale.

How the Pieces Fit

API Gateway receives the HTTP request, handles routing, throttling and authorization, then invokes a Lambda function. The function runs your code, returns a response, and you are billed only for the milliseconds it ran.

A Python Lambda Handler

The handler receives an event describing the request and returns a status code, headers and body:

python
import json

def lambda_handler(event, context):
    params = event.get("queryStringParameters") or {}
    name = params.get("name", "world")

    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({"message": f"Hello, {name}!"}),
    }

The Same Handler in Node.js

Lambda supports many runtimes. Here is the equivalent in JavaScript using async/await:

javascript
export const handler = async (event) => {
  const name = event.queryStringParameters?.name ?? "world";

  return {
    statusCode: 200,
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ message: `Hello, ${name}!` }),
  };
};

Defining Infrastructure with SAM

The AWS Serverless Application Model (SAM) describes the function and its HTTP route in a short template:

yaml
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Resources:
  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.lambda_handler
      Runtime: python3.12
      MemorySize: 256
      Timeout: 10
      Events:
        HelloApi:
          Type: Api
          Properties:
            Path: /hello
            Method: get

Production Tips

Keep serverless APIs fast and reliable:

  • Keep deployment packages small to reduce cold-start time.
  • Initialize SDK clients outside the handler so they are reused between invocations.
  • Set sensible timeouts and memory; more memory also means more CPU.
  • Use structured JSON logging so CloudWatch can be queried easily.
  • Protect routes with authorizers (JWT, Cognito or IAM).

Key Takeaways

  • API Gateway routes requests; Lambda runs your code on demand.
  • The same handler pattern works in Python, Node.js and other runtimes.
  • SAM templates make serverless infrastructure repeatable.
  • Reuse clients and keep packages small for faster responses.

Contact Us

Have a question or feedback? Fill out the form below or reach us directly at support@nvaitraining.com