Amazon API Gateway

Learn via video courses
Topics Covered

Overview

AWS API gateway is a mechanism for managing APIs that lie between a client and a set of backend services. An API gateway works as a reverse proxy, accepting all API calls, aggregating the different types of services required to complete them, and delivering the precise outcome.

What is AWS API Gateway?

AWS API Gateway allows you to create, publish, maintain, monitor, and secure REST, HTTP, and WebSocket APIs at any scale. API developers can construct APIs that allow users to access AWS services (or) data stored in the AWS Cloud.

API Gateway develops RESTful APIs that do the following: • They are HTTP-based. • Make stateless, client-server communication possible. • Use HTTP standard methods like GET, POST, PUT, PATCH, and DELETE.

API Gateway develops WebSocket APIs for: • Use the WebSocket protocol, which allows for stateful, full-duplex communication between client and server. • Handle incoming messages based on their content.

API Types

AWS API Gateway provides two choices for creating RESTful APIs: HTTP APIs and REST APIs, as well as a WebSocket API option.

Use API Gateway to create REST APIs

A REST API from AWS API Gateway is made up of resources and methods. A resource is a logical object that can be accessed by an app via a resource route. A method relates to a REST API request sent by an API user and the response delivered to the user.

For example, incomes may be the link to a resource indicating the app user's income. A resource can have one (or) more actions specified by HTTP verbs like GET, POST, PUT, PATCH, and DELETE. A method of the API is identified by the combination of a resource route and an operation. A POST /incomes method, for example, may add an income made by the caller, and a GET / expenditures method could query the reported costs incurred by the caller.

The app needs to know about the location of requested data retrieved from the backend. The front end of API Gateway REST APIs is contained by method requests and method replies. The API communicates with the backend via integration requests and answers.

For example, if DynamoDB is used as the backend, the API developer configures the integration request to route the incoming method request to the selected backend. The configuration comprises specs for necessary DynamoDB action, the Identity and Access Management (IAM) role and policies, and input data transformation.

API Gateway offers REST API administration features such as the following:

  • API Gateway extensions are used to generate SDKs and create API documentation.
  • HTTP request throttling

Use AWS API Gateway to create HTTP API

HTTP APIs allow you to construct RESTful APIs that are cheaper in latency and cost than REST APIs. HTTP APIs can be used to deliver queries to AWS Lambda functions (or) any public routable HTTP endpoint. For example, you can build an HTTP API that interfaces with a Lambda function on the backend. When a client makes a request, API Gateway forwards the request to the Lambda function and delivers the function's response to the client. HTTP APIs allow authorization using OpenID Connect and OAuth 2.0. They include cross-origin resource sharing (CORS) and automated deployment support.

Use AWS API Gateway to create WebSocket API

The client and server in a WebSocket API can send messages to each other at any time. Backend servers can simply send data to connected users and devices, eliminating the need for complicated polling systems to be implemented.

For example, you can create a serverless application that uses an API Gateway WebSocket API and AWS Lambda to send and receive messages in a chat room from individual (or) groups of users. Alternatively, you use message content to trigger backend services such as AWS Lambda, Amazon Kinesis, (or) an HTTP endpoint.

API Gateway WebSocket APIs are used to create secure, real-time communication apps without the need to deploy (or) operate any servers to manage connections.

Real-time applications such as the following are among the targeted use cases:

  • Chat apps.
  • Real-time dashboards with stock tickers.
  • Notifications and alerts in real-time.

API Gateway offers WebSocket API administration features such as the following:

  • Connection and message monitoring and throttling.
  • Using AWS X-Ray to track messages as they pass via APIs and reach backend services.
  • Straightforward interaction with HTTP/HTTPS endpoints.

