Skip to main content

Building Serverless APIs with API Gateway

Build serverless APIs with API Gateway, secure them with Cognito, and orchestrate multi-step workflows with Step Functions in production.

Overview and What You Will Learn

Amazon API Gateway is a fully managed front door for your APIs. It handles routing, authentication, throttling, caching, CORS and TLS before a request reaches your Lambda function or backend. Alongside it, AWS Step Functions orchestrates multi-step workflows and Amazon Cognito handles user sign-up, sign-in and AWS access. In this lab you build a Lambda-backed REST API and protect it with a Cognito User Pool.

By the end you will be able to:

  • Choose between REST, HTTP and WebSocket APIs and between Edge-Optimized, Regional and Private endpoints
  • Connect API Gateway to Lambda, HTTP backends and AWS services directly
  • Use stages, stage variables and canary deployments to separate dev from prod
  • Secure an API with IAM, Lambda authorizers or Cognito
  • Explain Step Functions state types, Standard vs Express workflows, retries and error handling
  • Explain Cognito User Pools vs Identity Pools and how they work together

Why This Matters in Production

A payments company such as Razorpay can put API Gateway in front of its APIs so authentication, rate limiting and routing run before any business code. A food delivery company such as Swiggy has an order flow that touches fraud checks, inventory, the kitchen, delivery assignment, email and analytics, and a Step Functions state machine gives that flow retries, error routing and a visible history instead of six services calling each other. A fintech such as CRED can use Cognito for sign-in and sessions instead of building and patching its own auth server.

These three services form the application layer of most serverless architectures on AWS. The costly mistakes are usually in the details: the wrong certificate Region, the wrong workflow type, or confusing authentication with AWS authorization.

Core Principles

What Is Amazon API Gateway and Which API Type Should You Pick?

API Gateway receives HTTP or WebSocket requests, authenticates and throttles them, routes them to a backend and returns the response. It offers three API types, and the right one depends on the features you need.

API type Best for
REST API Full feature set: API keys, usage plans, caching, request validation
HTTP API Cheaper, lower latency proxy to Lambda or HTTP with JWT authorizers
WebSocket API Persistent two-way connections
flowchart TD A([Client]) --> B[API Gateway] B --> C{Authorize and throttle} C -->|Allowed| D[Lambda] C -->|Allowed| E[HTTP backend] C -->|Allowed| F[AWS service] C -->|Denied| G([401 or 403]) classDef edge fill:#8B5CF6,color:#ffffff classDef gw fill:#326CE5,color:#ffffff classDef back fill:#10B981,color:#ffffff classDef bad fill:#EF4444,color:#ffffff class A edge class B,C gw class D,E,F back class G bad
What Are the API Gateway Endpoint Types?

An endpoint type decides where your API is reachable from. Edge-Optimized routes requests through CloudFront edge locations and suits global clients. Regional serves clients in or near one Region and is the usual choice when you add your own CloudFront. Private is reachable only from inside a VPC through an interface VPC endpoint.

Remember

Edge-Optimized APIs use CloudFront, so a custom domain certificate must be in us-east-1. A Regional API needs the certificate in the same Region as the API.

How Does API Gateway Connect to Lambda, HTTP Backends and AWS Services?

With a Lambda proxy integration, API Gateway turns the HTTP request into an event, invokes your function and converts the returned response back into HTTP. The event carries fields such as httpMethod, path, pathParameters, headers and body. HTTP integrations forward to any public endpoint, and AWS service integrations call services such as SQS, DynamoDB or Step Functions directly with no Lambda in between.

  • Use Lambda when you need business logic
  • Use a direct service integration for simple pass-through, for example POST /orders sending a message to SQS
  • Use an HTTP integration to put authentication and throttling in front of an existing service
What Are API Gateway Stages and Canary Deployments?

Changes to an API do nothing until you deploy them to a stage such as dev or prod, and each stage has its own URL, throttling, caching, logging and stage variables. Stage variables act like environment variables, so the dev stage can call a dev Lambda alias and the prod stage a prod alias. A canary deployment sends a small percentage of a stage's traffic to the new version so you can watch errors before promoting it.

â—ˆ DIAGRAM
prod stage: 95 percent to current version, 5 percent to canary
errors stay low -> promote canary to 100 percent
errors rise -> remove canary, traffic stays on current version
How Do You Secure an API Gateway API?

Pick the authorizer that matches who is calling. IAM authentication suits AWS service-to-service calls signed with Signature Version 4. A Lambda authorizer runs your own code to validate any token and returns an IAM policy that allows or denies the call, and the result can be cached for a configurable time (300 seconds by default, up to 3600). A Cognito authorizer validates a Cognito User Pool token directly with no code.

sequenceDiagram participant U as User participant C as Cognito participant G as API Gateway participant L as Lambda U->>C: Sign in C-->>U: JWT tokens U->>G: Request with token G->>G: Validate token G->>L: Invoke L-->>U: 200 response
  • With a REST API Cognito authorizer, send the token itself in the Authorization header. HTTP APIs use a JWT authorizer and accept the Bearer format.
  • API keys and usage plans identify clients and apply throttle and quota limits. They are not a substitute for authentication.
