To access data, business logic, and functionalities from backend services, an API can serve as an interface. API Gateway facilitates two-way communication in real-time applications, making it a crucial component for various development domains, including mobile app development and software testing, web development services, custom financial software development, iOS mobile app development, and software development in healthcare. This article delves into Amazon API Gateway, exploring its architecture, key concepts, use cases, and features, particularly its relevance in web applications, real-time chat applications, and streaming applications. A practical demonstration involves creating an API Gateway, integrating it with the AWS Lambda service, and obtaining the endpoint URL for consumption in client-side code.
What is an API?
API, short for Application Programming Interface, acts as a software intermediary enabling communication between two applications. For instance, using an app like Facebook, sending instant messages, or checking the weather on a mobile phone involves utilizing an API.
When interacting with a mobile application, the app connects to the Internet, sends data to a server, and receives interpreted data in return. The server processes the data, performs necessary actions, and sends the results back to the app. This entire process relies on an API.
To illustrate, consider a restaurant scenario:
You’re at a table with a menu, and the kitchen prepares your order. What’s missing is the link to convey your order to the kitchen and bring the food back to your table. The waiter, analogous to an API, acts as the messenger, relaying your request to the kitchen (system) and delivering the response—in this case, the food—back to you.
The client employs various HTTP methods for server communication:
GET (for reading)
POST (for inserting data)
PUT (for updating data)
DELETE (for deleting data)
Introduction to Amazon API Gateway
Lambda, a serverless service, can utilize DynamoDB as a database for the API. Clients can invoke the Lambda function directly with proper IAM permissions, use an Application Load Balancer (ALB) between the client and Lambda, or employ an API Gateway. The API Gateway, a serverless AWS service, facilitates the creation of public, accessible REST APIs. Clients interact with the API Gateway, which then proxies requests to the Lambda function, offering more than just an HTTP endpoint, including features such as authentication, usage plans, and development stages.
Amazon API Gateway Architecture & Key Concepts
To comprehend the architecture, components include:
Client: Mobile, web, or other services.
Types of API Based on Endpoints:
Integration: Connects routes to backend resources, supporting various integrations like Lambda function, HTTP, Mock, AWS Services, and VPC Link.
API Endpoint: The hostname, formatted as <<api-id>>execute-api.<<region>>.amazonaws.com.
Features of Amazon API Gateway
Integration with Lambda for a fully serverless architecture.
Support for stateful (WebSocket) and stateless (HTTP and REST) APIs.
Robust authentication mechanisms through AWS IAM Roles and Policies, Amazon Cognito User Pools, and Custom Authorizer.
Canary release development for seamless updates.
Monitoring API usage via CloudTrail and logs through CloudWatch with settable alarms.
Integration with Web Application Firewall (WAF) and AWS X-Ray.
Three deployment options
Edge-optimized (default): Accessible globally via CloudFront Edge locations for improved latency.
Regional: Limited to a specific region without using CloudFront Edge locations, allowing more control over caching strategies.
Private: Accessible only within the VPC using interface VPC endpoints, governed by a resource policy.
Types of Amazon API Gateway
Low latency and cost, currently lacking API management functionality.
Offers API management features like usage plans, API keys, publishing, and monetization.
Maintains persistent connections for real-time message communication.
API Gateway REST API:
The full-featured flagship service for building REST APIs with user/tenant-based throttling capabilities.
API Gateway HTTP API:
A modern alternative to REST APIs, promising lower latency, reduced costs, and an improved user experience.
API Gateway WebSocket API:
Event-driven API enabling bidirectional communication between client and server.
The table below provides a comprehensive comparison between REST API and HTTP API, allowing developers to choose based on specific requirements.
Benefits of API Gateway
Challenge: Renaming or moving services becomes challenging when clients communicate directly with multiple separate services.
Solution: API gateways enable routing based on path, hostname, headers, etc., allowing decoupling of publicly facing API endpoints from the microservice architecture.
Reduce Round Trips:
Challenge: Certain API endpoints require joining data across multiple services, leading to complicated call chaining and increased round trips.
Solution: API gateways perform data aggregation, simplifying client interactions and reducing the number of round trips.
API gateways act as a centralized proxy server, managing rate limiting, bot detection, authentication, CORS, etc.
Many API gateways support setting up a datastore, such as Redis, for session information storage.
Logging, caching, and other cross-cutting concerns can be handled centrally, avoiding deployment to every microservice.
Moesif provides plugins for various API gateways like Kong and Tyk, offering modern customer and API analytics without requiring SDK installations.
Use Cases of Amazon API Gateway
UK Driver & Vehicle Licensing Agency (DVLA):
DVLA employs an API-based approach for more than a decade, handling over 50 million vehicle-licensing transactions annually.
With records on every UK vehicle, DVLA is a crucial source of public information.
An online photography platform under Vogue Italia, PhotoVogue launched in 2011 to showcase upcoming photographers.
AWS Lambda and AWS Gateway implementation reduced IT costs by 30% and increased operating speed by 90%.
In the realm of QA software testing services and custom financial software development, API Gateway proves invaluable for decoupling, reducing round trips, and managing security concerns. It is particularly advantageous for banking software development companies and those engaged in custom enterprise software development.
API Gateway and Lambda Integration:
Login to AWS, navigate to Amazon API Gateway, and create a new API.
Create a Rest API from the API Gateway console.
Create a Get Method and integrate it with Lambda.
Create Lambda functions for CRUD operations, interacting with DynamoDB.
Client-Side Code Integration:
Use the generated API Gateway endpoint URL in the client-side code.
The API Gateway proxies requests to the appropriate Lambda function based on the resource in the endpoint URL.
This URL is utilized in client-side code to consume services via REST API.
AWS account Access:
Access your AWS account and go to the API Gateway dashboard for the creation of a new API. You’ll encounter various options to create an API, and you can select the most suitable one according to your needs. For simplicity, we will opt for creating a Rest API; hence, click on ‘Build’ within that category.
Enter the name for your API based on your preference.
In the Actions dropdown, choose ‘Create Method,’ and then opt for the GET method. It’s possible to create various methods like POST, DELETE, GET, etc. However, for simplicity, we are utilizing the GET method in this case.
In this context, we are integrating with a new Lambda function. Choose the Integration type as ‘Lambda Function,’ and opt for ‘Use Lambda Proxy Integration’ since it enables the client to invoke a single Lambda function in the backend.
Before moving forward in this step, it’s essential to assign a name to the Lambda function. Let’s initiate the process by creating a Lambda function.
Open a new tab in the console, navigate to the Lambda function, and click on ‘Create function.’
Provide the suitable name for the Lambda function, and in this instance, we are specifying the Runtime as Python 3.8. You can opt for any runtime based on your needs. Subsequently, click on the ‘Create Function’ button.
Implement Function Code
In the “Function code” segment, insert the following handler code for the function. The body will be invoked from the API Gateway endpoint URL. It’s also possible to retrieve the status code and headers, logging them in CloudWatch logs. For now, we will omit reviewing the CloudWatch logs. However, during the testing phase of the API Gateway call, we will examine the complete response with all details.
After putting the code, click on Deploy and then click on Test. Put an Event name and then click on ‘Create’
At the top of the screen, we must see the response and below:
Now, coming back to our first tab where we created our API Gateway’s GET method.
Put the lambda function name that we just created and click on ‘Save’.
Process To Test
Now, we can test our integration by clicking on TEST
We should now see the response that is getting called from our Lambda Function.
So, we have our API Gateway triggering Lambda function.
Now, similarly, we can create resource inside our GET method for the data to be called from sub-paths
We have created a resource called ‘states’. You can use it as per your requirement. Once done, click on ‘Create Resource’
Now, again we will create a method for this New Resource ‘states’ and integrate it with a new Lambda function.
As shown above, create a new Lambda function with the same steps as shown above and put the appropriate code inside the Lambda function handler.
Once we are done till here, we can test this method also by clicking on ‘TEST’.
Now, to consume these methods, we can have an HTTP endpoint, which we can call from client side code. To do that, in the Action dropdown, click on ‘Deploy API’.
As we can see, we have now got an Invoke URL from AWS.
Copy that URL and try calling it from the browser. We should get the response from the Lambda function that is being triggered by our API Gateway.
Also, test the URL by putting /states in the URL for testing the sub resource that we created above.
If we try to invoke any other resources which do not exist, we would get the below error.
This blog highlights the role of the API Gateway in seamlessly integrating client-side code with the AWS cloud network. Throughout this practical guide, we employed the Lambda function as a trigger, although it is worth noting that API Gateway can be utilized in conjunction with various other AWS services. Future posts will delve deeper into the API Gateway and explore additional implementations. Stay connected to receive timely updates on our upcoming blogs covering AWS and related technologies.
Get a Fast Estimate on Your Software Development Project
We are committed to delivering high-quality IT solutions tailored to meet the unique needs of our clients. As part of our commitment to transparency and excellence, we provide detailed project estimations to help our clients understand the scope, timeline, and budget associated with their IT initiatives.