As part of the Kong Gateway 2.6 release, we shipped a brand new jq plugin for anyone with an enterprise license to use. It’s like we combined the request and response transformer plugins to form a single, more powerful plugin—supercharging the way we work with request and response bodies.
If you're not familiar with jq, it's a JSON processing language that allows you to manipulate any JSON document and transform it however you need. We won't cover everything that jq can do in this post, but if you'd like a step-by-step introduction, I recommend this post on earthly.dev.
The Kong Gateway jq plugin allows you to run your transforms conditionally, depending on the request or response media type (it defaults to application/json) and response code. This means that you won't try to transform a response body if you get an error response by default.
To configure your jq filter, you need to provide the request_jq_program or response_jq_program options in your plugin config, or you can specify both to transform both the request and the response.
The Kong documentation has a comprehensive overview of the available options, which can be provided to the admin API as an HTTP request or via declarative configuration. Here's a sample declarative configuration file that uses jq to extract the title key from multiple items in a response:
Or using the admin API to configure the plugin:
Example Use Cases
The best way to learn jq is to see it used in some real-world scenarios. In this post, we'll cover three real-world scenarios and one fun example to show the power of jq:
- Transform a request body from one structure to another
- Remove sensitive information from a response
- Convert a JSON API to CSV
- Convert Celsius to Fahrenheit (this is the fun one!)
Let's dive in with how to restructure a request body before sending it to the upstream.