@Mouli Kaku , Unfortunately, JSON schema validation against a JSON schema document is not yet supported in API management currently.
You can upvote in the feedback item here.
As an alternative (though not very clean, but would work), you can write custom code (C# script) in a set-body inbound policy where you can validate 'JToken' with your logic and throw error if not met. Something like:
<set-body>@{
var body = context.Request.Body.As<JObject>(preserveContent: true); // Use JArray if request body is array type
if (body["userId"] == null) // just an example, adjust as per your json structure
{
throw new Exception("User ID is required");
}
// and so on further validation
return body.ToString();
}</set-body>
For request which contains array, you can use JArray instead:
<set-body>@{
var body = context.Request.Body.As<JArray>(preserveContent: true);
foreach(var item in body)
{
if (item["userId"] == null) // just an example, adjust as per your json structure
{
throw new Exception("User ID is required");
}
// and so on further validation
}
return body.ToString();
}</set-body>
You can also use context.Request.Body.As<JToken>(preserveContent: true);
JToken is base of both JObject and JArray (refer Querying JSON with LINQ).
For details, refer API Management policy expressions.
You can make it nicer by collecting all the errors in a list and raise exception with all together as part exception data. To control the returned status, you can use on-error policy to return '400 - bad request' response something like:
<on-error>
<choose>
<when condition="@(context.LastError.Message.Contains("Expression evaluation failed")==true)">
<set-status code="400" reason="Bad request" />
</when>
<otherwise>
<set-status code="500" reason="Error" />
</otherwise>
</choose>
<set-body template="none">@{
return context.LastError.Message.Replace("Expression evaluation failed.","").Trim();
}</set-body>
<base />
</on-error>