CrazyCoder
CrazyCoder

Reputation: 517

Azure API Management - How to send body along with my request

I have an API hosted on Azure and I have started using the Azure API Management. One of my API endpoint is a GET and it requires a body in the form of JSON to be passed to the endpoint. On my postman, I am able to hit the actual API (hosted on Azure) and send the body and I am able to get some results. But when i tried to hit the api on azure api management, I am getting the following exception, although i am sending the request body:

{
    "errors": {
        "": [
            "A non-empty request body is required."
        ]
    },
    "type": "https://tools.ietf.org/html/rfcXXXX#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "XXXXXXXXXXXXXXXXXXXXXXXXXXX"
}

Am I missing some configuration on the Azure Api management? I did look up the set policies and i used the following on my inbound but this is still not working

<set-header name="Content-Type" exists-action="override">
    <value>application/json</value>
</set-header>
<set-body template="liquid">{{body.json}}"}</set-body>

Any insight on how i can fix this issue will be greatly appreciated. Thanks in advance.

Upvotes: 4

Views: 14174

Answers (3)

ozkary
ozkary

Reputation: 2684

If you are trying to use liquid templates to query the document/json, you can follow this short example. Notice how we need to know the document information, so we can query its properties.

Sample document (postman request)

{
   "data": {"message":"hi"}
}

<set-body template="liquid">
{
 {% if body.data %}

    // you can also add guards for objects and arrays
    // {i.e. }if body.data.messages
   "message": {{body.data.message}}     
    
 {%else%} 

  "message": "error no data"               

 {% endif %}
}
</set-body>

Upvotes: 1

Vitaliy Kurokhtin
Vitaliy Kurokhtin

Reputation: 7795

As per spec: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.1 sending body along with GET request does not have defined behavior and suc hrequest may be denied entierly.

Upvotes: 0

Allen Wu
Allen Wu

Reputation: 16438

I can use the following policy to set the GET request body.

<inbound>
    <base />
    <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
    </set-header>
    <set-body template="liquid">{"QueryString": "123", "param1": "456"}</set-body>
    <set-body>@{ 
        JObject inBody = context.Request.Body.As<JObject>(); 
        return inBody.ToString(); 
    }</set-body>
</inbound>

When I test it, I can see that it has been added into body successfully. And I can also get it by using context.Request.Body.As<JObject>().

enter image description here

I noticed that your body is {{body.json}}"}, which seems to be incorrect in format. You should use {{body.json}} and make sure that body.json contains the exact content.

Upvotes: 2

Related Questions