What is an API? A Practical Guide with AWS API Gateway and OpenAPI | Kranio
What is an API? A Practical Guide with AWS API Gateway and OpenAPI
Team Kranio 1 de febrero de 2021
Compartir:
API stands for application programming interface. It is a set of definitions and protocols used to develop and integrate application software. There are various types of protocols for APIs, the most commonly used currently is REST.
The flow of a REST API is generally as indicated in the diagram. The client makes a request to the API, which communicates with the database or gives instructions to the server to process the client's request, and the information is returned to the client as a response. To communicate with the API, and thus with the server, we need to do so through an exchange language, generally JSON or XML.
The API is the intermediary between the client application and the server, and as such, it allows identifying who is making the call, enabling access to resources, and monitoring information traffic. They are reusable across multiple platforms and have the ability to work on the backend and frontend either in parallel or independently. This makes applications easy to scale, flexible, and reliable.
Impact of an API
The API is present in most of the interactions we have with systems, whether public or private. Organizations can create their own APIs to coordinate information from different sections of the company or public agency, companies make their APIs public so anyone can access and propagate their information, and other companies have the API as the core in providing their services.
Advantages of an API
Implementing an API in your company, agency, or application allows you to reuse functions in different software. This reduces efforts in application maintenance and also the time-to-market of your developments, regardless of the technologies you use. It helps you monitor your company's transactions to make better decisions for projects and react in time in case of any failure. It facilitates innovation and transformation processes in developments.
The OpenAPI Specification
There are several ways to generate an API contract, including the RAML or API Blueprint specifications. The most used is OpenAPI 3.0 (OAS3, formerly Swagger v2.0), which is open-source and uses JSON or YAML code to describe, document, and consume APIs. It has a modular structure that facilitates reusability and cooperation among developers.
OAS3 contains extensions that allow us to connect with other services such as ReDoc, APIMatic, and Amazon API Gateway.
Here are some examples of OAS3 code and its autogenerated documentation in the swagger editor.
It is an Amazon Web Services (AWS) service that allows you to create, publish, maintain, and secure APIs.
The client request can be processed by private applications, pre-existing endpoints, or other AWS services such as DynamoDB, Kinesis, EC2 among others. The most used is AWS Lambda which runs code without needing a server and supports different programming languages.
Endpoints
API Gateway describes the endpoints with their resources and methods, and each method can be integrated and configured independently.
You can generate the endpoints and their configurations with an OAS3 file, importing it into API Gateway with the necessary extensions.
You can also describe and configure these endpoints through the AWS console, which is simple and intuitive.
Step 1: Enter the AWS API Gateway service and click the Create API button, choose to create a REST API (note, not the private one) and give the new API a name.
Step 2: In the Actions dropdown, choose Create resource and give it a name. Within this resource, choose from the same dropdown the option Create method. Upon selecting and accepting the methodthe option to choose the integration appears, for now select Mock.
Step 3: Once you have defined all the resources and methods of your API, select the option Deploy API within the Actions menu. Create or select a Deployment Stage, which will serve to organize the API versions.
Step 4: You will be redirected to the Stages section where you can see the link to call your API! You can choose a tool like Postman or Insomnia to test your endpoints.
Integrations
In API Gateway there are different types of integrations and each can be proxy or non-proxy. Both can transform the request coming from the client but only non-proxy can transform the response coming back from the server.
Transforming the request coming from the client is useful when integrating two different applications or passing additional parameters in the body or header of the request.
Transforming the server response is useful to organize the server response, add headers, and model according to response code. This is an exclusive feature of the non-proxy integration.
AWS API Gateway has a graphical interface that expresses this flow and allows configuring it in 4 stages.
Method request: configures request validation, authorization method, API Key usage, and mapping of path or query parameters.
Integration request: configures the integration type, proxy or not, and the service to which the request will be sent. In the image case, we communicate with a lambda function in proxy mode. An example of transformation code to map the path parameter in the payload received by the backend:
Integration response: receives the server response and can transform it. This example looks for the word error in the server response; if found, it transforms the response code to “400”
#set($inputRoot = $input.path('
Method response: provides information about the response types
The possibility of making a “mock” integration and treating it as non-proxy helps decouple application development.
Security
API Gateway allows managing API security in different ways.
CORS
You can configure headers to include CORS parameters that will help control the origin and allowed methods of calls made to the API. This can be described in OAS3 or configured from the console in the Actions menu. It is important to remember that to enable CORS we need to have the OPTIONS method on the resource. The AWS console does this for you but you must do it for each resource in your API
API Key
You can configure access to your API via API Key. With it, you can identify who is making the call and restrict API usage through quota or throttling.
To enable an API Key you need to have a Usage Plan associated with a Stage of your API. To create it, go to the Usage Plans menu, press the Create button, and follow the instructions. At the end, you will have an API Key associated with your API and it will be requested in the x-api-key header of the request.
Remember that you must enable the endpoint to require API Key in the Method Request.
AWS IAM
AWS has its own identification and permissions service called AWS IAM. It follows the principle of least privilege, so it has a detailed way of granting permissions.
With IAM you identify yourself to the API with your user's programmatic keys. Once identified, API Gateway calculates if your user has the necessary permissions to invoke the endpoint.
Authorizers
You can configure authorizers in the “Authorizers” menu on the left side and they can be of two types:
Lambda Authorizer
It receives as input a header parameter, usually “Authorization”. This value is redirected to a lambda function that discriminates whether it is valid or not and returns a temporary policy that allows invoking that endpoint. We can use this authorization with tokens like JWT or OAuth or SAML protocols
AWS Cognito
It uses the AWS Cognito service to manage users, credentials, and custom permissions. It supports users from federated identities like Google, Facebook, OpenID Connect among others.
Monitoring
You can monitor your API Gateway through AWS Cloudwatch. To activate monitoring, you must assign the corresponding role to API Gateway in the Settings menu on the left side. It is also necessary to activate it in the Stages menu, Logs/Tracing tab. I recommend selecting the INFO log level to get a detailed log of the API Gateway flow.
AWS Cloudwatch shows the log groups so you can debug. You can use API Gateway metrics or create custom metrics and make them visually available through dashboards. You can also activate alarms to notify you if any metric exceeds a defined limit.
Additional Tools
Cache
In the Stages menu, we can select if we want to enable API Gateway cache, which will create a dedicated cache instance. By default and for greater security, only GET methods are cached.
SDK
When you have the API created, tested, and deployed and want to use it in a project, you can generate an SDK available for Java, Android, iOS, JavaScript, and Ruby languages. Use them to call your API from the client-side application.
Create it in the Stages menu, SDK Generation tab, and choose your preferred language. Press the Generate SDK button to download it ready to use.
Conclusion
Now that you know what an API is, how to create, deploy, and monitor it, I invite you to use the tools described in this post and think about how to leverage the advantages of an API to add value to your business, application, or development process.
Ready to implement efficient and secure APIs in your organization?
At Kranio, we have experts in API design and development using AWS API Gateway and OpenAPI, helping you create scalable solutions that drive your company's digital transformation. Contact us and discover how we can collaborate in your business success.
Method response: provides information about the response types
The possibility of making a “mock” integration and treating it as non-proxy helps decouple application development.
Security
API Gateway allows managing API security in different ways.
CORS
You can configure headers to include CORS parameters that will help control the origin and allowed methods of calls made to the API. This can be described in OAS3 or configured from the console in the Actions menu. It is important to remember that to enable CORS we need to have the OPTIONS method on the resource. The AWS console does this for you but you must do it for each resource in your API
API Key
You can configure access to your API via API Key. With it, you can identify who is making the call and restrict API usage through quota or throttling.
To enable an API Key you need to have a Usage Plan associated with a Stage of your API. To create it, go to the Usage Plans menu, press the Create button, and follow the instructions. At the end, you will have an API Key associated with your API and it will be requested in the x-api-key header of the request.
Remember that you must enable the endpoint to require API Key in the Method Request.
AWS IAM
AWS has its own identification and permissions service called AWS IAM. It follows the principle of least privilege, so it has a detailed way of granting permissions.
With IAM you identify yourself to the API with your user's programmatic keys. Once identified, API Gateway calculates if your user has the necessary permissions to invoke the endpoint.
Authorizers
You can configure authorizers in the “Authorizers” menu on the left side and they can be of two types:
Lambda Authorizer
It receives as input a header parameter, usually “Authorization”. This value is redirected to a lambda function that discriminates whether it is valid or not and returns a temporary policy that allows invoking that endpoint. We can use this authorization with tokens like JWT or OAuth or SAML protocols
AWS Cognito
It uses the AWS Cognito service to manage users, credentials, and custom permissions. It supports users from federated identities like Google, Facebook, OpenID Connect among others.
Monitoring
You can monitor your API Gateway through AWS Cloudwatch. To activate monitoring, you must assign the corresponding role to API Gateway in the Settings menu on the left side. It is also necessary to activate it in the Stages menu, Logs/Tracing tab. I recommend selecting the INFO log level to get a detailed log of the API Gateway flow.
AWS Cloudwatch shows the log groups so you can debug. You can use API Gateway metrics or create custom metrics and make them visually available through dashboards. You can also activate alarms to notify you if any metric exceeds a defined limit.
Additional Tools
Cache
In the Stages menu, we can select if we want to enable API Gateway cache, which will create a dedicated cache instance. By default and for greater security, only GET methods are cached.
SDK
When you have the API created, tested, and deployed and want to use it in a project, you can generate an SDK available for Java, Android, iOS, JavaScript, and Ruby languages. Use them to call your API from the client-side application.
Create it in the Stages menu, SDK Generation tab, and choose your preferred language. Press the Generate SDK button to download it ready to use.
Conclusion
Now that you know what an API is, how to create, deploy, and monitor it, I invite you to use the tools described in this post and think about how to leverage the advantages of an API to add value to your business, application, or development process.
Ready to implement efficient and secure APIs in your organization?
At Kranio, we have experts in API design and development using AWS API Gateway and OpenAPI, helping you create scalable solutions that drive your company's digital transformation. Contact us and discover how we can collaborate in your business success.