Change response bodies
Verified Code examples on this page have been automatically tested and verified.Update the response status based on request query parameters by using CEL expressions. The example uses request.uri and the contains() function with a conditional expression to set the :status pseudo header.
Before you begin
- Set up an agentgateway proxy.
- Install the httpbin sample app.
Change the response status on a route
In this example, the transformation applies after routing and targets a specific HTTPRoute. You change the value of the :status response header to 401 if the request URI contains the foo=bar query parameter. If the request URI does not contain foo=bar, you return a 403 HTTP response code.
Create an AgentgatewayPolicy resource with your transformation rules.
kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayPolicy metadata: name: transformation namespace: httpbin spec: targetRefs: - group: gateway.networking.k8s.io kind: HTTPRoute name: httpbin traffic: transformation: response: set: - name: ":status" value: 'request.uri.contains("foo=bar") ? 401 : 403' EOFSend a request to the httpbin app and include the
foo=barquery parameter. Verify that you get back a 401 HTTP response code.curl -vi http://$INGRESS_GW_ADDRESS:80/response-headers?foo=bar \ -H "host: www.example.com:80"curl -vi "localhost:8080/response-headers?foo=bar" \ -H "host: www.example.com"Example output:
< HTTP/1.1 401 Unauthorized HTTP/1.1 401 Unauthorized < access-control-allow-credentials: true access-control-allow-credentials: true < access-control-allow-origin: * access-control-allow-origin: * < content-type: application/json; encoding=utf-8 content-type: application/json; encoding=utf-8 < foo: bar foo: bar < content-length: 29 content-length: 29 { "foo": [ "bar" ] }Send another request to the httpbin app. This time, include the
foo=bazquery parameter. Verify that you get back a 403 HTTP response code.curl -vi http://$INGRESS_GW_ADDRESS:80/response-headers?foo=baz \ -H "host: www.example.com:80"curl -vi "localhost:8080/response-headers?foo=baz" \ -H "host: www.example.com"Example output:
< HTTP/1.1 403 Forbidden HTTP/1.1 403 Forbidden < access-control-allow-credentials: true access-control-allow-credentials: true < access-control-allow-origin: * access-control-allow-origin: * < content-type: application/json; encoding=utf-8 content-type: application/json; encoding=utf-8 < foo: baz foo: baz < content-length: 29 content-length: 29 { "foo": [ "baz" ] }
Cleanup
You can remove the resources that you created in this guide.kubectl delete AgentgatewayPolicy transformation -n httpbin --ignore-not-found