The OpenAPI Specification (OAS) is a language-agnostic standard for documenting REST APIs. It can be used to generate a request list, tests, and client and server stubs.
By using OAS, developers can streamline their workflow, defining the API specification and then generating code for interacting with the API based on that specification. This approach saves time and reduces the need to write boilerplate code.
OAS is commonly utilised to create documentation websites, allowing non-engineers on the team to interact with the API without relying on specialised tools such as Postman or Insomnia.
When working with multiple APIs, using an API gateway can help. It acts as a middleman between clients and APIs, offering various advantages, such as centralised API management, enhanced security, and efficient routing. This article will focus on Tyk, a powerful API gateway that enables monitoring, throttling, and securing APIs.
In this article, you’ll learn how to take an existing API defined using OAS and import the API into Tyk.
Use the OAS to define a new API in Tyk
Before you begin, you need to download this repo containing the Petstore OAS hosted by SwaggerHub. Or you can use this permalink . The petstore OAS points to a REST API hosted on Render.com that lets you perform create, read, update, and delete (CRUD) operations on pets, orders, and users.
If you want to clone the repo, you can use the following command:
```bash git clone https://github.com/vicradon/petstore.git ```
Set up the Tyk Gateway
Tyk offers two ways to use the API gateway: an open source gateway from GitHub that can run on Kubernetes or Tyk Cloud, which requires a licence. While the open source option is free, its setup takes longer and requires a server running Kubernetes. For this reason, you’ll take advantage of Tyk’s free five-week trial and use the cloud gateway to provision and secure an API.
To begin, you need to create a Tyk account. All the things you provision and deploy will be grouped under a single unit called an “organisation”. An organisation can have multiple teams, environments, control planes, and cloud data planes. After creating an account, you are navigated to a screen where you can set up your organisation:
Set up an organisation with Tyk
Choose a name and region for your organisation. Then select CREATE ORGANISATION. Choose DEMO SETUP, as that’s all that is needed for this tutorial:
Choose your setup
This sets up your personal control plane and cloud data plane. The control plane is the Tyk component that handles the configuration and management of the behaviour of the API. The data plane is the component that receives API traffic:
Set up of different components
Once the control plane deployment is finished, it’s time to create your first API.
On the control plane page, click on MANAGE APIS, which takes you to the APIs page on the Tyk dashboard:
APIs page
Create your first API
On the APIs page, click on import API. This takes you to an input form for your API definition and upstream URL. Copy the openapi.json
file from the repo and set the upstream URL as https://petstore-e7b0.onrender.com/v1
. The upstream URL comes from a deployed instance of the API. You can choose to deploy it yourself from either the code in the given repo or this Docker image. Click on IMPORT API to complete the process:
Click on IMPORT API
When the import is finished, you’ll be taken to the API configuration page for your new API, which has been named “petstore”:
API configuration page for the petstore API
Currently, your new petstore API does not have an endpoint where you can invoke it because you have not deployed it to any Tyk gateway. This can be done under advanced options > segment tags (node segmentation). You must select at least one API segment tag from the new tag form so that the API will be deployed to an endpoint. Select edge to deploy your API to the gateway in your data plane:
Segment tags (node segmentation)
When you created your organisation, a single Tyk data plane was configured. This single data plane gives you an edge gateway (and endpoint) that your API can be accessed from. With Tyk, you can configure multiple data planes to increase availability and distribute the API gateways geographically.
After setting the tags, click on UPDATE and navigate to the core settings tab on the API configuration page. You should see an API URL:
API URL
During the API import process, Tyk reads the version
field from the openapi.json
and sets this as the first (or base) version of the API. You can manually add future versions as your API version changes.
Currently, every request you make to the API URL expects a version header with a header key of version
and a header value of 1.0.0
. This means if you try to make an API request like “GET https://essential-airbus-gw.aws-euw2.cloud-ara.tyk.io/v1/pet/3” without the version header and value pair, you’ll get a version information not found
error:
```json { "error": "Version information not found" } ```
You can prevent this behaviour by setting a default version. Setting a default version removes the restriction of always having to include a version header in your API requests. To do so, navigate to the versions tab, then scroll down to the Set a default API version form. Set version 1.0.0 as the default version and then update the API using the UPDATE button in the top-right corner:
Setting the default API version
To see the data from the API, you need to make a GET request to the /pet/3
endpoint. Once you’ve made the request, your response will look like this:
```json {"id":3,"name":"Lovely Metty","status":"sold","createdAt":"2023-07-29T08:23:56.177Z","updatedAt":"2023-07-29T08:23:56.177Z"} ```
In this snippet, you can see a Pet object with an ID of three. This confirms that the API was successfully imported into Tyk and works as your request to the petstore API endpoint has reached the service/app and returned some data.
Perform API management with Tyk
Effective API management is a vital aspect of any API gateway, and Tyk, being a comprehensive gateway, offers an intuitive dashboard to facilitate this management process. With Tyk, you gain access to a wide range of essential features that help you version, rate-limit, and enhance the security of your APIs.
Moreover, with Tyk, you can implement other API management strategies, such as cross-origin request sharing (CORS) management and webhooks. Take a look at some of these API management strategies in the following sections:
Rate limiting
Rate limiting is a way to set a maximum number of API calls that can be made to an API by a specific client within a set duration. It prevents an API from being overwhelmed by bots and denial-of-service (DoS) attacks.
The general way rate limiting works is by using a counter to keep track of the number of requests a client has made to the API within a given duration. When the value of this counter exceeds the set limit, the API no longer forwards requests but sends a rate limit exceeded error.
To set up rate limiting with Tyk, navigate to the core settings tab of the petstore API configuration page. Scroll to the rate limiting and quotas section and then disable rate limiting or set it to a specific value:
Rate limiting
The rate input field allows you to set how many API calls can be made. The per (seconds) input field lets you set the reset duration of your rate limiter. Inputting 4
in the former and 60
in the latter means you don’t want your clients to make more than four API calls in one minute. If they do, they’ll receive the following error message:
```json { "error": "API Rate limit exceeded" } ```
Make sure you click UPDATE at the top of your page anytime you make a change.
API versioning
Versioning your API helps ensure that changes can be made to it without breaking existing consumer applications. This means that when a breaking change is introduced, a new version of the API is set and downstream consumers can move to the new version seamlessly.
For instance, if you develop a new version of the petstore API and wish to tag it as version 2.0.0, you simply need to define the version header key (ie 2.0.0
) as well as the URL where this new version lives:
Adding a new version
You can leave the expiry date empty for this tutorial.
Complete the versioning process by clicking on the ADD button and then update the API using the UPDATE button at the top of your page.
CORS management
CORS is a browser-based security feature that prevents websites from making requests to origins other than the one they were served from. This implementation prevents bad actors from easily performing distributed denial-of-service (DDoS) attacks, cross-site request forgery (CSRF), and cross-site scripting (XSS) attacks. Servers can set an allowed origins list that lists origins where requests can be made from, enhancing the overall security of the API.
Note that this access restriction only applies to web browsers, as your API can still be accessed using a proxy tool like Postman. Tyk allows you to protect your API using CORS by providing a way to set allowed origins and an allowed methods list.
To set up CORS, navigate to the advanced options tab and find the CORS options section. Under this section, you’ll find a checkbox for enabling CORS.
After enabling CORS, feel free to add your allowed origins per your requirements. The following image shows localhost:3000
as an allowed origin:
CORS options
Using the CORS options, you can also set the HTTP methods that can be called, the headers that can be added to requests, as well as the headers that are exposed in responses.
For instance, if you don’t want anyone to be able to perform a DELETE request, you can choose to add all other methods except DELETE to the allowed methods list.
You should also include the version
header so you can send the version information if you’re using a version other than the default. Setting a version is necessary because when CORS is enabled, any endpoint not explicitly specified in the allowed methods or allowed headers will be blocked.
Allowed methods and headers
Don’t forget to update the API before moving on to the next section.
Webhook configuration
With Tyk, you can perform specific actions in response to certain events that happen on your API. These events could include authentication failure, key expiration, or exceeding the rate limit. To achieve this, you can set up webhooks on your Tyk account and associate them with individual events occurring in your API.
To access the webhook management page, simply navigate to it from the sidebar:
Accessing the webhooks dashboard
Click on ADD WEBHOOK, then fill out the resulting form with your webhook’s details. The form in the following image shows how you can add a generic webhook:
Webhook details
You can obtain a similar webhook URL from https://webhook.site. The x-original-host
header in the form indicates the origin of the webhook request. It helps you distinguish your webhook from other webhooks.
Make sure you add this webhook to your API by navigating to the advanced options, scrolling to the webhooks section, and clicking ADD:
Adding a webhook to an API
Don’t forget to click on UPDATE to save your configuration.
You can proceed to test your webhook by making four API requests to an endpoint of your choosing; for example, /pet/5
. On the fifth request, you should get the rate limit exceeded error and a webhook response similar to this:
Webhook response
Make sure you configure the webhook. You can even integrate it with platforms such as Slack or Microsoft Teams to alert your team about events that occur on your APIs.
Perform API management with Tyk
Effective API management is a vital aspect of any API gateway, and Tyk, being a comprehensive gateway, offers an intuitive dashboard to facilitate this management process. With Tyk, you gain access to a wide range of essential features that help you version, rate-limit, and enhance the security of your APIs.
Moreover, with Tyk, you can implement other API management strategies, such as cross-origin request sharing (CORS) management and webhooks. Take a look at some of these API management strategies in the following sections:
Rate limiting
Rate limiting is a way to set a maximum number of API calls that can be made to an API by a specific client within a set duration. It prevents an API from being overwhelmed by bots and denial-of-service (DoS) attacks.
The general way rate limiting works is by using a counter to keep track of the number of requests a client has made to the API within a given duration. When the value of this counter exceeds the set limit, the API no longer forwards requests but sends a rate limit exceeded error.
To set up rate limiting with Tyk, navigate to the core settings tab of the petstore API configuration page. Scroll to the rate limiting and quotas section and then disable rate limiting or set it to a specific value:
Rate limiting
The rate input field allows you to set how many API calls can be made. The per (seconds) input field lets you set the reset duration of your rate limiter. Inputting 4
in the former and 60
in the latter means you don’t want your clients to make more than four API calls in one minute. If they do, they’ll receive the following error message:
Monitor your API with Tyk
Monitoring an API is crucial to ensure its reliability and health. To achieve this, various checks need to be performed, such as using a logging service, setting up alerts and notifications, and having a dashboard showing trends of a particular feature.
With Tyk’s API management platform, you have access to all these features, allowing you to implement a comprehensive monitoring and analytics suite for your APIs.
Provision logging for your API
Logging is an essential configuration for APIs because it shows trends and errors your API has encountered over a period of time.
Tyk gives you a full-featured logging experience that is seamless to set up. All you need to do is to enable logging on the core settings page:
Enable logging
Once logging is enabled, you can see every request and its associated response in the log browser:
Logging for a single endpoint
Set up a monitoring dashboard
Your gateway dashboard (aka API activity dashboard) can serve as a monitoring page where you can learn how your API is holding up or failing against requests. You can access this dashboard from the first navigation link on the side nav:
Logging dashboard
Please note: An important part of monitoring is alerting your developers and managers when an endpoint has failed repeatedly. This can be set up on the alerts page, which you’ll learn about next.
Set up alerts
Alerts notify your monitoring or operations team when certain events occur on your API or the API dashboard that could lead to downtimes or failures. Tyk offers an easy way to set up email alerts so your team is notified via email when events occur.
To set up alerts, navigate to the settings page under the portal management section of the sidebar. From there, you can add an email address where API subscription events are sent:
Alerts
Secure your API
So far, you’ve been using your API without having to provide any form of authentication, so it is open to anyone to use. Tyk offers several ways to make your API more secure. For instance, you can use an API key to authenticate clients when they call the API. You can use keys to track the activity of a user, and you can create as many keys as there are clients.
An alternative way of securing your API is using an authentication method such as OpenID Connect or OAuth 2.0. You can also add certain IP addresses to an allowlist or denylist to control who has access to your API (more on this next) and certain IP addresses to control who can access your API.
The good news is you don’t have to use a single security method. You can mix and match different methods to achieve the level of security you require.
Set up an authentication strategy
Currently, your API does not have an authentication strategy, and the authentication mode field is set as open/keyless. This allows requests from any client to access your API. You can make your API more secure by setting up an actual authentication strategy. This could be by using an API key, JSON Web Token (JWT), OpenID Connect, or OAuth 2.0. The choice of authentication strategies depends on your use case.
Let’s use the authentication token method; this is a simple authentication strategy that doesn’t require much setup. You simply go to your API, and under core settings, select authentication token:
Authentication token auth method
This authentication method mandates that you add a header with a key of authorisation
to all your API calls. Now, if you try to make an API request, you’ll get the following response:
```json { "error": "Authorisation field missing" } ```
You need to add the authorisation
header to your API request, but what value should it take? When using the authentication token method, the value is called a bearer token or key. You can create valid tokens/keys within the dashboard, so that Tyk knows which it should accept in requests to the API.
To create a bearer token key, navigate to the keys page under system management:
Keys under system management
Click on ADD KEY to add a new API key.
Then select CHOOSE API to apply the key to your petstore API:
Choose API
After selecting the petstore API, set the API version that the key applies to:
Keys page
Navigate to the configurations tab; then set the expiry time of the key and give it an alias:
Key configuration
Please note: The keys are hashed and not displayed on the keys page. However, you can revoke a key using its hash or alias.
Finalise the key creation process by clicking on CREATE KEY. Once the key is created, you should save it in an environment file that is not tracked by source control and use it until it expires.
You can also create keys without using this flow on the dashboard using the Tyk dashboard API.
Now, if you add an authorisation header and set the key as the value, you should be able to access your API again.
Allow and deny lists
IP whitelisting allows you to restrict access to your API only for certain IP addresses. In contrast, IP blacklisting prevents specific IP addresses from accessing your API. You can whitelist and blacklist IPs on the advanced options page:
Blacklisting and whitelisting IPs
Add path-based granular access control
Granular access control allows you to restrict access to different paths in your API to different users; you can manage this access control per API key or policy. A policy is a configuration that can be applied to multiple API keys such that the behaviour of the key is dictated by the rules defined in the policy. For instance, you can define the rate limiting rule and allowed paths in a policy, then apply that policy to a key that external users will use.
You can add granular access control by navigating to the policies page under system management. On this page, click on the ADD POLICY button:
Policies page
The add policy page has two tabs, an access rights tab and a configurations tab. Under the access rights tab, select the petstore API as the API you want to add the new policy to:
Selecting the API where the policy is to be applied
When you select the petstore API, you are presented with a form where you set the API version and paths the policy applies to. Select all available versions and set the path as /user*
. This binds the policy to all paths under /user
.
On the allowed methods drop-down, select all methods. This ensures the policy applies to all methods on all paths starting with /user
. Click on ADD to add this path-based permission rule and then proceed to the configurations tab:
Configuring the policy to apply to the user paths
The configurations tab lets you set the key expiry rules for this policy. Any key this policy applies to expires at the time set here.
You also need to give your policy a name. Set the name as “users-only access”. Finalise the process by selecting CREATE POLICY:
Policy rules
Now that your policy is created, it’s time to create a key that will be governed by it. Navigate to the keys page and create a new key as you did previously. On the resulting form, select the users-only access policy as the policy that will be applied to the new key and then click on CREATE KEY:
Creating a key with policy
Once the key has been created, copy it and test it with your API. If you try to access a path that is not under /user
, you’ll get the following error:
```json { "error": "Access to this resource has been disallowed" } ```
But if you try to fetch a user with the username GuyFawks
using the /v1/user/GuyFawks
path, you’ll get the following response:
```json { "id": 1, "username": "GuyFawks", "firstName": "Guy", "lastName": "Fawks", "password": "some-password-23", "phone": "+1384982783", "userStatus": 1, "createdAt": "2023-08-02T14:07:49.143Z", "updatedAt": "2023-08-02T14:07:49.143Z" } ```
Conclusion
Building and managing APIs aren’t easy tasks. There are several things you need to configure to ensure your API is secure and serves all your clients.
In this article, you learned about OAS and how to import an API defined using OAS into Tyk. With Tyk, you can handle these aspects effortlessly. Whether you opt for a cloud trial account or the open source version of the gateway, Tyk streamlines the process, making API management a breeze. Now, you can confidently create secure and reliable APIs without any unnecessary hassle.