Tip

Use usage plans for per-client rate limits. Clients that exceed their limit get a 429 response without any code in your Lambda function.

How Do WebSocket APIs Work?

A WebSocket API keeps a connection open in both directions so a server can push data without the client asking. API Gateway manages the connections and invokes your Lambda for connect, disconnect and message routes. To push to a client, your code calls the API Gateway management API with that client's connection ID. Connections have an idle timeout and a maximum duration, so clients should reconnect.

  • Good fits: live chat, live dashboards, multiplayer games, order tracking
What Is AWS Step Functions?

Step Functions is a serverless workflow service that runs a state machine, where each state is one step such as calling a Lambda, branching, waiting or running work in parallel. It manages retries, error routing, timeouts and a per-execution history, so you do not write glue code between services. You define the workflow in Amazon States Language and can design it visually in Workflow Studio.

State type Purpose
Task Do work, such as invoke Lambda or call an AWS service
Choice Branch on data
Parallel Run branches at the same time
Map Run the same steps for each item in a list
Wait Pause for a time or until a date
flowchart TD A([Order placed]) --> B[Fraud check] B --> C[Reserve inventory] C --> D[Notify kitchen] C --> E[Assign delivery] D --> F[Send confirmation] E --> F B -.->|Error| G[Cancel and refund] classDef start fill:#8B5CF6,color:#ffffff classDef task fill:#326CE5,color:#ffffff classDef err fill:#EF4444,color:#ffffff class A start class B,C,D,E,F task class G err

Step Functions has built-in error handling. A Retry block re-runs a failed state with backoff, and a Catch block routes to a recovery state, such as undoing earlier steps in a saga. Integrations can also wait for a job to finish or for an external callback with a task token.

Should You Use Standard or Express Step Functions Workflows?

Use Standard for long-running, auditable processes and Express for high-volume, short-lived work. Standard runs up to a year with exactly-once workflow execution and a full execution history. Express runs up to 5 minutes, is built for very high start rates and sends history to CloudWatch Logs.

Standard Express
Max duration 1 year 5 minutes
Pricing basis State transitions Requests and duration
Best for Order fulfilment, approvals Streaming and IoT processing

Express offers at-least-once execution for asynchronous runs and at-most-once for synchronous runs, so design steps to be idempotent.

Common Mistake

Using Standard workflows for millions of short executions. Standard bills per state transition, so cost climbs quickly. Use Express for high-volume short pipelines.

What Is Amazon Cognito and What Is the Difference Between User Pools and Identity Pools?

A User Pool is a user directory that authenticates people and issues JWT tokens, while an Identity Pool exchanges a login for temporary AWS credentials. User Pools handle sign-up, sign-in, MFA, password reset and social or SAML sign-in, and issue an ID token (who the user is), an access token (what the token allows) and a refresh token (get new tokens). Identity Pools then let the signed-in user call AWS services such as S3 or DynamoDB directly with short-lived credentials.

User Pools Identity Pools
Purpose Authentication AWS access
Issues JWT tokens Temporary AWS credentials
Typical use Sign in, sign up Upload to S3 from an app
flowchart LR A([User]) -->|Sign in| B[User Pool] B -->|JWT| C[Identity Pool] C -->|Temp credentials| D[S3 or DynamoDB] classDef user fill:#8B5CF6,color:#ffffff classDef auth fill:#326CE5,color:#ffffff classDef svc fill:#F97316,color:#ffffff class A user class B,C auth class D svc
Remember

User Pools answer who you are. Identity Pools answer which AWS resources you can use. Most apps use both, and an API-only app that just validates tokens may need only a User Pool.

How Can Cognito Give Each User Access to Only Their Own DynamoDB Items?

Attach an IAM condition to the Identity Pool role that restricts the DynamoDB leading key to the caller's Cognito identity. The condition key is dynamodb:LeadingKeys, compared with the policy variable ${cognito-identity.amazonaws.com:sub}. A user whose identity ID is abc-123 can then read and write only items whose partition key is abc-123, and the restriction is enforced by AWS rather than by your application code.

Detailed Step-by-Step Practical Lab

This lab builds a REST API backed by Lambda and protects it with a Cognito User Pool. Console menus change over time, so follow the intent of each step.

Step 1: Create the Lambda function

In Lambda, create a function named devops-orders-api with the Python 3.12 runtime (or a newer supported Python runtime) and paste this handler.

Python
import json
def lambda_handler(event, context):
method = event.get('httpMethod', 'GET')
path = event.get('path', '/')
if method == 'GET' and path.endswith('/orders'):
orders = [
dict(orderId='ORD-001', city='Mumbai', amount=450),
dict(orderId='ORD-002', city='Pune', amount=1200),
]
return dict(
statusCode=200,
headers={'Content-Type': 'application/json'},
body=json.dumps(orders),
)
return dict(statusCode=404, body=json.dumps(dict(error='Not found')))

Deploy the function.

