Imagine a complex web application where all the essential functions are implemented internally, in its body. Such a situation often leads to providing the app with direct access to the database or file storage.
As a result, if you would like to, for instance, authenticate a user, the application will query the database with a set of user and password hashes and possibly a set of privileges for that user to get an authentication response. If now you need to make another application available to your customer and allow them to authenticate with the same credentials, you’ll have to implement the same code fragment responsible for authentication in the new app.
The same applies to any repeatable function, such as product catalog or customer service. If you want to create a mobile client for your application, you have to find a way to provide it with secure access to backend services.
Let’s see it in a diagram.
At first glance, something is missing; an intermediate service that would grab all communication requests between clients on the left and services on the right and process them in a single point. Our missing piece is API.
Application Programming Interface (API) is a set of methods of communication between various software components. By now, APIs have become an integral part of modern application design. They are even more significant nowadays as a natural way of communication between the increasingly popular microservices.
Let’s compare the above image with the one below, with implemented API.
There are multiple API platforms available on the market, but since we use AWS, the easiest way to create APIs for your cloud application is to leverage an AWS native service, called – yes, you’ve guessed it, Amazon API Gateway.
What is Amazon API Gateway?
Amazon API Gateway is a fully managed service that enables you to create, configure, and host a RESTful API that allows applications to access the AWS Cloud.
You can think of it as a backplane in the cloud used to connect AWS services and other public or private websites.
An application gains access to AWS services through one or more APIs hosted in API Gateway. Services are placed behind, at the API’s backend, while the application is the API’s frontend.
How does API Gateway work?
To access the backend through an API, an app developer has to use a method request. It is a public interface of an API method in API Gateway that defines parameters and the body, which are then mapped into formats required by the backend and sent to the backend as integration request. The backend replies with the integration response including the status codes, headers, and payload. API Gateway returns these values as method response. Let’s see that flow in action using an example showing API integration with a simple Lambda function.
First, the client invokes the API in the Method Execution section; a process that you can test from the console by pressing the [TEST] button.
The image below shows the execution flow of a request coming from the client.
Once invoked, the request passes to the Method Request section. Here, you select the parameters you would like to receive as input.
Parameters can be anything you can pass to the gateway, for instance, URL query string parameters, HTTP Request Headers, or Request Body. Parameters determine your input. If you want to pass a name to the API, you can configure a parameter name as a URL Query String Parameter:
Then, the request passes on to the Integration Request section where it is mapped in the JSON format expected by the Lambda function.
Mapping to JSON means that you have to build a JSON object with keys and values equal to the parameters passed to API Gateway.
For instance, you can map the name parameter mentioned above to the name object key in JSON using the $input.params() function.
Once you finish mapping all parameters, proceed to backend implementation. In this case, we’re implementing a Lambda function.
The Integration Response section extracts and maps the backend response to different HTTP return statuses and formats. In this section, for example, you can map an error returned by the backend to standard HTTP error codes such as HTTP 5xx.
You may use the $input.path(‘$’) function to map the full response to the JSON object key.
The example uses no Regex function, therefore any response will return the status HTTP200 OK. A JSON object will also be created with the response body as the greeting key in the JSON object.
Finally, the Method Response section presents the method response of a given HTTP status code returned to the client.
Here is the test result of the example function:
Once the API is created, it has to be deployed. You can select a stage you wish to deploy it to, and complete the deployment. When it finishes, you will see the API in the Stages menu.
Staging is an essential element of Continuous Integration/Delivery pipelines. API Gateway supports staging and versioning so that developers can keep dedicated endpoints for testing, staging, and production.
API Gateway integration
The above example shows API integration with a simple Lambda function, but API Gateway offers much more than just that.
You can also create an API Gateway API to expose other AWS services, such as Amazon SNS, Amazon S3, Amazon Kinesis, and even AWS Lambda. API Gateway can act as a proxy for these services, allowing you to expose controlled access to your AWS services through API, and becoming a unified frontend for all inbound API calls.
Managing API access with Amazon API Gateway
API Gateway supports multiple mechanisms of access control:
- API Gateway Resource Policies
- IAM Permissions
- Enabling CORS
- Lambda Authorizers
- Amazon Cognito User Pools
- Client-Side SSL Certificates
- API Gateway Usage Plans
API Gateway Resource Policies
Amazon API Gateway Resource Policies are JSON policy documents attached to API to control whether a specified principal (typically an IAM user or role) can invoke the API. You can use the policies to allow users from different AWS accounts to securely access your API or to permit the API to be invoked only from specified source IP address ranges or CIDR blocks.
IAM Permissions are standard IAM access controls. An API developer must have appropriate permissions to be able to create, deploy and manage APIs, call a deployed API, or refresh API caching. An API caller needs relevant permissions to perform required IAM actions supported by the API execution component of API Gateway.
CORS (Cross-origin resource sharing)
The CORS mechanism is required to enable APIs receiving requests from domains other than the API’s domain. To learn how to enable it for Amazon Gateway API, go to the official AWS documentation.
Amazon API Authorizer (custom authorizer)
Formerly known as the custom authorizer, this is a Lambda function that you provide to control access to your API methods. Go to the official AWS documentation for more details.
Amazon Cognito User Pools
You can use Amazon Cognito User Pools in addition to IAM permissions and Lambda authorizer to control who can access your API in Amazon API Gateway. After the API is deployed, the client must first sign the user into a user pool, obtain an identity or access token for the user, and then call the API method with one of the tokens.
Client-Side SSL Certificates
You can also use API Gateway to generate an SSL certificate to verify that HTTP requests to your backend originated from API Gateway. This means that even if your backend systems are publicly accessible, they will accept only requests originating from API Gateway. See more details here.
API Gateway Usage Plans
Finally, you may use API Gateway Usage Plans to extend your APIs as a product offering for your customers. With usage plans, you may allow specific customers to access selected APIs at agreed-upon request rates and quotas that can meet their business requirements and budget constraints.
Amazon API Gateway Pricing
The pricing scheme for Amazon API Gateway is quite simple. You pay only for:
- APIs that are in use
- API calls you receive
- The amount of outbound data
- Cached information
The free tier includes one million API calls per month for up to 12 months. If you exceed this band, standard rates will apply. These vary from $3.50 to $4.25 per million API calls received, depending on the region. Additionally, you will pay extra for data transfer. The charges range between $0.05 and $0.14 per GB, depending on the region and data amount.
For better performance and faster API execution, you can optionally provide a dedicated cache for each stage of your API. If you decide to do so, it will cost you from $0.028 to $4.40 per hour, depending on the cache size. Cache sizes vary from 0.5 GB up to 237 GB.
Amazon API Gateway is a powerful tool that enables you to invoke your Lambda functions or grant access to AWS resources with simple API calls. All of this with full control and logging.
Moreover, API developers can create SDKs and documentation for the APIs in an automated manner, which marks a significant step towards serverless backend infrastructure. Code and data can now be committed to AWS without running a single VM.
Serverless is the future. However, for it to become a reality, tools such as API Gateway are indispensable.