Benefits

  • Efficient API development You can run many iterations of the same API simultaneously using AWS API Gateway, allowing you to quickly test, develop, and deploy new versions. You just pay for API calls and data transfers; there are no minimum prices or up-front commitments.
  • Available at Every Scale Utilize the global network of edge sites that Amazon CloudFront offers to give end users the least amount of delay for API requests and responses. To guarantee that backend operations can withstand traffic surges and that backend services are not contacted needlessly, throttle traffic, and approve API requests.
  • Cost reductions on a large scale For API queries, API Gateway offers a tiered price plan. With an API Requests pricing of $0.90 per million requests at the highest tier, you may reduce your expenditures as your API usage per region rises across your AWS accounts.
  • Simple Monitoring The AWS API Gateway dashboard, which allows you to visually monitor calls to your services using Amazon CloudWatch, displays performance metrics and statistics on API calls, data latency, and error rates.
  • Adaptable Security Controls To give access to your APIs, use Amazon Cognito with AWS Identity and Access Management (IAM). If you utilize OAuth tokens, API Gateway supports both OIDC and OAuth2. You may use AWS Lambda to execute a Lambda authorizer to satisfy bespoke authorization needs.
  • Options for RESTful APIs RESTful APIs may be created using HTTP APIs or REST APIs. HTTP APIs are the most cost-effective option to construct APIs for the vast majority of use cases, costing up to 71% less than REST APIs. REST APIs can be used if your use case necessitates API proxy capability as well as administration functions in a single solution.

Architecture of API Gateway

The architecture of API Gateway is shown in the figure below.

architecture-of-api-gateway

The APIs that you create in AWS API Gateway give you (or) your developer clients a unified and consistent development environment for creating AWS serverless apps, as shown in the figure above. Up to hundreds of thousands of API requests can be accepted and processed simultaneously by API Gateway. These duties include managing traffic, controlling access and authorization, and Monitoring and managing API versions.

Apps such as workloads running on Amazon Elastic Compute Cloud (Amazon EC2), code running on AWS Lambda, any web application, (or) real-time communication applications can access data, business logic, (or) functionality from your backend services using API Gateway.

Features of API Gateway

Features that Amazon API Gateway provides include the following:

  • Support for stateless (HTTP and REST) and stateful (WebSocket) APIs. You may develop RESTful APIs with AWS API Gateway by utilizing either HTTP APIs or REST APIs. HTTP APIs are the most effective technique for creating APIs that do not require API management tools. HTTP APIs are tailored for serverless workloads and HTTP backends, offering up to 71% cost savings and 60% latency reduction when compared to API Gateway REST APIs. API Gateway provides REST APIs for workloads that require API proxy capability and API administration capabilities in a single solution, such as consumption plans and API keys.
  • AWS ELB and AWS Cloud Map private integrations You may use API Gateway to redirect requests to private resources in your VPC. APIs for services behind private Application Load Balancer (ALBs), private Network Load Balancer (NLBs), and IP-based services registered in AWS Cloud Map, such as ECS tasks, may be built using HTTP APIs.
  • Resiliency API Gateway assists you in managing traffic to your backend systems by allowing you to create throttling rules depending on the number of HTTP methods in your APIs. API Gateway manages any level of traffic received by an API, allowing you to focus on your business logic and services rather than infrastructure maintenance. If you're utilizing REST APIs, you can also set up a cache for your API data with adjustable keys and time-to-live in seconds to prevent hitting your backend services with each request.
  • Simple API Development and Deployment You can use API Gateway to quickly and simply construct a custom API to your AWS Lambda code and then call the Lambda code from your API. API Gateway can run AWS Lambda code in your account, launch AWS Step Functions state machines, or make calls to AWS Elastic Beanstalk, Amazon EC2, or web services not hosted by AWS via publicly available HTTP endpoints.
  • Operation Monitoring for APIs API Gateway gives you a dashboard to visually track calls to the services when an API is deployed and in use. You can view backend performance data such as API calls, latency, and error rates since the API Gateway dashboard is connected to Amazon CloudWatch. You may create unique alerts on API Gateway APIs since API Gateway records monitoring information using CloudWatch.
  • AWS Certification API Gateway can let you employ signature version 4 for REST APIs and WebSocket APIs to authorize and validate API calls to AWS services. You may use AWS Identity and Access Management (IAM) and access policies to permit access to your APIs and other AWS services while using signature version 4 authentication.
  • Third-Party Developer API Keys API Gateway assists you in managing the ecosystem of third-party developers that access your REST APIs. On API Gateway, you may generate API keys, assign fine-grained access rights to each API key, and distribute them to third-party developers to allow them to access your APIs. You may also create plans that include throttling and request quotas for each API key.
  • SDK Development When leveraging REST APIs, API Gateway can produce client SDKs for a variety of platforms, allowing you to quickly test new APIs from your apps and provide SDKs to third-party developers. Client SDKs for Java, JavaScript, Java for Android, Objective-C or Swift for iOS, and Ruby may be generated using API Gateway.
  • API Lifecycle Administration If you use REST APIs, API Gateway allows you to run many versions of the same API at the same time, allowing apps to continue using earlier API versions even after the latest ones are published. API Gateway also assists you in managing several release phases, such as alpha, beta, and production, for each API version.

