Build Serverless APIs: API Gateway, Cognito, AppSync, Lambda and a Complete Serverless Web Architecture
A Serverless Web Application
text
Browser ─► CloudFront ─► S3 (static front end: React, Vue) [no servers]
│
└─► Cognito (sign-in, JWT tokens)
└─► API Gateway (REST/HTTP API, validates JWT, throttles) ─► Lambda ─► DynamoDB / S3 / SQS
└► Step Functions, EventBridge
Nothing runs when nobody uses it. You pay per request, and AWS handles scaling, patching and multi-AZ availability.
Amazon API Gateway
| API type | Features | Notes |
|---|---|---|
| HTTP API | Lower cost and latency, JWT authorizers (Cognito/OIDC), Lambda and HTTP integrations, CORS, automatic deployments | Best for most new serverless APIs |
| REST API | More features: API keys and usage plans, request validation, caching, WAF, resource policies, private endpoints, canary release, mapping templates, per-method throttling | When you need those extras |
| WebSocket API | Two-way, persistent connections | Chat, live dashboards, notifications |
| Concept | Meaning |
|---|---|
| Stage | A deployed version such as dev, prod, with its own URL and settings. REST APIs support stage variables and canary deployments |
| Integration | Backend: Lambda (proxy), HTTP endpoint, other AWS services, or a mock. Private integration reaches resources in a VPC through a VPC link |
| Throttling | Default account limit (about 10,000 requests/s, 5,000 burst, can be raised). Set per stage and per route. Over the limit → HTTP 429 |
| Caching (REST) | Cache responses per stage (0.5 to 237 GB), TTL default 300 s |
| Usage plans and API keys (REST) | Rate limits and quotas per customer (not a security feature on its own) |
| Endpoint type | Regional, Edge-optimized (through CloudFront) or Private (only from a VPC endpoint) |
| Custom domain | Your domain plus ACM certificate and Route 53 alias |
Authorization Options
| Method | Use for |
|---|---|
| IAM authorization (SigV4) | Callers that are AWS identities: other services, backends |
| Cognito user pool authorizer / JWT authorizer | Your app users signed in with Cognito or any OIDC provider |
| Lambda authorizer | Custom logic: tokens from another system, API keys in headers, complex rules. Result can be cached |
| Resource policy | Allow only certain IPs, VPCs or accounts |
| WAF | Block SQL injection, bad bots, rate-limit by IP (REST API with WAF) |
| mTLS | Client certificates for B2B APIs |
Amazon Cognito
| Component | What it does |
|---|---|
| User pool | A user directory and sign-in service: sign-up, sign-in, password policies, MFA, email/phone verification, social login (Google, Facebook, Apple) and SAML/OIDC federation. Issues JWT tokens (ID, access, refresh). Hosted UI for login pages |
| Identity pool (federated identities) | Exchanges a token (from a user pool, social, SAML, or anonymous guest) for temporary AWS credentials to call AWS services directly (for example upload to S3) |
| Groups and attributes | Roles and custom data in tokens |
| Lambda triggers | Customize flows (pre sign-up, post confirmation, pre token generation) |
text
Authenticate users: App ─► Cognito USER POOL ─► JWT ─► API Gateway validates JWT ─► Lambda
Give users AWS permissions: App ─► token ─► Cognito IDENTITY POOL ─► temporary IAM credentials ─► S3 / DynamoDB directly
Exam shortcut: Sign-in and user directory → User pool. Access to AWS resources with temporary credentials → Identity pool. For internal staff accounts use IAM Identity Center instead.
AWS AppSync
- Managed GraphQL (and Pub/Sub) API service. One endpoint, clients ask for exactly the fields they need
- Resolvers connect to DynamoDB, Lambda, Aurora, OpenSearch, HTTP
- Real-time subscriptions over WebSockets
- Offline data sync for mobile and web apps
- Authorization: API key, Cognito, IAM, OIDC, Lambda
A Complete SAM Template
yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Orders API (HTTP API + Lambda + DynamoDB + Cognito JWT)
Globals:
Function:
Runtime: python3.13
Architectures: [arm64]
Timeout: 10
MemorySize: 256
Environment:
Variables:
TABLE: !Ref OrdersTable
Resources:
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: shop-users
AutoVerifiedAttributes: [email]
UsernameAttributes: [email]
UserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref UserPool
GenerateSecret: false
ExplicitAuthFlows: [ALLOW_USER_SRP_AUTH, ALLOW_REFRESH_TOKEN_AUTH]
OrdersTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- {AttributeName: customerId, AttributeType: S}
- {AttributeName: orderId, AttributeType: S}
KeySchema:
- {AttributeName: customerId, KeyType: HASH}
- {AttributeName: orderId, KeyType: RANGE}
Api:
Type: AWS::Serverless::HttpApi
Properties:
Auth:
DefaultAuthorizer: JwtAuth
Authorizers:
JwtAuth:
IdentitySource: $request.header.Authorization
JwtConfiguration:
issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool}
audience: [!Ref UserPoolClient]
CreateOrder:
Type: AWS::Serverless::Function
Properties:
Handler: app.create_order
CodeUri: src/
Policies:
- DynamoDBWritePolicy: {TableName: !Ref OrdersTable}
Events:
Post:
Type: HttpApi
Properties: {ApiId: !Ref Api, Method: POST, Path: /orders}
Outputs:
ApiUrl:
Value: !Sub https://${Api}.execute-api.${AWS::Region}.amazonaws.com
bash
sam build && sam deploy --guided
sam logs -n CreateOrder --tail
sam delete
python
# src/app.py
import json, os, uuid, boto3
table = boto3.resource("dynamodb").Table(os.environ["TABLE"])
def create_order(event, context):
claims = event["requestContext"]["authorizer"]["jwt"]["claims"] # verified by API Gateway
body = json.loads(event.get("body") or "{}")
item = {"customerId": claims["sub"], "orderId": str(uuid.uuid4()), "items": body.get("items", [])}
table.put_item(Item=item)
return {"statusCode": 201, "body": json.dumps({"orderId": item["orderId"]})}
Serverless Design Rules
- Stateless functions; state in DynamoDB, S3 or caches
- Use queues and events between steps so spikes are absorbed (API → SQS → Lambda)
- Idempotent handlers because events can repeat
- Least-privilege role per function
- Throttle and protect APIs: WAF, usage plans, per-route limits
- Observe: X-Ray, structured logs, alarms on 5xx, throttles, duration
- Know the limits: API Gateway timeout is 29 seconds by default for REST integrations (can be raised per Region quota), Lambda 15 minutes. For long jobs return 202 Accepted and process asynchronously
Practice Tasks
- Deploy the SAM template and call the API with a JWT from the Cognito Hosted UI
- Add a Lambda authorizer to a REST API and cache its result
- Change the API to send orders to SQS and process them with another Lambda
- Add a WAF rate rule on a REST API
- Explain when you need a user pool, an identity pool, or both
Conclusion
Build serverless apps with CloudFront and S3 for the front end, Cognito for users, API Gateway (HTTP API for most cases, REST for advanced features) for secure, throttled APIs, Lambda for logic and DynamoDB for data. Use JWT or Lambda authorizers, queues for long work, and deploy with SAM or CDK.
Quick Summary: serverless web diagram; HTTP vs REST vs WebSocket; throttling, stages, caching; authorizer types; Cognito user pool vs identity pool; AppSync; SAM template; design rules + limits.

