How to modify Status Codes of API Responses

Membrane API Gateway allows you to modify response status codes dynamically using the groovy element. This is useful for masking backend errors, customizing error responses, or implementing security measures.

For more in-depth scripting guidance, visit: Scripting Guide.

Example Configuration

This configuration checks if the backend returns a 401 Unauthorized status. If so, the response is modified to return 404 Not Found instead.

<api port="2000">
<response>
<if test="statusCode == 401">
<groovy>exc.getResponse().setStatusCode(404)</groovy>
</if>
</response>
<target url="http://localhost:2001" />
</api>

<api port="2001">
<return statusCode="401" />
</api>
<api port="2000">
    <response>
        <if test="statusCode == 401">
            <groovy>exc.getResponse().setStatusCode(404)</groovy>
        </if>
    </response>
    <target url="http://localhost:2001" />
</api>

<api port="2001">
    <return statusCode="401" />
</api>

Understanding the Configuration

  • <if>: Evaluates whether the response has a 401 status code.
  • <groovy>: Executes Groovy code to modify the response status.
  • exc.getResponse().setStatusCode(404): Rewrites the status code to 404 Not Found.

Resources

PluginExampleDocumentation
groovyExampleDocumentation
IfExampleDocumentation