Step 2: Create the REST API, resource and method

In API Gateway, create a REST API named devops-orders-api with a Regional endpoint. Create a resource /orders, then a GET method with the integration type Lambda function and Lambda proxy integration turned on. Choose devops-orders-api as the function and grant permission when asked.

Step 3: Deploy to a stage

Deploy the API to a new stage named dev and copy the invoke URL, which looks like https://abc123.execute-api.ap-south-1.amazonaws.com/dev. Open the /orders path in a browser to see the JSON orders. At this point the API is open to everyone.

Step 4: Create a Cognito User Pool and app client

In Cognito, create a user pool named devops-users with email sign-in. Create an app client named devops-web-app without a client secret and enable the USER_PASSWORD_AUTH flow for the lab. Note the User Pool ID and the App Client ID.

Step 5: Add a Cognito authorizer

In API Gateway, create a Cognito authorizer named cognito-auth for the devops-users pool, with the token source set to the Authorization header. On GET /orders, set the method request authorization to cognito-auth, then redeploy to the dev stage.

Step 6: Create a user and get a token
Bash
aws cognito-idp admin-create-user \
--user-pool-id ap-south-1_EXAMPLE \
--username test@devops.in \
--message-action SUPPRESS \
--region ap-south-1
aws cognito-idp admin-set-user-password \
--user-pool-id ap-south-1_EXAMPLE \
--username test@devops.in \
--password 'Test@12345!' \
--permanent \
--region ap-south-1
# Sign in and read IdToken from the output
aws cognito-idp initiate-auth \
--auth-flow USER_PASSWORD_AUTH \
--client-id YOUR-APP-CLIENT-ID \
--auth-parameters USERNAME=test@devops.in,PASSWORD='Test@12345!' \
--region ap-south-1
Step 7: Test with and without a token
Bash
# With the ID token: 200 and the orders
curl -H "Authorization: PASTE-ID-TOKEN-HERE" \
https://abc123.execute-api.ap-south-1.amazonaws.com/dev/orders
# Without a token: 401 Unauthorized
curl -i https://abc123.execute-api.ap-south-1.amazonaws.com/dev/orders
Step 8 (optional): Sketch a workflow in Workflow Studio

In Step Functions, create a state machine and use Workflow Studio to drag in a Lambda Task, a Choice and a Fail state. Add a Retry with exponential backoff to the Task and run an execution to see the visual history.

Step 9: Clean up

Delete the API, the Lambda function, the user pool and any state machine you created.

Production Best Practices & Common Pitfalls

  • Pick the cheapest API type that fits: Use HTTP APIs for simple Lambda proxies and REST APIs when you need usage plans, caching or request validation.
  • Mind the certificate Region: Edge-Optimized needs us-east-1, Regional needs the API's Region.
  • Throttle and protect: Set stage throttling, and use usage plans for per-client limits.
  • Never rely on API keys for security: Use Cognito, a Lambda authorizer or IAM.
  • Use stages and canaries: Test changes on a small share of traffic first.
  • Choose Express for high volume, Standard for auditability: Make steps idempotent either way.
  • Handle failure in the workflow: Use Retry and Catch rather than custom code in every function.
  • Combine User Pools and Identity Pools only when needed: An API that validates JWTs does not need an Identity Pool.
Common Mistake

Confusing User Pools with Identity Pools. One authenticates users, the other issues AWS credentials, and a design that needs both will fail if you set up only one.

Common Mistake

Putting the Edge-Optimized custom domain certificate in ap-south-1. CloudFront needs it in us-east-1, otherwise the domain cannot use HTTPS.

Quick Reference & Troubleshooting Commands

Task Command
List REST APIs aws apigateway get-rest-apis --region ap-south-1
Create a deployment aws apigateway create-deployment --rest-api-id <API-ID> --stage-name dev
List state machines aws stepfunctions list-state-machines
Start an execution aws stepfunctions start-execution --state-machine-arn <ARN> --input file://input.json
List user pools aws cognito-idp list-user-pools --max-results 10
Tail Lambda logs aws logs tail /aws/lambda/devops-orders-api --follow
Problem Likely cause and fix
401 with a valid token Wrong token type or Bearer prefix on a REST authorizer. Send the ID token as is.
403 Missing Authentication Token Wrong path or method, or API not redeployed. Redeploy the stage.
502 Bad Gateway Lambda returned an invalid response shape. Return statusCode and a string body.
429 Too Many Requests Throttle or usage plan limit reached. Raise it or retry with backoff.
NEW_PASSWORD_REQUIRED on sign-in User has a temporary password. Set a permanent password or complete the challenge.
HTTPS fails on custom domain Certificate in the wrong Region for the endpoint type.

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Compute and Auto Scaling

All 6 Topics

Frequently Asked Questions

Is Building Serverless APIs with API Gateway free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Building Serverless APIs with API Gateway topic cover?

Build serverless APIs with API Gateway, secure them with Cognito, and orchestrate multi-step workflows with Step Functions in production.

Found a mistake, an outdated step or a broken link?