Web API GET method with two complex parameters - json

I have a Web API program that has 8 get methods.
Each method can get 2 parameters - filters and sorts.
filters - a json object that contains all the params you can filter by
sorts - an array that contains all the properties you want to sort by
For example:
www.facebook.com/GetFriends?filters={name:"lior", color:{name:"blue", RGB:{255, 100, 0}}}&sorts=[{prop:"name", desc:true}, {prop:"age", desc:false}]
The api's only available from other servers, so there's no need to worry about URL characters limit in browsers.
We chose GET method because the purpose of this api is only to get data.
I'm not sure the url we require is in a 'normal' format-
Is that okay in a GET method to use a two query params that one of them is json and the other is array?
Thank you for your help

Related

Jenkins API xpath like functionality for JSON

I am trying to use the jenkins API to retrieve a list of running jobs buildURLs and this works with this the query
https://jenkins.server.com/computer/api/xml?tree=computer[executors[currentExecutable[url]]]&depth=1&xpath=//url&wrapper=buildUrls
By searching for all executors on given jenkins server and then grabbing the urls and wrapping them in a xml buildUrls object
(what I actually want is a count of total running jobs but I can filter in api then get a .size of this once client side)
However the application I am uses only accepts json, although I could convert to json I am wondering if there is a way I can have this return a json object which contains just the buildUrls. Currently if I change return to json the xpath modification is removed (since its xml only)
And I instead get returned the list of all executors and their status
I think my answer lies within Tree but i cant seem to get the result I want
To return a JSON object you can modify the URL as below
http://jenkins.server.com/computer/api/json?tree=computer[executors[currentExecutable[url]]]&depth=1&pretty=true
It will not be possible to get only the build urls you need to iterate through all the executables to get the total running jobs. The reason is that build urls alone cannot give you information where it is running. Hence, unfortunately we need to iterate through each executor.
The output you will get is something like below.
Another way of doing this same thing is parsing via jobs
http://jenkins.server.com/api/json?tree=jobs[name,url,lastBuild[building,timestamp]]&pretty=true
You can check for building parameter. But here too you will not be able to filter output from url diretly in jenkins. Iteration would be required through each and every job.

What are developers their expectations when receiving a JSON response from a server

I have java library that runs webservices and these return a response in XML. The webservices all revolve around giving a list of details about items. Recently, changes were made to allow the services to return JSON by simply converting the XML to JSON. When looking at the responses, I saw they're not as easy to parse as I thought. For example, a webservice that returns details about items.
If there are no items, the returned JSON is as follows:
{"ItemResponse":""}
If there is 1 item, the response is as follows (now itemResponse has a object as value instead of a string):
{"ItemResponse":{"Items":{"Name":"Item1","Cost":"$5"}}}
If there two or more items, the response is (now items has an array as value instead of an object):
{"ItemResponse":{"Items":[{"Name":"Item1","Cost":"$5"},{"Name":"Item2","Cost":"$3"}]}}
To parse these you need several if/else which I think are clunky.
Would it be an improvement if the responses were:
0 items: []
1 item: [{"Name":"Item1","Cost":"$5"}]
2 items: [{"Name":"Item1","Cost":"$5"},{"Name":"Item2","Cost":"$3"}]
This way there is always an array, and it contains the itemdata. An extra wrapper object is possible:
0 items: {"Items":[]}
1 item: {"Items":[{"Name":"Item1","Cost":"$5"}]}
2 items: {"Items":[{"Name":"Item1","Cost":"$5"},{"Name":"Item2","Cost":"$3"}]}
I'm not experienced in JSON so my question is, if you were a developer having to use these webservices, how would you expect the JSON resonse to be formatted? Is it better to always return a consistent array, even if there are no items or is this usually not important? Or is an array not enough and do you really expect a wrapper object around the array?
What are conventions/standards regarding this?
Don't switch result types, always return an array if there are more items possible. Do not mix, for 1 item an object for more an array. That's not a good idea.
Another best practise is that you should version your API. Use something like yoursite.com/api/v1/endpoint. If you don't do this and you change the response of your API. All your client apps will break. So keep this in mind together with documentation. (I've seen this happen a lot in the past..)
As a developer I personally like your second approach, but again it's a preference. There is no standard for this.
There are several reasons to use json:
much more dense and compact: thus data sent is less
in javascript you can directly access those properties without parsing anything. this means you could convert it into an object read the attributes (often used for AJAX)
also in java you usually don't need to parse the json by yourself - there are several nice libs like www.json.org/java/index.html
if you need to know how json is build ... use google ... there tons of infos.
To your actual questions:
for webservices you often could choose between xml and json as a "consumer" try:
https://maps.googleapis.com/maps/api/place/textsearch/json
and
https://maps.googleapis.com/maps/api/place/textsearch/xml
there is no need to format json visually - is it not meant for reading like xml
if your response doesn't have a result, json-service often still is giving a response text - look again at the upper google map links - those are including a response status which makes sense as it is a service.
Nevertheless it's the question if it is worth converting from xml to json if there isn't a specific requirement. As Dieter mentioned: it depends on who is already using this service and how they are consumed ... which means the surrounding environment is very important.

