API Managment unable to cast response body as string - azure-api-management

In Azure API Management, when the response going back to the client is a 500, I wish to check the body of the response to see if it matches "Some text". I need to do this so that I may change the body of the response to contain some more helpful text in this particular scenario.
The following <outbound> section of my policy is accepted by the API Management console, but when I test and get a 500, API Management generates an error -
Expression evaluation failed. Unable to cast object of type 'Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.MessageBody' to type 'System.String'.
I'm guessing this is my fault, but does anybody know how I can amend the ploicy so that it does not generate an error? To clarify, the error is being generated by this line - ((string)(object)context.Response.Body == "Some text").
<outbound>
<choose>
<when condition="#((context.Response.StatusCode == 500) && ((string)(object)context.Response.Body == "Some text"))">
<set-status code="500" reason="Internal Server Error" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>
{
"statusCode": "500",
"Message": "Some different, more helpful text."
}
</set-body>
</when>
</choose>
</outbound>
Update
I've discovered that context.Response.Body is of type IMessageBody. There seems to be woefully little documentation around this type, and the only reference I can find comes under <set-body> in the Transformation Policies API management documentation.
The troube is, the example that MS havd documented produces an exception when I try and save my policy -
<set-body>
#{
JObject inBody = context.Request.Body.As<JObject>();
if (inBody.attribute == <tag>) {
inBody[0] = 'm';
}
return inBody.ToString();
}
</set-body>
Property or indexer 'string.this[int]' cannot be assigned to -- it is read only

Try context.Request.Body.As<string>(). Method As currently supports following types as generic argument value:
byte[]
string
JToken
JObject
JArray
XNode
XElement
XDocument
Mind that if you try to call .As<JObject> over response that does not contain valid JSON you would get an exception, same applies to other types as well.

Related

How to update Azure API Management named values in a batch?

We have existing production services which are based on this policy sample which acquires a bearer token via client grant flow. However we want to switch the client application settings to a new app, which requires updating 4 named values. How can this be done with high throughput traffic volumes?
We have updated named value pairs as documented and we've looked at the REST API. There is only 1-by-1 update of values. We applied this on lower volume environments with no problems. However when we applied this on production environments we have outages with the expression unable to parse the value, which results in a null and caused an outage.
This was the policy, copied from the portal.
<choose>
<when condition="#(!context.Variables.ContainsKey("access_token"))">
<send-request ignore-error="true" timeout="20" response-variable-name="response" mode="new">
<set-url>{{authorizationServer}}</set-url>
<set-method id="apim-generated-policy">POST</set-method>
<set-header name="Content-Type" exists-action="override">
<value>application/x-www-form-urlencoded</value>
</set-header>
<set-body>#{return "client_id={{clientid}}&resource={{scope}}&client_secret={{clientsecret}}&grant_type=client_credentials";}</set-body>
</send-request>
<set-variable name="responseJson" value="#(((IResponse)context.Variables["response"]).Body.As<JObject>())" />
<set-variable name="access_token" value="#("Bearer " + (String)((JObject)context.Variables["responseJson"])["access_token"])" />
<set-variable name="expires_in" value="#((int)((JObject)context.Variables["responseJson"])["expires_in"] - 20)" />
<cache-store-value key="access_token" value="#((string)context.Variables["access_token"])" duration="#(((int)context.Variables["expires_in"]))" />
</when>
</choose>
<set-header name="Authorization" exists-action="override">
<value>#((string)context.Variables["access_token"])</value>
</set-header>
"Elapsed": 109,
"Source": "set-variable[3]",
"Reason": null,
"Message": "Expression evaluation failed. Value cannot be null.\r\nParameter name: value\r\n at Newtonsoft.Json.Linq.JToken.EnsureValue(JToken value)\r\n at Newtonsoft.Json.Linq.JToken.op_Explicit(JToken value)",
"Scope": "product",
"Section": "inbound",
"Path": "choose\\when[1]",
"PolicyId": "",
"TransportErrorCode": 0,
"HttpErrorCode": 0
}
I suspected that the issue was related to one of these variables being null but our logs were unclear as to which variable.
There is no API to anatomically update multiple named value properties. There are two approaches that come to mind. You could store all your values in a single named value encoding them into a single string and parsing out inside policy.
Or you could have two sets of named values and a fifth one that controls which one to use. This way you'll be free to update your passive set freely and only activate it later.

How to prepare JSON in Azure Policy

In Azure Policy, How to prepare and return the result as following JSON object.
return { Id : 1, prototype: 'skeleton1', status: 'success'}
The value will be dynamically set to JSON data in policy.
When use straight as above JSON string then, its fail and unable to save the policy.
If you need a dynamic data response, then you probably need to look at the set-body policy and liquid templates:
https://blogs.msdn.microsoft.com/apimanagement/2017/09/25/deep-dive-on-set-body-policy/
For static response data, you can also use the set-body policy like this:
<set-body>{
"Id" : 1,
"prototype": "skeleton1",
"status": "success"
}</set-body>
This will result in the required body.

Convert POST to GET Azure API Management Rest API

I am using Azure API Management REST API's to import a WSDL and convert it to a REST endpoint calling SOAP backend.
However when you import the WSDL all the methods are imported as POST (which makes sense since you need to send the soap envelope). Now I want to convert the operation from POST to GET via the REST API (which I can do through portal).
Has anyone tried that before, and if yes which API's should I call?
For this case I used a public soap service:
https://www.dataaccess.com/webservicesserver/numberconversion.wso?op=NumberToDollars
I imported this SOAP service to API Management:
Request-Body:
<?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope">
<Body>
<NumberToDollars xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.dataaccess.com/webservicesserver/">
<dNum>1</dNum>
</NumberToDollars>
</Body>
</Envelope>
The NumberToDollars operation has to read the XML, transform it into JSON, and pass the data to a GET API.
For testing purposes I created an mocked Operation which returns 200:
https://rfqapiservicey27itmeb4cf7q.azure-api.net/echo/200/test
<policies>
<inbound>
<base />
<set-variable name="num" value="#{
string xml = context.Request.Body.As<string>(preserveContent: true);
xml = Regex.Unescape(xml);
// Remove the double quotes
xml = xml.Remove(0,1);
xml = xml.Remove(xml.Length-1,1);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var data = JObject.Parse(JsonConvert.SerializeObject(doc));
JObject envelope = data["Envelope"] as JObject;
JObject body = envelope["Body"] as JObject;
JObject numberToDollars = body["NumberToDollars"] as JObject;
return numberToDollars["dNum"].Value<string>();
}" />
<set-method>GET</set-method>
<set-backend-service base-url="https://rfqapiservicey27itmeb4cf7q.azure-api.net/echo/200/" />
<rewrite-uri template="#("/test?q=" + context.Variables.GetValueOrDefault<string>("num"))" copy-unmatched-params="false" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Testing the operation:
The trace log:
The JSON document generated from XML:
{
"?xml": {
"#version": "1.0",
"#encoding": "utf-8"
},
"Envelope": {
"#xmlns": "http://www.w3.org/2003/05/soap-envelope",
"Body": {
"NumberToDollars": {
"#xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"#xmlns": "http://www.dataaccess.com/webservicesserver/",
"dNum": "1"
}
}
}
}

Alfresco Workflow: How to set association value when update "Task" by REST Json?

My application is interacting with Alfresco workflow by REST.
There is a task having association to an object of type cm:person, its value should be collected form the end user -to be used as assignee of the next task-. How can I set this value by REST ??
I tried to send HTTP "PUT" request (content-type:application/json) on URL
http://localhost:8080/alfresco/service/api/task-instances/activiti$11102
and body request is:
{
"cio_employee": "workspace://SpacesStore/bcb9817f-5778-484b-be16-a388eb18b5ab" }
where "workspace://SpacesStore/bcb9817f-5778-484b-be16-a388eb18b5ab" is the reference of admin person, but when I end the task (by REST also), Alfresco throws error:
...
Caused by: org.activiti.engine.ActivitiException: Unknown property
used in expression: ${cio_employee.properties.userName} ... Caused by:
org.activiti.engine.impl.javax.el.PropertyNotFoundException: Could not
find property properties in class java.lang.String
Below is the task and its model definition:
//User Task:
<userTask id="assignHandler" name="Assign Employee" activiti:assignee="admin"
activiti:formKey="cio:assignEmployeeTask">
<documentation>Please, Assign employee to the next task</documentation>
<extensionElements>
<activiti:taskListener event="complete"
class="org.alfresco.repo.workflow.activiti.tasklistener.ScriptTaskListener">
<activiti:field name="script">
<activiti:string>
execution.setVariable('cio_employee',
task.getVariable('cio_employee'));
</activiti:string>
</activiti:field>
</activiti:taskListener>
</extensionElements>
</userTask>
///////////////////////////////////////////////////////////
//Model
...
<types>
...
<type name="cio:assignEmployeeTask">
<parent>bpm:workflowTask</parent>
<mandatory-aspects>
<aspect>cio:employee</aspect>
</mandatory-aspects>
</type>
...
</types>
...
<aspects>
<aspect name="cio:employee">
<associations>
<association name="cio:employee">
<source>
<mandatory>false</mandatory>
<many>false</many>
</source>
<target>
<class>cm:person</class>
<mandatory>true</mandatory>
<many>false</many>
</target>
</association>
</associations>
</aspect>
</aspects>
////////////////////////////////////////////////////////////////////////
After searching deeply, you will need to send POST request on
http://localhost:8080/alfresco/s/api/task/[taskId]/formprocessor
with body:
{
"assoc_cio_employee_added": "workspace://SpacesStore/bcb9817f-5778-484b-be16-a388eb18b5ab"
}
and for removing use the key "assoc_cio_employee_removed"
https://wiki.alfresco.com/wiki/Forms_Developer_Guide
Hope it may help someone.
Alfresco Version 4.2.e

