Build Serverless APIs: API Gateway, Cognito, AppSync, Lambda and a Complete Serverless Web Architecture

AWS Solutions Architect 50 min min read Updated: Nov 17, 2026 Intermediate
Build Serverless APIs: API Gateway, Cognito, AppSync, Lambda and a Complete Serverless Web Architecture
Intermediate Topic 2 of 3

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 typeFeaturesNotes
HTTP APILower cost and latency, JWT authorizers (Cognito/OIDC), Lambda and HTTP integrations, CORS, automatic deploymentsBest for most new serverless APIs
REST APIMore features: API keys and usage plans, request validation, caching, WAF, resource policies, private endpoints, canary release, mapping templates, per-method throttlingWhen you need those extras
WebSocket APITwo-way, persistent connectionsChat, live dashboards, notifications
ConceptMeaning
StageA deployed version such as dev, prod, with its own URL and settings. REST APIs support stage variables and canary deployments
IntegrationBackend: Lambda (proxy), HTTP endpoint, other AWS services, or a mock. Private integration reaches resources in a VPC through a VPC link
ThrottlingDefault 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 typeRegional, Edge-optimized (through CloudFront) or Private (only from a VPC endpoint)
Custom domainYour domain plus ACM certificate and Route 53 alias

Authorization Options

MethodUse for
IAM authorization (SigV4)Callers that are AWS identities: other services, backends
Cognito user pool authorizer / JWT authorizerYour app users signed in with Cognito or any OIDC provider
Lambda authorizerCustom logic: tokens from another system, API keys in headers, complex rules. Result can be cached
Resource policyAllow only certain IPs, VPCs or accounts
WAFBlock SQL injection, bad bots, rate-limit by IP (REST API with WAF)
mTLSClient certificates for B2B APIs

Amazon Cognito

ComponentWhat it does
User poolA 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 attributesRoles and custom data in tokens
Lambda triggersCustomize 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

  1. Stateless functions; state in DynamoDB, S3 or caches
  2. Use queues and events between steps so spikes are absorbed (API → SQS → Lambda)
  3. Idempotent handlers because events can repeat
  4. Least-privilege role per function
  5. Throttle and protect APIs: WAF, usage plans, per-route limits
  6. Observe: X-Ray, structured logs, alarms on 5xx, throttles, duration
  7. 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

  1. Deploy the SAM template and call the API with a JWT from the Cognito Hosted UI
  2. Add a Lambda authorizer to a REST API and cache its result
  3. Change the API to send orders to SQS and process them with another Lambda
  4. Add a WAF rate rule on a REST API
  5. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators