AWS Cloud Developer Associate Certification

14.API Gateway
Build, Deploy and Manage APIs

Index

  1. Introduction
  2. Integration with other services
  3. API Gateway- endpoints Types
  4. Deployment stages
  5. API Gateway Integration Types
  6. Caching API Responses
  7. API Gateway- Usage plans and API Keys
  8. API Gateway throlleling
  9. API Gateway – errors
  10. API Gateway – CORS
  11. API Gateway – SECURITY
  12. API Gateway – HTTP API vs Rest API
  13. API Gateway – web Socket
  14. connecting Api
  15. API Gateway Architecture
  1. Introduction
  1. AWS Lambda + API Gateway: No infrastructure to manage
  2. Handle different environments (dev, test, prod…)
  3. Handle security (Authentication and Authorization)
  4. Create API keys, handle request throttling
  • Integration with other services
  1. Lambda Function
    1. Easy way to expose REST API backed by AWS Lambda
  2. HTTP
    1. Expose HTTP endpoints in the backend
    2. Why? Add rate limiting, caching, user authentications, API keys, etc…
  3. AWS Service
    1. Expose any AWS API through the API Gateway?
    2. Example: start an AWS Step Function workflow, post a message to SQS
    3. Why? Add authentication, deploy publicly, rate control…
  • API Gateway endpoints Types
  1. Edge-Optimized (default): For global clients
    1. Requests are routed through the CloudFront Edge locations (improves latency
    2. The API Gateway still lives in only one region
  2. Regional:
    1. For clients within the same region
    2. Could manually combine with CloudFront (more control over the caching strategies and the distribution)
  3. Private:
    1. Can only be accessed from your VPC using an interface VPC endpoint (ENI)
    2. Use a resource policy to define access
  • Deployment stages
  1. Making changes in the API Gateway does not mean they’re effective
  2. You need to make a “deployment” for them to be in effect
  3. It’s a common source of confusion
  4. Changes are deployed to “Stages” (as many as you want)
    1. Use the naming you like for stages (dev, test, prod)
    1. Each stage has its own configuration parameters
    2. Stages can be rolled back as a history of deployments is kept

API Gateway – Stage Variables

  1. Stage variables are like environment variables for API Gateway
  2. They can be used in:
    1. Lambda function ARN
    2. HTTP Endpoint
    3. Parameter mapping templates
  3. Use cases:
    1. Configure HTTP endpoints your stages talk to (dev, test, prod…)
    2. Pass configuration parameters to AWS Lambda through mapping templates
  4. Stage variables are passed to the ”context” object in AWS Lambda

API Gateway – Canary Deployment

  1. Possibility to enable canary deployments for any stage (usually prod)
  2. Choose the % of traffic the canary channel receives(say 5%)
  3. Possibility to override stage variables for canary
  4. This is blue / green deployment with AWS Lambda & API Gateway
  • API Gateway Integration Types
  1. Integration Type MOCK
    1. API Gateway returns a response without sending the request to the backend
  2. Integration Type HTTP / AWS (Lambda & AWS Services)
    1. you must configure both the integration request and integration response
    2. Setup data mapping using mapping templates for the request & response
  1. Integration Type AWS_PROXY (Lambda Proxy):
    1. incoming request from the client is the input to Lambda
    2. The function is responsible for the logic of request / response
    3. No mapping template, headers, query string parameters… are passed as arguments
  2. Integration Type HTTP_PROXY
    1. No mapping template
    2. The HTTP request is passed to the backend
    3. The HTTP response from the backend is forwarded by API Gateway

Mapping Templates (AWS & HTTP Integration)

  1. Mapping templates can be used to modify request / responses
  2. Rename / Modify query string parameters
  3. Modify body content
  4. Add headers
  5. Uses Velocity Template Language (VTL): for loop, if etc…
  6. Filter output results (remove unnecessary data)
    1. Mapping Example: JSON to XML with SOAP
    2. Mapping Example: Query String parameters
Response mapping
Query -variable mapping

  1. Caching API Responses
  1. Caching reduces the number of calls made to the backend
  2. Default TTL (time to live) is 300 seconds (min: 0s, max: 3600s)
  3. Caches are defined per stage
  4. Possible to override cache settings per method
  5. Cache capacity between 0.5GB to 237GB
  6. Cache is expensive, makes sense in production, may not make sense in dev / test
  7. Cache Invalidation
    1. Clients can invalidate the cache with header: Cache- Control: max-age=0 (with proper IAM authorization)
    2. If you don’t impose an InvalidateCache policy (or choose the Require authorization check box in the console), any client can invalidate the API cache
  1. API Gateway- Usage plans and API Keys

If you want to make an API available as an offering ($) to your customers

  1. Usage Plan
    1. who can access one or more deployed API stages and methods
    2. how much and how fast they can access them
    3. uses API keys to identify API clients and meter access
    4. configure throttling limits and quota limits that are enforced on individual client
  2. API Keys:
    1. alphanumeric string values to distribute to your customers
  1. Usage Plan
    1. who can access one or more deployed API stages and methods
    2. how much and how fast they can access them
    3. uses API keys to identify API clients and meter access
    4. configure throttling limits and quota limits that are enforced on individual client
  2. API Keys:
    1. alphanumeric string values to distribute to your customers
    2. Ex: WBjHxNtoAb4WPKBC7cGm64CBibIb24b4jt8jJHo9
    3. Can use with usage plans to control access
    4. Throttling limits are applied to the API keys
    5. Quotas limits is the overall number of maximum requests
    6. Callers of the API must supply an assigned API key in the x-api-key header in requests to the API.
  • API Gateway throttling
  1. API Gateway throttles requests at 10,000 rps across all API
  2. Soft limit that can be increased upon request
  3. In case of throttling => 429 Too Many Requests (retriable error)
  4. Can set Stage limit & Method limits to improve performance
  5. Or you can define Usage Plans to throttle per customer
  6. Just like Lambda Concurrency, one API that is overloaded, if not limited, can cause the other APIs to be throttled.
  • API Gateway – errors
  1. 4xx means Client errors
    1. 400: Bad Request
    2. 403: Access Denied, WAF filtered
    3. 429: Quota exceeded, Throttle
  2. 5xx means Server errors
    1. 502: Bad Gateway Exception, usually for an incompatible output returned from a Lambda proxy integration backend and occasionally for out-of-order invocations due to heavy loads.
    2. 503: Service Unavailable Exception
    3. 504: Integration Failure – ex Endpoint Request Timed-out Exception,API Gateway requests time out after 29 second maximum
  • API Gateway – CORS
  1. CORS must be enabled when you receive API calls from another domain.
  2. The OPTIONS pre-flight request must contain the following headers:
    1. Access-Control-Allow-Methods
    2. Access-Control-Allow-Headers
    3. Access-Control-Allow-Origin
  • API Gateway – SECURITY
  1. IAM Permissions
    1. Create an IAM policy authorization and attach to User / Role
    2. Authentication = IAM | Authorization = IAM Policy
    3. Good to provide access within AWS (EC2, Lambda, IAM users…)
    4. Leverages “Sig v4” capability where IAM credential are in headers
  2. API Gateway – Resource Policies
    1. Resource policies (similar to Lambda Resource Policy)
    2. Allow for Cross Account Access (combined with IAM Security)
    3. Allow for a specific source IP address
    4. Allow for a VPC Endpoint
  3. Cognito User Pools
    1. Cognito fully manages user lifecycle, token expires automatically
    2. API gateway verifies identity automatically from AWS Cognito
    3. Authentication = Cognito User Pools | Authorization = API Gateway Methods
  4. Lambda Authorizer (formerly Custom Authorizers)
    1. Token-based authorizer (bearer token) – ex JWT (JSON Web Token) or Oauth
    2. A request parameter-based Lambda authorizer (headers, query string, stage var)
    3. Lambda must return an IAM policy for the user, result policy is cached
    4. Authentication = External | Authorization = Lambda function
    5. Pay per Lambda invocation, results are cached
  • API Gateway – HTTP API vs Rest API
  1. HTTP APIs
    1. low-latency, cost-effective AWS Lambda proxy, HTTP proxy APIs and private integration (no data mapping
    2. support OIDC and OAuth 2.0 authorization, and built-in support for CORS
    3. No usage plans and API keys
  2. REST APIs
    1. All features (except Native OpenID Connect / OAuth 2.0)
  • API Gateway – web Socket
  1. What’s WebSocket?
    1. Two-way interactive communication between a user’s browser and a server
    2. Server can push information to the client
    3. This enables stateful application use cases
  2. WebSocket APIs are often used in realtime applications such as chat applications, collaboration platforms, multiplayer games, and financial trading platforms.
  3. Works with AWS Services (Lambda DynamoDB) or HTTP endpoints
  • Connecting API
  1. WebSocket URL
    1. wss://[some-uniqueid].execute-api.[region].amazonaws.com/[stage-name]
  2. Client to Server Messaging
    1. ConnectionID is re-used
  1. Server to Client messaging

API Gateway – WebSocket API – Routing

  1. Incoming JSON messages are routed to different backend
  2. If no routes => sent to $default
  3. You request a route selection expression to select the field on JSON to route from
  4. Sample expression: $request.body.action
  5. The result is evaluated against the route keys available in your API Gateway
  6. The route is then connected to the backend you’ve setup through API Gateway
  • API Gateway Architecture
  1. Create a single interface for all the microservices in your company
  2. Use API endpoints with various resources
  3. Apply a simple domain name and SSL certificates

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment