Direct responses
Verified Code examples on this page have been automatically tested and verified.Use the directResponse API to directly respond to incoming requests without forwarding them to services. Instead, you return a pre-defined body and HTTP status code to the client.
About direct responses
When you configure a direct response, the gateway proxy intercepts requests to specific routes and directly sends back a predefined response. Common use cases include:
- Static responses: You might have endpoints for which sending back static responses is sufficient.
- Health checks: You might configure health checks for the gateway.
- Redirects: You might redirect users to new locations, such as when an endpoint is now available at a different address.
- Test responses: You can simulate responses from backend services without forwarding the request to the actual service.
Limitation
You cannot configure multiple direct response resources on the same route. If you configure multiple direct responses, only the oldest is applied.
Schema validation
The following rule is applied during schema validation:
- The
statusfield can define a valid HTTP status code in the 200-599 range.
Before you begin
- Set up an agentgateway proxy.
- Install the httpbin sample app.
Set up direct responses
Create an HTTPRoute resource that routes traffic with the
/path.kubectl apply -f- <<EOF apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: direct-response namespace: agentgateway-system spec: parentRefs: - name: agentgateway-proxy namespace: agentgateway-system rules: - matches: - path: type: PathPrefix value: / EOFCreate an AgentgatewayPolicy resource with a
directResponseconfiguration. The policy is applied on the HTTPRoute that you created earlier and returns a 200 HTTP response code with a custom message body.kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayPolicy metadata: name: direct-response namespace: agentgateway-system spec: targetRefs: - group: gateway.networking.k8s.io kind: HTTPRoute name: direct-response traffic: directResponse: status: 200 body: "Status: Healthy" EOF
Send a request along the
/status/404path of the httpbin app. Typically, this path returns a 404 HTTP response code. However, because you apply a direct response to this route, the request returns a 200 HTTP response code with a custom message instead as defined in your policy. Verify that you see the 200 HTTP response code with your custom message.curl -vi http://$INGRESS_GW_ADDRESS:80/status/404curl -vi localhost:8080/status/404Example output:
... < HTTP/1.1 200 OK HTTP/1.1 200 OK < content-length: 15 content-length: 15 < * Connection #0 to host localhost left intact Status: Healthy%
Cleanup
You can remove the resources that you created in this guide. Run the following commands.
kubectl delete AgentgatewayPolicy health-response -n agentgateway-system
kubectl delete httproute direct-response -n agentgateway-system