Accessing API Gateway

You can choose the following methods to access Amazon API Gateway:

The web interface for maintaining and developing APIs is provided via the AWS Management Console. You may access the API Gateway console via the link to get started with AWS API Gateway.

  • AWS SDKs You can use an SDK to access API Gateway if you're using a programming language for which AWS offers an SDK. The use of API Gateway commands is made possible by SDKs, which also make authentication simple and integrate well with your development environment. Visit Tools for Amazon Web Services for further details.
  • API Gateway V1 and V2 APIs Consult the Amazon API Gateway Version 1 API Reference and Amazon API Gateway Version 2 API Reference if you're using a programming language for which an SDK isn't available.
  • AWS Command Line Interface In the AWS Command Line Interface User Guide, go to Getting Set Up with the AWS Command Line Interface for further details.
  • AWS Tools for Windows PowerShell In the AWS Tools for Windows PowerShell User Guide, go to Setting Up the AWS Tools for Windows PowerShell for further details.

Getting Started with AWS API Gateway

Step 1: Create a Lambda Function

For the API's backend, you utilize a Lambda function. Lambda is scalable automatically from a few requests per day to thousands per second, only running your code when it is required. You utilize the standard Node.js function from the Lambda interface for this example.

Creating a Lambda function

  1. Go to the link to log in to the Lambda console.
  2. Select the Create option.
  3. Type my function as the function name, API Gateway for Amazon Developers, and create an HTTP API.
  4. Select the Create option. The sample function returns the string Hello from Lambda! Along with a 200 response code to clients. You can change your Lambda function as long as the answer complies with API Gateway's specifications. The default Lambda function code should look something like this:

default-lambda-function-code

Step 2: Create an HTTP API

You then develop an HTTP API. API Gateway also supports REST APIs and WebSocket APIs. However, for this exercise, an HTTP API is the best option. REST APIs provide more functionalities than HTTP APIs, although such characteristics are not required for this activity. Your Lambda function will have an HTTP endpoint because of HTTP API. Clients are routed to your Lambda function through API Gateway, which subsequently returns the function's answer.

  • To develop an HTTP API
  1. Go to the link to access the API Gateway console.
  2. One of the following steps should be taken: • Select Build for HTTP API to construct your first API. • If you've previously developed an API, choose to Create API and then Build for HTTP API.
  3. Select Add integration from the Integrations menu.
  4. Select Lambda.
  5. Type my-function in the Lambda function field.
  6. Enter my-http-api as the API name.
  7. Select Next.
  8. Examine the path that API Gateway generates for you, then click Next.
  9. Examine the stage that API Gateway has created for you, and then click Next.
  10. Select Create.

Step 3: Test Your API