Inconsistent response (JSON array lengths different) from Google Places API

When I make GET HTTP call to Google Places API. (Example Call: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=") ....
Under "results", inconsistent number of elements are returned. What is the base list of fields that will always be returned?
In the screenshot below, you can see how the array length count under "results" is different, counts are 11, 10, 10, and 8.
Screenshot below shows how one the JSON Arrays in the response has more elements than the other and the extra fields are circled in red.
I am confused here because I am trying to write code to parse the JSON and trying to understand which are the fields to expect? Missing fields in some arrays in the response is breaking my code.
Am I interpreting the API documentation incorrectly or Is this a bug that I should be filing with Google directly?
You might consider using logic that does not require any fields at all. Because the server is out of your control, it could return anything at any time (due to API changes, bugs, technical faults, etc.)
For example, in Sprockets I loop through whatever objects are returned and if the name matches something that I expect, then I process it. Otherwise the fields in my objects simply remain empty. You can see the top-level processing Java code in the PlacesResponse constructor.
It's not a bug, but documented behaviour. The Google Places API documentation says:
Each result within the results array may contain the following fields:
In other words, Google returns ratings, opening hours etc for places if it has them, but it will leave them out if it does not or the field is not relevant to the place (eg. you wouldn't have opening hours for an apartment complex or rate a train station). As #pushbit says, you have to parse accordingly and check whether each field was returned.

How to query ASP.NET Web API like OData, but with a POSTed JSON object, not a GET URL/QueryString?

How to query ASP.NET Web API, but with a JSON POST, not GET URL?
The JSON object would contain the same data/filters/sort/paging as ODATA query or LINQ query. Can we deserialize the JSON object into something ODATA/LINQ can understand and then use that to easily execute on the DB (SQL Server)?
We've come across from articles about LINQ Expression Trees and ODataLib ODataUriParser, but still researching.
We want to expose an advanced search web service for a few tables or views in SQL Server, and want to keep it JSON and generic so many platforms can consume it. The consumer would need to pass in the search parameters, and we could probably create a data structure to contain it all, but are trying to also see if we can leverage some query model in ODATA or LINQ.
Any way to instead of putting the OData query in the URL, put it as a POSTed JSON object instead and have it continue to query the DB and return results normally? A couple of current reasons to put in POST are 1. can handle larger size and 2. instead of the consumer learning OData query syntax, they can just popular an search param object model.
Thanks in advance.

questions wcf rest service with webclient

I'm getting confused on a few things in regards to wcf rest.
If you call a login method, should I use a POST or GET? After implementing a POST, I started to find various articles saying you should only use post to update data, and get for retrieving data. Which is the most appropriate method?
If I had to change the Login method from a Post to a Get, how would I call this?
http://....myservice.svc/login/{username}/{passpord} or is there another way to call this?
Note that in my post method, I'm passing and returning data in json format.
I need to create a search function that requires to pass various parameters i.e. list, string, list, etc... I assume in this instance I would have to define GET method, but again how to I pass these list of objects? Convert them to json first and pass them as parameters?
A brief url sample would be great.
Ok, I guess I'll answer my own question based on further finding when researching it and remember that my answer is based on using JSON as parameters. I'm not sure how it would behave if xml was used as I did not try it.
It appears to make more sense to use POST when logging in as you do not want to display the information you are posting via a url. You could encrypt the data and pass it in the url using a GET method... Again I could be wrong, but that's how I interpreted the various articles I read.
Again, in this instance, it appears POST is the best solution if a) you require a large amount of data to be passed to your url and b) if you do not want to show this data to the user. If your query only requires simple parameters (i.e. userid, type, etc...) and you don't mind showing this info, you can use the GET method.
If you require to pass multiple parameters to a function, you should instead pass a single parameter. This parameter should be a single object. This object should be made of all the parameters you wanted to use in the first place, this way, when using the POST method, this object can easily be converted to JSON and it will handle passing multiple parameters through a single object and it will handle numeric, string, list<>, array<>, etc... very nicely.