JSON RPC 2.0: response that is part error and part result - json-rpc

What is the standard approach to returning a JSON RPC response when there is only partial failure? It appears that both 'result' and 'error' cannot both be set.
We have a case where a server is aggregating results across several sites running the same API. The reason for the aggregation is due to the Same-Origin Policy. Each site may respond with either a result or an error. If some respond with a result and others with an error, then what does the aggregation server return as the complete response to the original caller?
a =(method)=> b
b =(method)=> c
b =(method)=> d
b <=(error)== c
b <=(result)= d
a <=(??????)= b
Is it best to simply return two responses (one with any errors and no 'id' and one with the results and an 'id' suggesting this is the last response)?

The server responsibility is to aggregate and return the results, which may contain errors. This is what your client is expecting.
--> {"jsonrpc": "2.0", "method": "getResults", "id": 1}
<-- {"jsonrpc": "2.0", "result": [ "success", "error" ], "id": 1}
You should return an error if the server itself could not process the request, for any unexpected reason.

Related

Unable to update results of a shared test step via Azure Devops REST-api in Postman

I am trying to update the result of a test case via Azure DevOps REST-Api in Postman.
My test case is very simple and consists only of one shared step that has two simple steps inside.
I want to mark these steps of my shared step as "Passed".
Currently I am doing the following steps:
create a new test Run via POST request to {{baseUrlTestApi}}/runs?api-version=7.0
In request's body I pass the test run name, shallow reference to build and owner. Run is successfully created, I can see it on the portal.
create a result of a test case via POST request to {{baseUrlTestApi}}/Runs/{{runId}}/results?api-version=7.0
In request body I pass shallow references to the project, test plan, test suite, test point and test case, outcome ("Passed"), state ("Completed"), testCaseTitle and revision. On the portal I can see that the result is created with the correct outcome and state and is linked to the right test suite and test case.
update the result with actionResults via PATCH request to {{baseUrlTestApi}}/Runs/{{runId}}/results?api-version=7.0
In request body I pass the test result's ID and iteration details, that contains iteration id and an array of action results, where I specify shared step's ID and revision and outcome for each shared step's step. This is the request's body:
[
{
"id": 100000,
"iterationDetails": [
{
"id": 1,
"outcome": "Passed",
"startedDate": "2022-02-16T21:14:14.337Z",
"completedDate": "2022-02-16T21:14:17.057Z",
"durationInMs": 27180000.0,
"actionResults": [
{
"actionPath": "0000000200000001",
"sharedStepModel": {
"id": 18338,
"revision": 2
},
"iterationId": 1,
"stepIdentifier": "1;1",
"outcome": "Passed",
"startedDate": "2022-02-16T21:14:14Z",
"completedDate": "2022-02-16T21:14:14Z",
"url": "{{baseUrlTestApi}}/Runs/{{runId}}/Results/100000/Iterations/1/ActionResults?actionPath=0000000200000001"
},
{
"actionPath": "0000000200000002",
"sharedStepModel": {
"id": 18338,
"revision": 2
},
"iterationId": 1,
"stepIdentifier": "1;2",
"outcome": "Passed",
"startedDate": "2022-02-16T21:14:14Z",
"completedDate": "2022-02-16T21:14:14Z",
"url": "{{baseUrlTestApi}}/Runs/{{runId}}/Results/100000/Iterations/1/ActionResults?actionPath=0000000200000002"
}
],
"parameters": [],
"attachments": [],
"url": "{{baseUrlTestApi}}/Runs/{{runId}}/Results/100000/Iterations/1"
}
]
}
]
Then I go to the portal to see the results. I am expecting to see all three steps of my shared step marked as Passed in the Details section. However, when I go to Runs --> select my run --> test results --> select my result I see this error:
workItemRevision error
I found that what is causing this error is that in the payload of POST request to https://{{organization}}.visualstudio.com/_apis/Contribution/dataProviders/query sent by the portal shared step's work item has an empty string in workItemRevisions.
empty string in workItemRevisions
However, I have explicitly specified the revision ID in step 3 (in sharedStepModel object in each element of actionResults array). If I send a request to this endpoint myself via Postman with the same payload but with "1" instead of empty string, the request is successful.
Before this request, portal sends another one to the same endpoint for the Test Case's workitem and that request is successful, workItemRevisions field is populated correctly, so it is empty string only for the shared step's workitem.
This is the case only if the shared step is involved. If a test case consists of only regular steps, then I am able to mark them as "Passed" with the same flow I described above.
Any ideas what can be causing this? Is this even the right approach to mark the shared step's outcome? Thanks in advance.
After checking the REST API:
You could get a request body (use the Iterations detailsToInclude parameter) and modify the request body. and then to update the result to check if it works.
12.14 Update:
If you manually run the test with shared steps, we can get the actionresults like:
"actionResults": [
{
"actionPath": "00000002",
"iterationId": 1,
"sharedStepModel": {
"id": 142,
"revision": 1
},
"stepIdentifier": "2",
"outcome": "Failed",
"startedDate": "2022-12-14T07:43:03Z",
"completedDate": "2022-12-14T07:43:03Z"
},
{
"actionPath": "0000000200000001",
"iterationId": 1,
"stepIdentifier": "2;1",
"outcome": "Failed",
"startedDate": "2022-12-14T07:43:03Z",
"completedDate": "2022-12-14T07:43:03Z"
}
],
"parameters": [],
"attachments": [],
"url": "https://dev.azure.com/{org}/{project}/_apis/test/Runs/{runId}/Results/100000/Iterations/1"
}
]
And then I change the outcome from "Failed" to "Passed" and then Patch the result to:
https://dev.azure.com/{org}/{project}/_apis/test/Runs/{runId}/results?api-version=7.0
And then I can view the result in the run -> Test results -> The run.
So, I think your problem maybe related to the format of the actionresults, you can try to run a manually test to get the actionresults and then PATCH it to check if it works.

Should I return a 404 error on a resource resulting in empty set?

If I have a resource with the following endpoint that lists all items within that resource:
/api/v1/resources
This results in:
[
{
"id": 1,
"value": -100
},
{
"id": 2,
"value": -999
}
]
It has various filters, for example:
/api/v1/resources?values_gte=999
If the filters exclude every resource and results in an empty set:
[]
Should I return a 404 status code, or a 200 status code?
Should I return a 404 status code, or a 200 status code?
200
You asked for the current representation of the resource identified by "/api/v1/resources?values_gte=999" so here it is: an empty JSON array
Notice that this is exactly what you would do if somebody requested /foo.json, and that file on your disk happened to contain exactly the contents []
HTTP status codes are metadata identifying the semantics of the response; they are used to distinguish representations of documents (2xx Successful) from representations of errors (4xx Client Error).
The payload of a 404 response would be "a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.", not an empty document.

Actions Builder webhookResponse Unexpected internal error at List Response

I tried to add a List Response from my webhook and always receiving an error such as:
Unexpected internal error id=c57c97b2-0b6f-492b-88a3-3867cf2e7203
(The id changes each time.)
After comparing the expected JSON webhookResponse from the Docs with the generated Response from the Actions SDK I found a difference at the typeOverrides object:
JSON from Docs
"typeOverrides": [
{
"name": "prompt_option",
"synonym": {
"entries": []
},
"typeOverrideMode": "TYPE_REPLACE"
}
]
Generated JSON Response from Actions SDK
"typeOverrides": [
{
"name": "prompt_option",
"synonym": {
"entries": []
},
"mode": "TYPE_REPLACE"
}
]
There seems to be an error in the example documentation, but the reference docs say that it should be mode. I've tested it both ways, and that isn't causing the error.
The likely problem is that if you're replying with a List, you must do two things:
You need a Slot in the Scene that will accept the Type that you specify in the typeOverride.name. (And remember - you're updating the Type, not the name of the Slot.)
In the prompt for this slot, you must call the webhook that generates the list. (It has to be that slots prompt. You can't request it in On Enter, for example.)

Use output from Web Activity call as variable

I'm using ADFv2 to transfer some data. As a part of this operation I need some configuration values to pass into the pipeline.
The config values must be pulled at runtime from a REST service - not as parameters.
I can successfully query the REST service with Web Activity and I can see the output in the debug view.
Now the problem :)
How do I use this output in other activities further in the pipeline?
My Web Activity configuration is like this:
{
"name": "Web1",
"type": "WebActivity",
"policy": {
"timeout": "7.00:00:00",
"retry": 0,
"retryIntervalInSeconds": 30,
"secureOutput": false
},
"typeProperties": {
"url": "https://myazurefunction.azurewebsites.net/api/MyFunction",
"method": "GET",
"headers": {
"Content-Type": "application/json"
}
}
I have tried to access the output after is has executed, but it seems empty:
#activity('Web1').Output
#activity('Web1').output
#string(activity('Web1').Output)
they are all empty. Any suggestions?
Thanks!
I set up an ADF2 and try to get a response.
This works for me:
#string(activity('Post').output)
Have you checked the output in the debugging?
Here is my output:
{
"test": {
"value": 123,
"text": abc
},
"concat": 123abc
}
I use the stored procedure to insert the values into the destination table on a Logical Server.
In ADFv2, you access the output of previous activities using #activity('ActivityName').output.
For the web activity defined, the response from your function should be in JSON format, so you would reference specific JSON values using their attribute names in the response. For example, your defined web activity, named Web1, calls a function that returns a response of:
{
"foo": "bar",
"some": "value"
}
To use the value of foo in a subsequent ADF activity, you would reference #activity('Web1').output.foo. ADFv2 provides multiple type conversion functions, should you need the returned value converted to another type.
If your function is returning an empty JSON response back, you may want to inspect the response from your function using Postman or another tool to ensure you are returning a properly formatted response, and that your function isn't failing for another reason.
Inside your Azure function code, you should be returning a JSON object, along with a success code, similar to return req.CreateResponse(HttpStatusCode.OK, json);.
Also note that if you reference a property of the response and it does not exist, ADF will fail at that point, so you can use an If Condition activity to check for the required values to better handle failures in ADFv2.

Pagination response payload from a RESTful API

I want to support pagination in my RESTful API.
My API method should return a JSON list of product via /products/index. However, there are potentially thousands of products, and I want to page through them, so my request should look something like this:
/products/index?page_number=5&page_size=20
But what does my JSON response need to look like? Would API consumers typically expect pagination meta data in the response? Or is only an array of products necessary? Why?
It looks like Twitter's API includes meta data: https://dev.twitter.com/docs/api/1/get/lists/members (see Example Request).
With meta data:
{
"page_number": 5,
"page_size": 20,
"total_record_count": 521,
"records": [
{
"id": 1,
"name": "Widget #1"
},
{
"id": 2,
"name": "Widget #2"
},
{
"id": 3,
"name": "Widget #3"
}
]
}
Just an array of products (no meta data):
[
{
"id": 1,
"name": "Widget #1"
},
{
"id": 2,
"name": "Widget #2"
},
{
"id": 3,
"name": "Widget #3"
}
]
ReSTful APIs are consumed primarily by other systems, which is why I put paging data in the response headers. However, some API consumers may not have direct access to the response headers, or may be building a UX over your API, so providing a way to retrieve (on demand) the metadata in the JSON response is a plus.
I believe your implementation should include machine-readable metadata as a default, and human-readable metadata when requested. The human-readable metadata could be returned with every request if you like or, preferably, on-demand via a query parameter, such as include=metadata or include_metadata=true.
In your particular scenario, I would include the URI for each product with the record. This makes it easy for the API consumer to create links to the individual products. I would also set some reasonable expectations as per the limits of my paging requests. Implementing and documenting default settings for page size is an acceptable practice. For example, GitHub's API sets the default page size to 30 records with a maximum of 100, plus sets a rate limit on the number of times you can query the API. If your API has a default page size, then the query string can just specify the page index.
In the human-readable scenario, when navigating to /products?page=5&per_page=20&include=metadata, the response could be:
{
"_metadata":
{
"page": 5,
"per_page": 20,
"page_count": 20,
"total_count": 521,
"Links": [
{"self": "/products?page=5&per_page=20"},
{"first": "/products?page=0&per_page=20"},
{"previous": "/products?page=4&per_page=20"},
{"next": "/products?page=6&per_page=20"},
{"last": "/products?page=26&per_page=20"},
]
},
"records": [
{
"id": 1,
"name": "Widget #1",
"uri": "/products/1"
},
{
"id": 2,
"name": "Widget #2",
"uri": "/products/2"
},
{
"id": 3,
"name": "Widget #3",
"uri": "/products/3"
}
]
}
For machine-readable metadata, I would add Link headers to the response:
Link: </products?page=5&perPage=20>;rel=self,</products?page=0&perPage=20>;rel=first,</products?page=4&perPage=20>;rel=previous,</products?page=6&perPage=20>;rel=next,</products?page=26&perPage=20>;rel=last
(the Link header value should be urlencoded)
...and possibly a custom total-count response header, if you so choose:
total-count: 521
The other paging data revealed in the human-centric metadata might be superfluous for machine-centric metadata, as the link headers let me know which page I am on and the number per page, and I can quickly retrieve the number of records in the array. Therefore, I would probably only create a header for the total count. You can always change your mind later and add more metadata.
As an aside, you may notice I removed /index from your URI. A generally accepted convention is to have your ReST endpoint expose collections. Having /index at the end muddies that up slightly.
These are just a few things I like to have when consuming/creating an API.
I would recommend adding headers for the same. Moving metadata to headers helps in getting rid of envelops like result , data or records and response body only contains the data we need. You can use Link header if you generate pagination links too.
HTTP/1.1 200
Pagination-Count: 100
Pagination-Page: 5
Pagination-Limit: 20
Content-Type: application/json
[
{
"id": 10,
"name": "shirt",
"color": "red",
"price": "$23"
},
{
"id": 11,
"name": "shirt",
"color": "blue",
"price": "$25"
}
]
For details refer to:
https://github.com/adnan-kamili/rest-api-response-format
For swagger file:
https://github.com/adnan-kamili/swagger-response-template
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
Without the total count, how can the client know that it has not yet received everything there is and should continue paging through the result set? In a UI that didn't perform look ahead to the next page, in the worst case this might be represented as a Next/More link that didn't actually fetch any more data.
Including metadata in the response allows the client to track less state. Now I don't have to match up my REST request with the response, as the response contains the metadata necessary to reconstruct the request state (in this case the cursor into the dataset).
If the state is part of the response, I can perform multiple requests into the same dataset simultaneously, and I can handle the requests in any order they happen to arrive in which is not necessarily the order I made the requests in.
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
just add in your backend API new property's into response body.
from example .net core:
[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
var users = await _repo.GetUsers(userParams);
var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);
// create new object and add into it total count param etc
var UsersListResult = new
{
usersToReturn,
currentPage = users.CurrentPage,
pageSize = users.PageSize,
totalCount = users.TotalCount,
totalPages = users.TotalPages
};
return Ok(UsersListResult);
}
In body response it look like this
{
"usersToReturn": [
{
"userId": 1,
"username": "nancycaldwell#conjurica.com",
"firstName": "Joann",
"lastName": "Wilson",
"city": "Armstrong",
"phoneNumber": "+1 (893) 515-2172"
},
{
"userId": 2,
"username": "zelmasheppard#conjurica.com",
"firstName": "Booth",
"lastName": "Drake",
"city": "Franks",
"phoneNumber": "+1 (800) 493-2168"
}
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44
}
This is an interessting question and may be perceived with different arguments. As per the general standard meta related data should be communicated in the response headers e.g. MIME type and HTTP codes. However, the tendency I seem to have observed is that information related to counts and pagination typically are communicated at the top of the response body. Just to provide an example of this The New York Times REST API communicate the count at the top of the response body (https://developer.nytimes.com/apis).
The question for me is wheter or not to comply with the general norms or adopt and do a response message construction that "fits the purpose" so to speak. You can argue for both and providers do this differently, so I believe it comes down to what makes sense in your particular context.
As a general recommendation ALL meta data should be communicated in the headers. For the same reason I have upvoted the suggested answer from #adnan kamili.
However, it is not "wrong" to included some sort of meta related information such as counts or pagination in the body.
generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn"
with theses parameters, you can do it a simple request.
in the service, eg. .net
jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
from tbANyThing tt
where id > lastIdObtained
order by id
}
In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got