Set‑Body Policy

The <set-body> policy replaces the request or response body with a new value. It is commonly used to transform payloads, inject static content, or generate dynamic JSON/XML from expressions.

Syntax

<set-body>
    <value>[Expression or literal value]</value>
    (optional) <content-type>[MIME type]</content-type>
</set-body>

Attributes

Examples

1. Static JSON response

<policies>
    <inbound>
        <base/>
    </inbound>
    <backend>
        <base/>
    </backend>
    <outbound>
        <set-body>
            <value>{
    "status": "success",
    "message": "Hello from API Management"
}</value>
            <content-type>application/json</content-type>
        </set-body>
    </outbound>
</policies>

2. Dynamic XML based on query string

<policies>
    <inbound>
        <base/>
    </inbound>
    <outbound>
        <set-body>
            <value>@{
var name = context.Request.QueryString.GetValueOrDefault("name", "Guest");
return $"<greeting>Hello, {name}!</greeting>";
}</value>
            <content-type>application/xml</content-type>
        </set-body>
    </outbound>
</policies>

3. Override response body from backend

<policies>
    <outbound>
        <choose>
            <when condition="@(context.Response.StatusCode == 404)">
                <set-body>
                    <value>{
    "error": "Resource not found"
}</value>
                    <content-type>application/json</content-type>
                </set-body>
            </when>
        </choose>
    </outbound>
</policies>

Notes

When using @{} expressions, ensure the result is a string. Complex objects must be serialized (e.g., JsonConvert.SerializeObject()) before assignment.