What is an API? Practical Guide with AWS API Gateway and OpenAPI

API stands for application programming interface. It is a set of definitions and protocols used to develop and integrate application software. There are several types of protocols for APIs, the most used currently being 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 in response. To communicate with the API, and thus with the server, we need to do so through a Exchange language, usually JSON or XML.

© Kranio 2021

The API is the intermediary between the client application and the server, and as such, it allows us to identify the caller, enable access to resources and monitor information traffic. They are reusable on multiple platforms and have the ability to work on the backend and frontend in parallel or independently. This makes applications easy to scale, flexible and reliable.

Impact of an API

The API is in most of the interactions we have with systems, whether public or private. Organizations can create their own APIs to be able to coordinate the information of the different sections of the company or public body, companies leave their APIs publicly available so that anyone can access and disseminate their information, and other companies have the API at the center of the provision of their services.

Benefits of an API

Implementing an API in your company, organization or application allows you to reuse functions in different software. This reduces application maintenance efforts and also reduces the time-to-market of your developments, regardless of the technologies you use. It helps you monitor your company's transactions so you can make better decisions for projects and react in time in the event of a failure. It makes it easier for you to innovate and transform developments.

The specification OpenAPI Specification

There are several ways to generate an API contract, including the RAML specification or API Blueprint. The most used is OpenAPI 3.0 (OAS3, formerly Swagger v2.0), 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 between 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 self-generated documentation in the Swagger editor.

-- CODE language-yaml -- openapi: 3.0.1 info: title: Kranio-API license: name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.0 tags: - name: Project - name: Team - name: User - name: options paths: /project: post: summary: post project operationId: post-project tags: - Project responses: 200: description: 200 OK headers: Access-Control-Allow-Origin: schema: type: string 201: description: Recurso creado correctamente headers: Access-Control-Allow-Origin: schema: type: string ...

AWS API Gateway

It is an Amazon Web Services (AWS) service that allows you to create, publish, maintain and secure APIs.

The customer's request can be processed by private applications, pre-existing endpoints, or other AWS services such as DynamoDB, Kinesis, EC2, and others. The most used is AWS Lambda, which executes code without having a server and supports different programming languages.

Endpoints

API Gateway describes 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.

-- CODE language-yaml -- paths: /project: post: tags: - Project responses: 200: description: 200 OK headers: Access-Control-Allow-Origin: schema: type: string 500: description: Generic Server Error headers: Access-Control-Allow-Origin: schema: type: string security: - api_key: [] x-amazon-apigateway-integration: type: "mock" responses: default: statusCode: 200 responseParameters: method.response.header.Access-Control-Allow-Origin: '''*''' 500: statusCode: 500 responseParameters: method.response.header.Access-Control-Allow-Origin: '''*'''

You can also describe and configure these endpoints through the AWS console, which is simple and intuitive.

Step 1: Log in to the AWS API Gateway service and click the button Create API,  choose to create a REST API (mind you, not the private one) and give the new API a name.

Step 2: In the dropdown of Shares elects Create resource and give it a name. Within this resource, choose from the same dropdown the option Create method. When selecting and accepting the method the option to choose the integration is presented, for now select Simulation (Mock).

Step 3: When you have defined all the resources and methods of your API, select the option Implement the API (Deploy API) within the menu of Shares. Create or select one Implementation Stage, which will serve to order the versions of the API.

Step 4: You will be redirected to the section of Stages 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 one can be proxy or non-proxy. Both can transform the request that comes from the client, but only non-proxy can transform the response that returns from the server.

Transforming the request that comes 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 for ordering the server's response, adding headers, and modeling based on response code. It's a feature unique to non-proxy integration.

AWS API Gateway has a graphical interface that expresses this flow and allows it to be configured in 4 stages.

Method request: configure the request validation, authorization method, use of API Key and mapping of path or query parameters.

Integration request: configure the type of integration, proxy or not, and the service to which you will send the request. In the case of the image, we communicate with a lambda function in a proxy way. An example of a transformation code to map the path parameter to the payload received by the backend:

-- CODE language-velocity -- #set($root = $input.params()) { "pathParameters" : "$root.path.id" }

Integration response: receives the response from the server and can transform it. This example looks for the word error in the server's response, when found it then transforms the response code to “400”

-- CODE language-velocity -- #set($inputRoot = $input.path('$')) $input.json("$") #if($inputRoot.toString().contains("error")) #set($context.responseOverride.status = 400) #end

Method answer: provides information on response types

The possibility of making an integration “Mock” and treating it as a non-proxy helps to decouple application development.

Security

API Gateway allows you to manage API security in a variety of ways.

CORS

You can configure the headers to include CORS parameters that will help control the origin and allowed methods of the calls made to the API. This can be described in OAS3 or configured from the console in the menu. Shares. It's important to remember that to enable CORS we need to have the OPTIONS method on the resource. The AWS console does it for you, but you must do it for each resource in your API.

API Key

You can configure access to your API using API Key. With it, you can identify the caller and restrict the use of the API by Quota or Throttling.

To enable an API Key you need to have a Plan of use associated with a Stage of your API. To create it, go to the menu Usage plans, press the button Create and you 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 is governed by the principle of least privilege, so it has a detailed way of giving 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 the authorizers in the menu”Authorizers” on the left side and can be of two types:

Lambda Authorizer

It receives as input a parameter from the header, usually”Authorization”. This value is redirected to a lambda function that discriminates whether or not it is valid and returns a temporary policy that allows that endpoint to be invoked. We can use this authorization with tokens such as JWT or OAuth or SAML protocols

AWS Cognito

Use the AWS Cognito service to manage custom users, credentials, and permissions. It supports federated identity users such as Google, Facebook OpenID Connect and others.

Monitoring

You can monitor your API Gateway using AWS Cloudwatch. In order to activate monitoring, we must assign the corresponding role to the API Gateway in the menu. Configuration on the left side. It is also necessary to activate it in the menu Stages, lash Records/Tracking. I recommend that you select the INFO log level to obtain a detailed log of the API Gateway flow.

AWS Cloudwatch shows 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 set alarms to notify you if any metric exceeds a defined limit.

Additional tools

Cache

On the menu Stages we can select if we want to enable the 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 implemented and you want to use it in a project, you can generate an SDK available for the Java, Android, iOS, JavaScript and Ruby languages. Use them to call your API from the client-side application.

Create it in the menu Stages, tab SDK Generation and you choose the language of your choice. You push the button Generate SDK to download it ready to use.

Conclusion

Now that you know what an API is, how to create, implement and monitor it, I invite you to use the tools described in this post and think about how to take advantage of the advantages of an API to bring value to your business, application or development process.

Ready to implement efficient and secure APIs in your organization?

At Kranio, we have experts in designing and developing APIs using AWS API Gateway and OpenAPI, helping you create scalable solutions that drive the digital transformation of your company. Contact us and discover how we can contribute to the success of your business.

Team Kranio

September 16, 2024