After that, you test your API to ensure that it is operational. To make things easier, utilize a web browser to access your API. To evaluate your API

  1. Go to the link to access the API Gateway console.
  2. Select your API.
  3. Take note of your APIs to invoke URLs.

api-to-invoke-url

  1. Copy the invoke URL of your API and paste it into a web browser. To invoke your Lambda function, include the name of your Lambda function in your invoke URL. By default, the API Gateway interface generates a route called my-function, which is the same name as your Lambda function. The whole URL should be "https:// abcdef123.execute-api.useast-2.amazonaws.com/my-function". The API receives a GET request from your browser.
  2. Check the response from your API. In your browser, you should see the sentence "Hello from Lambda!"

Step 4: Clean Up

Delete the resources you established as part of this getting started activity to avoid extra charges. The procedures below will destroy your HTTP API, Lambda function, and all associated resources. To uninstall an HTTP API

  1. Go to the link to access the API Gateway console.
  2. Choose an API from the APIs page. Select Actions, and then Delete.
  3. Select Delete.

To get rid of a Lambda function

  1. Access the Lambda console by going here.
  2. Choose a function from the Functions page. Select Actions, and then Delete.
  3. Select Delete.

To remove a log group from a Lambda function

  1. Navigate to the Log groups page in the Amazon CloudWatch dashboard.
  2. On the Log groups page, pick the log group for the function (/aws/lambda/my-function). Select Actions, and then Delete the log group.
  3. Select Delete.

To remove the execution role of a Lambda function

  1. Navigate to the Roles page in the AWS Identity and Access Management interface.
  2. Choose the function's role, such as my-function-31exxmpl.
  3. Select the Delete role option.
  4. Select Yes, delete.

Pricing

You are only charged when your APIs are utilized through Amazon API Gateway. There are no mandatory minimum expenses (or) requirements. When using HTTP and REST APIs, you only pay for the API calls you get and the amount of data you send out. Private APIs have no data transfer costs. When utilizing Private APIs in API Gateway, however, AWS PrivateLink costs apply. API Gateway also offers optional data caching at an hourly cost that varies depending on the cache size you choose.

  • Free Tier 1: For up to 12 months, the Amazon API Gateway free tier offers one million REST API requests, one million HTTP API calls, one million messages, and 750,000 connection minutes for WebSocket APIs. You will be charged the API Gateway use fees if you make more than this amount of calls each month.
  • Cost of HTTP APIs: User pay just for the API calls they make and the quantity of data they send. For HTTP APIs, the API Gateway free tier includes one million API requests every month for up to 1 year.
  • Cost of REST APIs: It charges you just for the API calls you make and the quantity of data you send. Private APIs have no data transmission fees. However, AWS PrivateLink fees apply during the utilization of Private APIs in AWS API Gateway. AWS API Gateway also offers optional data caching at an hourly cost that varies depending on the specified cache size. For REST APIs, the API Gateway free tier allows one million API requests every month for up to 1 year.
  • Cost of WebSockets APIs: Users pay only for messages sent and received, as well as total connection minutes. Messages of up to 128 kilobytes (KB) in size can be sent and received. Messages are metered in increments of 32 KB. As a result, communication of 33 KB is metered as two messages.

Conclusion

  • AWS API Gateway provides two choices for creating RESTful APIs: HTTP APIs and REST APIs, as well as a WebSocket API option.
  • AWS API Gateway provides a quick and simple option to construct a custom API to your AWS Lambda code and then call the Lambda code from your API.
  • AWS API Gateway assists you in managing traffic to your backend systems by allowing you to create throttling rules depending on the number of HTTP methods in your APIs.
  • The AWS API Gateway dashboard, which allows you to visually monitor calls to your services using Amazon CloudWatch, displays performance metrics and statistics on API calls, data latency, and error rates.
  • You are only charged when your APIs are utilized through Amazon API Gateway. There are no mandatory minimum expenses (or) requirements. When using HTTP and REST APIs, you only pay for the API calls you get and the amount of data you send out.