0% found this document useful (0 votes)
50 views21 pages

5 - Api Gateway

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views21 pages

5 - Api Gateway

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Module 5: Amazon API Gateway

Introduction to Amazon 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.

API Gateway endpoints are typically structured as follows:

https://{api-id}.execute-api.{region}.amazonaws.com/{stage}/{resource}

Where:

● {api-id}: The unique identifier for your API.


● {region}: The AWS region where your API is hosted.
● {stage}: The deployment stage of your API (e.g., dev, test, prod).
● {resource}: The resource path that you define in your API.

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.

3. API Stages and Deployment

● 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).

4. Security and Authorization

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.

Getting Started with Amazon API Gateway

Here’s a step-by-step guide to getting started with Amazon API Gateway:

Step 1: Creating a REST API

1. Log in to the AWS Management Console:


○ Navigate to the Amazon API Gateway service.
2. Create a New API:
○ Click on "Create API".
○ Choose "REST API" and then select "Build".
○ Choose an API type: "HTTP API" for lightweight APIs or "REST API" for fully-featured
APIs.
○ Enter an API name and description.
○ Click "Create API".

Step 2: Define Resources and Methods

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.

Step 3: Deploy the API

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.

Step 4: Secure and Monitor 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.

Step 5: Versioning and API Lifecycle Management

1. Create New Versions:


○ As you make updates to your API, you can create new versions or stages to manage the
API lifecycle.
○ Deploy new versions to different stages for testing or production use.
2. Documentation and SDK Generation:
○ Generate API documentation and SDKs (Software Development Kits) for client
developers to integrate with your API.
○ Use the built-in documentation editor to provide details on API usage, methods, and
parameters.

Advanced Features and Use Cases


Caching:

● 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.

Throttling and Rate Limiting:

● 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.

Cross-Origin Resource Sharing (CORS):


● Enable CORS on your API to allow cross-domain requests from browsers, which is essential for
web applications that interact with your API from different domains.

API Gateway WebSocket APIs:

● 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.

Integrating with Other AWS Services:

● 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.

Difference between HTTP Api and REST Api:


Amazon API Gateway offers two main types of APIs: HTTP APIs and REST APIs. While they both allow
you to create, deploy, and manage APIs, they serve different use cases and offer different features.
Here’s a detailed comparison between HTTP APIs and REST APIs in AWS API Gateway:

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:

● Enterprise-grade applications requiring robust security, monitoring, and management features.


● Scenarios where you need to enforce fine-grained access control using API keys, usage plans, or
custom authorizers.
● APIs that require request and response validation, transformation, or caching for optimization.

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.

Sample REST endpoints

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

1. GET: Retrieve a Resource


1.1 Retrieve a List of Users

● Endpoint: GET /users


● Description: Fetches a list of all users in the system.
● Example Request:
1.2 Retrieve a Single User by ID

● Endpoint: GET /users/{id}


● Description: Fetches the details of a single user by their ID.
2. POST: Create a New Resource
● Endpoint: POST /users
● Description: Creates a new user in the system.
● Example Request:

3. PUT: Update an Entire Resource


● Endpoint: PUT /users/{id}
● Description: Updates the entire user resource, typically replacing all fields.
4. PATCH: Update Part of a Resource
● Endpoint: PATCH /users/{id}
● Description: Updates part of the user resource, typically one or more fields.
5. DELETE: Remove a Resource
● Endpoint: DELETE /users/{id}
● Description: Deletes a user from the system.

Summary of REST Endpoints

HTTP Verb Endpoint Description

GET /users Retrieve a list of users


GET /user/{id} Retrieve a specific user by ID

POST /user Create a new user

PUT /user/{id} Update an entire user resource

PATCH /user/{id} Partially update a user resource

DELETE /user/{id} Delete a user from the system

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.

Resource: Users and Orders


Base URL: https://api.example.com/users

1. GET: Retrieve Nested Resources


1.1 Retrieve All Orders for a Specific User

● Endpoint: GET /user/{userId}/orders


● Description: Fetches all orders placed by a specific user.
1.2 Retrieve a Specific Order for a Specific User

● Endpoint: GET /user/{userId}/order/{orderId}


● Description: Fetches the details of a specific order placed by a specific user.
2. POST: Create a Nested Resource
2.1 Create a New Order for a Specific User

● Endpoint: POST /user/{userId}/order


● Description: Creates a new order for a specific user.
3. PUT: Update a Nested Resource
3.1 Update an Entire Order for a Specific User

● Endpoint: PUT /user/{userId}/order/{orderId}


● Description: Updates the entire order for a specific user.
4. PATCH: Partially Update a Nested Resource
4.1 Update Specific Items in an Order for a Specific User

● Endpoint: PATCH /users/{userId}/orders/{orderId}


● Description: Partially updates an order for a specific user.
5. DELETE: Remove a Nested Resource
5.1 Delete a Specific Order for a Specific User

● Endpoint: DELETE /users/{userId}/orders/{orderId}


● Description: Deletes a specific order placed by a user.

Summary of Nested Resource Endpoints

HTTP Verb Endpoint Description

GET /user/{userId}/orders Retrieve all orders for a specific user

GET /user/{userId}/orders/{orderId} Retrieve a specific order for a specific user

POST /user/{userId}/orders Create a new order for a specific user

PUT /user/{userId}/orders/{orderId} Update an entire order for a specific user

PATCH /user/{userId}/orders/{orderId} Partially update an order for a specific user

DELETE /user/{userId}/orders/{orderId} Delete a specific order for a specific user

Difference Between PUT and PATCH in RESTful APIs


In RESTful APIs, both PUT and PATCH are HTTP methods used to update resources, but they are used in
slightly different ways and have distinct semantics.

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:

● Endpoint: PATCH /users/1


● Request Body
{ "email": "[email protected]" }
● Effect: This request will update only the email field of the user with id 1, leaving other fields like
name unchanged.

When to Use Each


● Use PUT:
○ When updating the entire resource.
○ When you want to ensure that the resource on the server matches exactly what you
send.
● Use PATCH:
○ When updating only specific fields of a resource.
○ When you need to make partial changes without affecting other parts of the resource.
REFERENCES:

● Hindi video for what is API


https://youtu.be/XGa4onZP66Q

● API English Video


What is an API and how does it work? (In plain English) (youtube.com)
https://youtu.be/ByGJQzlzxQg
● REST API
What is a REST API?

● Difference between REST and HTTP API


https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html

You might also like