Is there any standard for JSON API response format?

Do standards or best practices exist for structuring JSON responses from an API? Obviously, every application's data is different, so that much I'm not concerned with, but rather the "response boilerplate", if you will. An example of what I mean:
Successful request:
{
"success": true,
"payload": {
/* Application-specific data would go here. */
}
}
Failed request:
{
"success": false,
"payload": {
/* Application-specific data would go here. */
},
"error": {
"code": 123,
"message": "An error occurred!"
}
}
Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:
JSON API - JSON API covers creating and updating resources as well, not just responses.
JSend - Simple and probably what you are already doing.
OData JSON Protocol - Very complicated.
HAL - Like OData but aiming to be HATEOAS like.
There are also JSON API description formats:
Swagger
JSON Schema (used by swagger but you could use it stand alone)
WADL in JSON
RAML
HAL because HATEOAS in theory is self describing.
Google JSON guide
Success response return data
{
"data": {
"id": 1001,
"name": "Wing"
}
}
Error response return error
{
"error": {
"code": 404,
"message": "ID not found"
}
}
and if your client is JS, you can use if ("error" in response) {} to check if there is an error.
I guess a defacto standard has not really emerged (and may never).
But regardless, here is my take:
Successful request:
{
"status": "success",
"data": {
/* Application-specific data would go here. */
},
"message": null /* Or optional success message */
}
Failed request:
{
"status": "error",
"data": null, /* or optional error payload */
"message": "Error xyz has occurred"
}
Advantage: Same top-level elements in both success and error cases
Disadvantage: No error code, but if you want, you can either change the status to be a (success or failure) code, -or- you can add another top-level item named "code".
Assuming you question is about REST webservices design and more precisely concerning success/error.
I think there are 3 different types of design.
Use only HTTP Status code to indicate if there was an error and try to limit yourself to the standard ones (usually it should suffice).
Pros: It is a standard independent of your api.
Cons: Less information on what really happened.
Use HTTP Status + json body (even if it is an error). Define a uniform structure for errors (ex: code, message, reason, type, etc) and use it for errors, if it is a success then just return the expected json response.
Pros: Still standard as you use the existing HTTP status codes and you return a json describing the error (you provide more information on what happened).
Cons: The output json will vary depending if it is a error or success.
Forget the http status (ex: always status 200), always use json and add at the root of the response a boolean responseValid and a error object (code,message,etc) that will be populated if it is an error otherwise the other fields (success) are populated.
Pros: The client deals only with the body of the response that is a json string and ignores the status(?).
Cons: The less standard.
It's up to you to choose :)
Depending on the API I would choose 2 or 3 (I prefer 2 for json rest apis).
Another thing I have experienced in designing REST Api is the importance of documentation for each resource (url): the parameters, the body, the response, the headers etc + examples.
I would also recommend you to use jersey (jax-rs implementation) + genson (java/json databinding library).
You only have to drop genson + jersey in your classpath and json is automatically supported.
EDIT:
Solution 2 is the hardest to implement but the advantage is that you can nicely handle exceptions and not only business errors, initial effort is more important but you win on the long term.
Solution 3 is the easy to implement on both, server side and client but it's not so nice as you will have to encapsulate the objects you want to return in a response object containing also the responseValid + error.
The RFC 7807: Problem Details for HTTP APIs is at the moment the closest thing we have to an official standard.
Following is the json format instagram is using
{
"meta": {
"error_type": "OAuthException",
"code": 400,
"error_message": "..."
}
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
I will not be as arrogant to claim that this is a standard so I will use the "I prefer" form.
I prefer terse response (when requesting a list of /articles I want a JSON array of articles).
In my designs I use HTTP for status report, a 200 returns just the payload.
400 returns a message of what was wrong with request:
{"message" : "Missing parameter: 'param'"}
Return 404 if the model/controler/URI doesn't exist
If there was error with processing on my side, I return 501 with a message:
{"message" : "Could not connect to data store."}
From what I've seen quite a few REST-ish frameworks tend to be along these lines.
Rationale:
JSON is supposed to be a payload format, it's not a session protocol. The whole idea of verbose session-ish payloads comes from the XML/SOAP world and various misguided choices that created those bloated designs. After we realized all of it was a massive headache, the whole point of REST/JSON was to KISS it, and adhere to HTTP. I don't think that there is anything remotely standard in either JSend and especially not with the more verbose among them. XHR will react to HTTP response, if you use jQuery for your AJAX (like most do) you can use try/catch and done()/fail() callbacks to capture errors. I can't see how encapsulating status reports in JSON is any more useful than that.
For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.
However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.
The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.
Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.
As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?
Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:
https://github.com/adnan-kamili/rest-api-response-format
Swagger file:
https://github.com/adnan-kamili/swagger-sample-template
The point of JSON is that it is completely dynamic and flexible. Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node.
What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json or leave it as text/plain is up to you (as long as you know how to handle the edge cases).
Build a lightweight schema that you like.
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed.
So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch.
That said, there's a lot to be said for using schemas which make sense to you and are well thought out.
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need.
JSON-RPC 2.0 defines a standard request and response format, and is a breath of fresh air after working with REST APIs.
The basic framework suggested looks fine, but the error object as defined is too limited. One often cannot use a single value to express the problem, and instead a chain of problems and causes is needed.
I did a little research and found that the most common format for returning error (exceptions) is a structure of this form:
{
"success": false,
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
This is the format proposed by the OASIS data standard OASIS OData and seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point. This format is consistent with the JSON-RPC specification.
You can find the complete open source library that implements this at: Mendocino JSON Utilities. This library supports the JSON Objects as well as the exceptions.
The details are discussed in my blog post on Error Handling in JSON REST API
For those coming later, in addition to the accepted answer that includes HAL, JSend, and JSON API, I would add a few other specifications worth looking into:
JSON-LD, which is a W3C Recommendation and specifies how to build interoperable Web Services in JSON
Ion Hypermedia Type for REST, which claims itself as a "a simple and intuitive JSON-based hypermedia type for REST"
There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).
Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.
Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.
I used to follow this standard, was pretty good, easy, and clean on the client layer.
Normally, the HTTP status 200, so that's a standard check which I use at the top. and I normally use the following JSON
I also use a template for the API's
dynamic response;
try {
// query and what not.
response.payload = new {
data = new {
pagination = new Pagination(),
customer = new Customer(),
notifications = 5
}
}
// again something here if we get here success has to be true
// I follow an exit first strategy, instead of building a pyramid
// of doom.
response.success = true;
}
catch(Exception exception){
response.success = false;
response.message = exception.GetStackTrace();
_logger.Fatal(exception, this.GetFacadeName())
}
return response;
{
"success": boolean,
"message": "some message",
"payload": {
"data" : []
"message": ""
... // put whatever you want to here.
}
}
on the client layer I would use the following:
if(response.code != 200) {
// woops something went wrong.
return;
}
if(!response.success){
console.debug ( response.message );
return;
}
// if we are here then success has to be true.
if(response.payload) {
....
}
notice how I break early avoiding the pyramid of doom.
I use this structure for REST APIs:
{
"success": false,
"response": {
"data": [],
"pagination": {}
},
"errors": [
{
"code": 500,
"message": "server 500 Error"
}
]
}
A bit late but here is my take on HTTP error responses, I send the code, (via status), the generic message, and details (if I want to provide details for a specific endpoint, some are self explanatory so no need for details but it can be custom message or even a full stack trace depending on use case). For success it's a similar format, code, message and any data in the data property.
ExpressJS response examples:
// Error
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: `missing ${missingParam}`,
}
});
// or
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: 'expected: {prop1, prop2, prop3',
}
});
// Success
res
.status(200)
.json({
message: 'password updated',
data: {member: { username }}, // [] ...
});
Best Response for web apis that can easily understand by mobile developers.
This is for "Success" Response
{
"code":"1",
"msg":"Successfull Transaction",
"value":"",
"data":{
"EmployeeName":"Admin",
"EmployeeID":1
}
}
This is for "Error" Response
{
"code": "4",
"msg": "Invalid Username and Password",
"value": "",
"data": {}
}