Building Serverless APIs - Scalable API Infrastructure with Amazon API Gateway

Learn how to build serverless APIs using Amazon API Gateway and Lambda.

The Concept of Serverless APIs and the Role of API Gateway

APIs are at the core of modern applications, handling communication between frontends and backends, between microservices, and with external partners. Amazon API Gateway is a fully managed service for creating, publishing, and managing REST APIs, HTTP APIs, and WebSocket APIs. It can handle hundreds of thousands of requests per second and automatically scales in response to traffic spikes. API Gateway's internal architecture processes requests through a pipeline of stages: request reception, authentication/authorization, throttling, backend invocation, and response transformation. This design allows each stage to be independently configured and optimized, enabling declarative management of the entire API lifecycle. When running API servers on-premises, you need to build reverse proxies like Nginx or Kong, manage SSL certificates, configure load balancers, and design scaling strategies. API Gateway provides all of these as a managed service, letting you focus on API design and business logic implementation.

Choosing Between REST API and HTTP API

API Gateway offers two types: REST API and HTTP API. REST API provides full-featured API management, including API key management, usage plans, request/response transformation (VTL templates), caching, WAF integration, and request validation. HTTP API is up to 71% cheaper than REST API, offers lower latency, and is ideal for simple APIs and proxy integrations. HTTP API natively supports OIDC and OAuth 2.0 JWT authorizers, making integration with identity providers like Cognito and Auth0 straightforward. In terms of pricing, HTTP API costs $1.29 per million requests, while REST API costs $4.25 per million requests. Here are the selection criteria: ``` # When to choose HTTP API - Lambda proxy integration is sufficient - JWT-based authentication meets your needs - Cost optimization is a priority # When to choose REST API - API keys + usage plans are required - Request/response transformation is needed - WAF integration or caching is required - Request validation is needed ``` REST API's caching feature supports cache sizes from 0.5 GB to 237 GB, reducing backend requests while simultaneously improving response times and lowering costs.

Authentication, Authorization, and API Security

API Gateway provides multi-layered security features. Lambda authorizers let you implement custom authentication and authorization logic, supporting any authentication method including JWT tokens, OAuth, and SAML. Integration with Cognito user pools enables you to build a complete authentication flow with user registration, sign-in, MFA, and token management using API Gateway alone. Resource policies restrict access to specific IP addresses, VPC endpoints, or AWS accounts. Usage plans and API keys enable per-partner rate limiting and quota management. AWS WAF integration adds protection against SQL injection, XSS, and DDoS attacks. Mutual TLS (mTLS) authentication is also supported, enabling two-way authentication with client certificates. With on-premises API servers, you would need to implement and integrate each of these security features individually, significantly increasing development and operational overhead.

WebSocket API and Real-Time Communication

API Gateway's WebSocket API enables bidirectional real-time communication in a serverless architecture. It supports use cases requiring persistent connections, such as chat applications, real-time dashboards, multiplayer game communication, and IoT device control. WebSocket API automatically manages connections, and Lambda functions handle the $connect, $disconnect, and $default route events. By storing connection IDs in DynamoDB, you can send messages to specific clients or broadcast to all connected users. WebSocket API supports a maximum idle timeout of 2 hours and a maximum connection duration of 24 hours. Pricing is $1.14 per million messages and $0.285 per million connection-minutes. API Gateway's WebSocket API is fully pay-per-use, with zero cost during periods with no connections. This pricing model difference creates significant cost savings for applications with highly variable traffic. You can systematically learn serverless API fundamentals and advanced topics from books (Amazon).

API Deployment and Lifecycle Management

API Gateway provides built-in API versioning and stage management. Stage variables let you specify different backend Lambda functions or endpoints for dev, staging, and prod environments, separating environment-specific configuration from the API definition. The canary release feature allows you to route only a portion of traffic (e.g., 10%) to a new API version, then gradually shift to 100% once confirmed stable. With SAM (Serverless Application Model) for IaC management, you can declaratively manage API definitions, Lambda functions, and IAM roles in a single template. ```yaml Resources: ApiFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs20.x Events: GetItems: Type: HttpApi Properties: Path: /items Method: GET ``` CloudWatch metrics integration enables real-time monitoring of API latency, error rates, and request counts, with alarms triggered on anomaly detection. X-Ray integration lets you trace the full request path from API Gateway through Lambda to DynamoDB, identifying performance bottlenecks.

API Gateway Pricing

HTTP API costs approximately $1.00 per million requests, while REST API costs approximately $3.50 per million requests. WebSocket API costs approximately $1.00 per million messages plus connection-time charges. When estimating the total cost of a serverless API, factor in Lambda pricing (approximately $0.20 per million requests plus execution time). Use HTTP API as the default choice and select REST API only when WAF integration or usage plans are required to optimize costs.

Summary - Choosing a Serverless API Platform

Amazon API Gateway comprehensively supports three API types as a serverless API platform: REST, HTTP, and WebSocket. By selecting the right type for each use case - HTTP API's low cost of $1.29 per million requests, REST API's advanced management features, and WebSocket API's pay-per-use real-time communication - you can build an optimal API infrastructure.