5 - Api Gateway
5 - Api Gateway
Amazon API Gateway is a fully managed service that enables developers to create, publish, maintain,
monitor, and secure APIs at any scale. APIs act as the "front door" for applications to access data,
business logic, or functionality from backend services. API Gateway allows you to create RESTful APIs,
WebSocket APIs, and HTTP APIs, providing the flexibility to meet the needs of your application.
With Amazon API Gateway, you can create APIs that connect to a variety of backend services, including
AWS Lambda functions, Amazon EC2 instances, and other web services. It also offers features like traffic
management, authorization and access control, monitoring, and API version management.
Key Concepts
1. API Endpoints
An API Endpoint is a unique URL where your API can be accessed by client applications. API Gateway
provides several types of endpoints depending on the API type you are using:
● REST API Endpoints: These are used for RESTful APIs and are accessed using standard HTTP
methods like GET, POST, PUT, DELETE, etc.
● WebSocket API Endpoints: These are used for WebSocket APIs, which provide two-way
communication channels between the client and the server.
● HTTP API Endpoints: These are lightweight, low-latency endpoints that are used to create HTTP
APIs. HTTP APIs are simpler and more cost-effective compared to REST APIs.
https://{api-id}.execute-api.{region}.amazonaws.com/{stage}/{resource}
Where:
2. Resources
Resources in API Gateway represent the various parts of your API, such as collections or specific data
objects. Each resource is identified by a path (e.g., /users, /orders/{orderId}), and you can define
multiple methods (GET, POST, DELETE, etc.) for each resource.
● Resource Paths: Resources are defined hierarchically, similar to a folder structure, and can have
child resources. For example, /orders/{orderId}/items could be a resource within an
/orders/{orderId} resource.
● Methods: Each resource can have one or more methods associated with it, corresponding to
HTTP methods like GET, POST, DELETE, PUT, etc. Methods define how the API should handle
requests sent to that resource.
● Integration: Each method is linked to a backend integration, which could be an AWS Lambda
function, an HTTP endpoint, or another AWS service. This integration defines how API Gateway
should process and route the request.
● Stages: Stages represent different versions or environments of your API (e.g., dev, test, prod).
Each stage has its own URL endpoint and can have different settings, such as caching or
logging.
● Deployment: Deploying an API in API Gateway means making it available at a specific stage.
Once you deploy an API, you can access it via the stage URL, and it becomes publicly accessible
(depending on your configuration).
API Gateway provides several options for securing your APIs, including:
● API Keys: You can require clients to include API keys in their requests to identify and
authenticate them.
● IAM Permissions: Use AWS Identity and Access Management (IAM) policies to control access
to your API.
● Cognito User Pools: Integrate with Amazon Cognito to manage user authentication and
authorization.
● Lambda Authorizers: Use custom AWS Lambda functions to control access to your API by
implementing custom authorization logic.
1. Create a Resource:
○ In the API Gateway console, under your newly created API, click on "Resources".
○ Click "Create Resource" to add a new resource.
○ Enter a resource name and path (e.g., /users).
2. Add Methods:
○ Select the resource you just created.
○ Click "Create Method".
○ Choose an HTTP method (e.g., GET, POST).
○ Select the integration type. You can choose from options like "Lambda Function",
"HTTP", "Mock", or "AWS Service".
○ If you choose "Lambda Function", select your Lambda function to integrate with this
method.
3. Set Up Method Response and Integration Response:
○ Configure the method response to define how the API responds to the client.
○ Configure the integration response to define how API Gateway should handle responses
from the backend service.
1. Create a Stage:
○ After defining your resources and methods, you need to deploy your API to a stage.
○ Click on "Deploy API".
○ Choose "Deploy API" from the Actions menu.
○ Create a new stage (e.g., dev, prod) and provide a description.
2. Access Your API:
○ After deployment, you will receive an endpoint URL for the stage.
○ You can use this URL to test and access your API.
1. Enable Security:
○ Implement security measures like requiring API keys, setting up IAM permissions, or
integrating with Amazon Cognito.
2. Monitor API Usage:
○ Use Amazon CloudWatch to monitor API usage and performance metrics like request
count, latency, and error rates.
○ Set up alarms to notify you of any unusual activity or performance degradation.
● API Gateway provides the option to cache responses at the stage level to improve performance
and reduce backend load. You can configure caching settings such as time-to-live (TTL) and
cache key parameters.
● You can set up throttling limits to control the number of requests that clients can make to your API
within a certain timeframe. This helps protect your backend services from being overwhelmed by
excessive traffic.
● Use WebSocket APIs for real-time communication applications, such as chat apps or live data
feeds. API Gateway manages WebSocket connections and can trigger backend services based
on WebSocket events.
● API Gateway can be integrated with other AWS services such as AWS Lambda, Amazon
DynamoDB, Amazon S3, and more to build comprehensive serverless applications.
Conclusion
Amazon API Gateway is a powerful service that allows you to create and manage APIs with ease. By
understanding the key concepts such as API endpoints, resources, and methods, and following the steps
to get started, you can leverage API Gateway to build scalable, secure, and efficient APIs for your
applications. Whether you're building RESTful APIs, WebSocket APIs, or lightweight HTTP APIs, API
Gateway provides the tools and features needed to manage the entire API lifecycle, from development to
deployment and monitoring.
HTTP API
1. Purpose:
● Simplicity and Performance: HTTP APIs are designed to provide a simpler, faster, and more
cost-effective way to build APIs. They are ideal for use cases where you need to build
straightforward HTTP-based APIs without requiring all the advanced features of REST APIs.
● Low Latency: HTTP APIs are optimized for low latency, making them suitable for performance-
sensitive applications.
2. Features:
● Core Features: HTTP APIs support essential features such as creating routes, defining
integrations with AWS services (like Lambda, ECS, etc.), and configuring custom domains.
● Authentication: Supports JWT (JSON Web Tokens) and AWS IAM-based authorization. It does
not support custom authorizers (Lambda authorizers).
● API Integration: Integrates with AWS Lambda, HTTP backends, and AWS services through
AWS service integrations.
● Simplified Proxy: HTTP APIs are optimized for use cases where you simply proxy requests to a
backend service without the need for extensive transformation or validation.
● Pricing: Generally cheaper than REST APIs, with lower request pricing and no additional
charges for features like caching or data transformation.
3. Limitations:
● Limited Features: HTTP APIs do not support advanced features such as request/response
validation, API keys, usage plans, caching, or the full set of custom authorizers available in REST
APIs.
● Customizable Throttling: Limited to simple rate limiting and burst control.
4. Use Cases:
● Building simple APIs for proxying requests to Lambda or other HTTP backends.
● Lightweight services where you need minimal features and lower latency.
● Cost-sensitive applications that do not require the advanced features of REST APIs.
REST API
1. Purpose:
● Comprehensive Features: REST APIs are designed for complex and enterprise-grade use
cases that require advanced features and fine-grained control over API behavior.
● Full Control: REST APIs provide a full set of API Gateway features, making them suitable for
more sophisticated API scenarios.
2. Features:
● Advanced Features: REST APIs support features like API keys, usage plans, request and
response validation, custom authorizers (including Lambda and Cognito authorizers), and stage
variables.
● Transformation and Validation: REST APIs offer extensive capabilities for request and
response transformation using mapping templates, and the ability to validate incoming requests
against models.
● Caching: Supports response caching, which helps reduce backend load and improve API
performance by caching responses for a configurable duration.
● Stages and Deployments: REST APIs support multiple stages (e.g., dev, test, prod), enabling
you to manage different versions or environments of your API.
● Monitoring and Logging: Enhanced logging and monitoring capabilities, including access logs
and integration with CloudWatch for detailed tracking of API performance.
3. Limitations:
● Higher Latency: Due to the richer feature set, REST APIs tend to have slightly higher latency
compared to HTTP APIs.
● Complexity: The configuration and management of REST APIs can be more complex, requiring
more setup and maintenance effort.
● Cost: Generally more expensive than HTTP APIs, with additional charges for features like
caching, transformation, and validation.
4. Use Cases:
Summary
● HTTP APIs: Best for simple, low-latency, and cost-effective APIs where advanced features like
transformation, validation, and complex authorization are not required. Ideal for building
lightweight microservices and proxying requests to Lambda functions or HTTP backends.
● REST APIs: Best for complex APIs that require advanced features, extensive customizability, and
fine-grained control over API behavior. Suitable for enterprise applications, scenarios requiring
sophisticated authorization, monitoring, and transformation, and when multiple stages or
environments need to be managed.
Choosing between HTTP APIs and REST APIs depends on your specific requirements in terms of
features, performance, complexity, and cost.
Here are examples of REST API endpoints using all the main HTTP verbs (GET, POST, PUT, PATCH,
DELETE). These examples are based on a typical CRUD (Create, Read, Update, Delete) operations for
managing resources, such as users in a system.
Resource: Users
Base URL: https://api.example.com/users
Nested resources are common in REST APIs, especially when modeling hierarchical or related data.
Here’s an example that extends the previous scenario to demonstrate accessing nested resources, such
as orders within users.
PUT Method
● Purpose: The PUT method is used to update an existing resource or create a resource if it does
not exist. It typically requires the full representation of the resource being updated or created.
● Idempotency: PUT is idempotent, meaning that making the same PUT request multiple times will
have the same effect as making it once. This means that if you PUT the same resource twice, the
second request won’t change anything, assuming the resource hasn’t changed between
requests.
● Request Structure: When using PUT, you generally send the entire updated resource in the
request body. This means you need to include all fields, even if only some of them are being
updated.
Example:
● Suppose you have a user resource with id, name, and email fields.
● Endpoint: PUT /users/1
● Request Body
{ "id": 1, "name": "John Doe", "email": "[email protected]" }
● Effect: This request will update the user with id 1. If the user does not exist, PUT might create it
(depending on the API design). If you omit any field, it may either set the field to null or use a
default value.
PATCH Method
● Purpose: The PATCH method is used to apply partial updates to a resource. It is designed to
update only the fields that are provided in the request body, leaving the rest of the resource
unchanged.
● Idempotency: While PATCH is not strictly idempotent according to the HTTP specification, in
practice, many PATCH operations are designed to be idempotent in the same way as PUT.
However, depending on the implementation, applying the same PATCH request multiple times
may not always result in the same state as applying it once.
● Request Structure: When using PATCH, you send only the fields that need to be updated in the
request body. This means that you can update just one or a few fields of the resource without
having to send the entire resource representation.
Example: