Automatic Request Validation with OpenAPI

July 21, 2022
Est. reading time:
6 min.
Let's explore how you can use OpenAPI with Kusk Gateway to ensure that all the request bodies sent to your cluster a properly validated!
Abdallah Abedraba
Technical Developer Advocate
Kubeshop
Table of Contents
Automatic Request Validation with OpenAPI

Request validation is an important part of any API as it ensures that your backend is receiving data in the format that it should. This helps solving a potential myriad of bugs and even security vulnerabilities that arise when the clients of your APIs send wrong or harmful request data. 

If you can do the request validation before the request hits your backend (for example, doing the validation on your API gateway directly), you would be able to reduce the load that your backend receives and it improves the code as it enforces a separation of the validation logic from the business logic (a huge source of problems of issues and bugs) leading to easier debugging and readability of the code.  

In a Kubernetes environment, with multiple microservices each owned by a different team, it becomes harder to ensure that every microservice is validating requests in a consistent way and that they all send similar error codes and messages when a request validation fails. 

To simplify this request validation workflow, Kusk Gateway, an OpenAPI-driven gateway, has added a feature to enable request validation against a given OpenAPI definition. Let’s look at what this means.

# What is OpenAPI?

OpenAPI (f.k.a Swagger) is an industry standard specification for the API ecosystem that allows to describe all functional aspects of your REST API (the APIs’ paths, requests body, responses, etc). It is very well known and used in modern API teams.

The surge of OpenAPI have pushed API developers to think in a design-first perspective – that is, designing the definition of the API before starting to write code– to be able to then reap the benefits of existing toolings from the OpenAPI world like code generation, documentation, developer portal, [and more](https://openapi.tools/) all out-of-the box.

## How does Kusk Gateway perform request validation with OpenAPI?

With Kusk Gateway, your ingress controller is configured directly through the OpenAPI definition, from the functional aspects, to the operational ones; not through yet another Kubernetes YAML configuration with endless annotations. This means that you can configure CORS, rate-limiting, validation and more all through the OpenAPI definition.

Because the gateway itself is aware of the OpenAPI definition, a user can automatically toggle validation for all incoming requests from the gateway itself. So if a bad request body is caught by Kusk Gateway, it will automatically provide a nice and detailed error message to the client.

For the developers this means that they only need to learn a standard specification like OpenAPI to configure their APIs, not needing to write all the code and logic for handling requests validation in each and every microservice. That’s the no-code experience!

# How is this done in practice?

I will now take you in a walkthrough to learn how you install Kusk in your cluster and activate request validation with no-code required from the backend. 

## 1- Install Kusk CLI

First you need to install the Kusk CLI. Please see the instructions [here](https://kubeshop.github.io/kusk-gateway/cli/overview/).

If you are on Mac, the command is the following:

-- CODE language-bash --
brew install kubeshop/kusk/kusk

## 2- Install Kusk Gateway in your Kubernetes cluster

Run the command to install Kusk Gateway and its resources to your Kubernetes cluster. 

-- CODE language-bash --
kusk install

## 3- Deploy an example application

-- CODE language-bash --
kubectl apply -f https://bit.ly/3co3fjD

## 4- Configure Kusk Gateway

This is a normal OpenAPI definition that configures Kusk Gateway to connect it to the application from the step above and enables request validation to it:

Please create a file `openapi.yaml` and copy the content of the code section to it.

If you’ve seen an OpenAPI/Swagger definition before, the only new thing you’ll have noticed is the `x-kusk` section. This part describes the operational aspects of your gateway and as such Kusk Gateway is configured by them. Under this section you can see multiple Kusk extensions like:

- `cors` which applies CORS rules to the APIs.

- `upstream` section contains the information of the application we deployed earlier so we can connect Kusk Gateway to it. 

- `validation` section is what enables Kusk to automatically validate all requests incoming to your API, and it will validated against the `requestBody` field of any path. In this case, it should validate that the required field `name` is available in the request body to the path `/validated`.

To apply this to your cluster run the following command

-- CODE language-bash --
kusk api generate --envoyfleet.name kusk-gateway-envoy-flee -i openapi.yaml | kubectl apply -f -

## 5- Test your validated endpoint

To make some tests, first let’s get the External IP of the Gateway.

-- CODE language-bash --
kubectl get -n kusk-system svc/kusk-gateway-envoy-fleet

And now test the `/validated` path without sending a request body, which is expected to fail. 

-- CODE language-bash --
$ curl -X POST $EXTERNAL_IP/validated
{"errors":["request body has an error: value is required but missing"]}

Now let’s try to make the same request with a body!

-- CODE language-bash --
$ curl -X POST $EXTERNAL_IP/validated -H 'Content-Type: application/json' -d '{"name":"Kusk Tester"}'
{"message":"Hello Kusk Tester!"}%

And now the request has gone through to the upstream, completely validated, reducing the chances of a server error and the load to it!

# Wrapping up

Validating the request bodies so easily is crucial for the developer experience while building APIs, which is what the Kusk Gateway team is trying to solve. 

Design-first principles and the use of standard specifications like OpenAPI allows Kusk Gateway to provide features like validation which we have convered here, but it has also enabled features like [mocking](https://kubeshop.github.io/kusk-gateway/guides/mocking/), which enables to return mock responses from your API without having deployed any services to your cluster!

Head over to the [Kusk Gateway documentation](https://kubeshop.github.io/kusk-gateway/getting-started/installation/) to try it out and explore all the benefits of an OpenAPI-driven gateway! We would love to hear your thoughts and ideas in our [Discord server](https://discord.gg/uNuhy6GDyn) or just drop by if you to say hi :)

Thank you!

Tags:
OpenAPI
Kubernetes

Recent Articles

Subscribe to stay up to date by getting the blog direct to your inbox
Or join the Kubeshop Community in one of these channels