Make sure an incoming JSON response conforms to a schema? - json

I use Alamofire to interact with the server API via JSON requests/responses. I want to make sure server responds with some strictly formed payload to my requests.
How do I check that, for example, in {"responseCode":15, "data":{"username":"maxpayne", "fullname":"Max Payne", "score":154, friends:["johndoe", "franksinatra"]}}, responseCode is a number, username and fullname are strings, and friends is an array of strings?
I can do it manually for each response, but seems like it's going to be the most worthless time waste.
Alamofire has .validate() method but it is created for different purpose as what I see. I also had a look at JSONSchemaSwift which seems to be a right solution, but is not in active development.
As an alternative, it could be good to have a JSON deserializer which validates a response automatically and creates an object based on a Swift class I define.

May be a bit late, but this came out kylef/JSONSchema.swiftcame out on github. It's a JSONSchema validator, simple and effective.

Related

Create JSON Object in React.js from Rest Service

I am looking for either guidance or a good example where I can map data coming from rest services to JSON "type" object which can then be used in a number of different react components.
The JSON Object will be used to map data from a few different rest services, which essentially hold very similar data which makes it better to use one object and then to bind the data to the respective React Components.
I am fairly new to React.JS and I have googled around to find a data mapper to JSON from Rest Service example.
Can anyone help?
You typically don't have to do too much, at least on the front end side. As long as the REST endpoint can return JSON responses you'll be fine. Just make sure you set the appropriate Content-Type headers in the request. Note that setting the header doesn't guarantee a JSON response, the server has to be able to send it in that format.
If you're creating the REST service yourself, you have many options. If you're using node, you can simply return a javascript object. If you're using some other language like Java, C#, etc., they come with libraries that can serialize objects into JSON for you. I use JSON.net when working with C#. In these cases, because the data will be returned as a string, you'll just need to JSON.parse() it upon receiving it and then set it to the appropriate React component's state.

JSON REST endpoint returning / consuming JSON literals

Is it advisable or not in a RESTful web service to use JSON literal values (string / number) as input parameter in the payload or in the response body?
If I have an endpoint PUT /mytodolist is it OK for it to accept a JSON string literal value "Take out the rubbish" in the request payload (with Content-Type=application/json) or should it accept a JSON object instead ({"value":"Take out the rubbish"})?
Similarly, is it fine for GET /mytodolist/1 to return "Take out the rubbish" in the response body or should it return a proper JSON object {"value":"Take out the rubbish"}
Spring MVC to makes implementing and testing such endpoints easy, however clients have flagged this as non standard or hard to implement. In my point of view JSON literals are JSON, but not JSON objects, so I'd say it is fine. I have found no recommendations using Google.
EDIT 1: Clafirication
The question is entirely about the 'standard', if it allows this or not.
I understand the problem with the extensibility, but one can never design a fully extensible interface IMHO. If changes need to be done, we can try extending what we have in a backwards compatible way, but there will come a time when it becomes messy and an other approach is required - which is commonly handled by versioning the API in one way or another. I find it a fair point even though, because using literals as request/response body immediately becomes inextensible, while coming up with a reasonable one-attribute JSON object does not.
It is also understood that some frameworks have problems with handling JSON literals, this is the origin of this question. The tool I used happened to support this, so I thought this was all right, but the front-end library did not.
Still, what I am intending to find out right now, is if using JSON literals is according to the de-facto standard (even if it is a cornercase) or not.
I would recommend to use JSON object always. One reason is that for Content-Type application/json people expect something staring with "{" and not all frameworks will handle json literals properly. Second reason is that probably you will add some additional attributes to you list item (due date, category, priority, etc). And then you'll break backward compatibility, by adding new field.
It may be acceptable in the context of your example, but keep in mind that unambiguous interfaces are easier to use and that will encourage adoption.
For example, your interface could interpret "Take out he rubbish" as the same as {task:"take out the rubbish"}, but once you add additional properties (eg "when" or "who") the meaning of a solitary string in the request becomes ambiguous. It's inevitable that you'll add support for new properties as your interface matures.

Consuming JSON WCF on Silverlight

I'm want to try changing a SOAP WCF to accept requests and return results in JSON format to make the data traffic less bulky.
I see that JSON requests functions looks like this:
wcfClient.OpenReadAsync(http://yourUrl.com/wcf/service1.svc/GetEmployees)
and do the regular SOAP requests functions instead that looks like :
wcfClient.GetEmployeesAsync();
1) For JSON results, do you need to parse them into an object or is it automatically parsed like SOAP?
2) Is there a way to do this without doing too much work like changing every single WCF calls in the project to looks "JSON-ish"?
To complement Davut's answer - WCF does support building RESTful services, although I agree that the ASP.NET Web API framework in general easier to use than WCF. JSON.NET is a great library, and it has nice deserialization capabilities (e.g., it can easily take the JSON which represent the list of Employee objects and convert them into the actual List<Employee> instance)
But for completeness sake, if you want to use a "normal" WCF client to access WCF-based services which return JSON, you can do it. It's not too straightforward, but you can do that by using a new encoder and behavior which does the conversion. The post at http://blogs.msdn.com/b/carlosfigueira/archive/2010/04/29/consuming-rest-json-services-in-silverlight-4.aspx talks more about it, and has a pointer to a code sample.
In short, it's possible to consume JSON using a WCF client in Silverlight, but due to its complexity it's usually not done, and Davut's option (use a HTTP client such as WebClient to download JSON, then a library such as JSON.NET to parse it into objects) is preferred.
Firstly the idea "make the data traffic less bulky." is good.
Especially for Mobile devices. Beside this don't think that WCF xml causes network issues for PC. XM is the one of most compressible format. By WCF binary it goes as compressed.
For "Is there a way to do this without doing too much work?"
Yes there is a way name on it RESTFul Services(Restless Services). Now Microsoft directly support it by WEBApi.
Also you may use ODATA for filtering,ordering operations
Here are some links,
http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webgetattribute.aspx
http://blogs.msdn.com/b/rjacobs/archive/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4.aspx
ODATA
http://www.odata.org/documentation/uri-conventions#FilterSystemQueryOption
A few practice notes,Some restrictions:
EntityFrameWork entities derived from EntityObject which has IsReferenceType attribute doesn't allow you to JSON serialize. ( I produced POCO objects using an automapper mapped them and serialized json)
WEBAPI support you much think such as WebGet,WebInvoke GetXML Give JSON ,ODATA features(just select and format not allowed.)
Note:In your web request's header you should accept text/json to get really json.
"For JSON results, do you need to parse them into an object or..."
I can say you should try JSON.NET it's portable library works everywhere. When you deserialize with a generic function it returns you the collection you expect.
Hope it helps someone. While discovering these stackoverflow helped me like an assistant.

Common practice to HTTP Form POST a JSON string instead of using key/value fields?

Is it a common practice to create an HTTP POST end point (with the header "application/x-www-form-urlencoded") that takes in a JSON string as the value of the key/value POST data instead of having a list of fields as the POST data? Regardless of being common or not, is it considered bad since it requires more work to stringify the fields into a JSON string?
Example:
user={"username":"bob", "age":1} vs username=bob&age=1 in the POST form data.
This is actually very common - the SOAP messaging format does just this; replacing the standard POST body with a custom messaging format (in the case of SOAP it is XML).
The only thing to consider is that HTTP is pretty ubiquitous these days and although it is trivial to find a JSON library for any language, creating a HTTP body is utterly simple.
So it isn't bad by any means, but if the client is serializing to JSON and then you are deserializing from JSON, would it just be easier to use standard HTTP message bodies?

JSON vs Form POST

We're having a bit of a discussion on the subject of posting data to a REST endpoint. Since the objects are quite complex, the easiest solution is to simply serialize them as JSON and send this in the request body.
Now the question is this: Is this kosher? Or should the JSON be set as a form parameter like data=[JSON]? Or is sending of JSON in the request body just frowned upon for forcing the clients using the application, to send their data via JavaScript instead of letting the browser package it up as application/x-www-form-urlencoded?
I know all three options work. But which are OK? Or at least recommended?
I'd say that both methods will work well
it's important that you stay consistent across your APIs. The option I would personally choose is simply sending the content as application/json.
POST doesn't force you to use application/x-www-form-urlencoded - it's simply something that's used a lot because it's what webbrowsers use.
There is nothing wrong about sending it directly as serialized JSON, for example google does this by default in it's volley library (which obviously is their recommended REST library for android).
If fact, there are plenty of questions on SO about how not to use JSON, but rather perform "normal" POST requests with volley. Which is a bit counter intuitive for beginners, having to overwrite it's base class' getParams() method.
But google having it's own REST library doing this by default, would be my indicator that it is OK.
You can use JSON as part of the request data as the OP had stated all three options work.
The OP needs to support JSON input as it had to support contain complex structural content. However, think of it this way... are you making a request to do something or are you just sending what is basically document data and you just happen to use the POST operation as the equivalent of create new entry.
That being the case, what you have is basically a resource endpoint with CRUDL semantics. Following up on that you're actually not limited to application/json but any type that the resource endpoint is supposed to handle.
For non-resource endpoints
I find that (specifically for JAX-RS) the application/x-www-urlencoded one is better.
Consistency with OAuth 2.0 and OpenID Connect, they use application/x-www-urlencoded.
Easier to annotate the individual fields using Swagger Annotations
Swagger provides more defaults.
Postman generates a nice form for you to fill out and makes things easier to test.
Examples of non-resource endpoints:
Authentication
Authorization
Simple Search (though I would use GET on this one)
Non-simple search where there are many criteria
Sending a message/document (though I would also consider multipart/form-data so I can pass meta data along with the content, but JAX-RS does not have a standard for this one Jersey and RestEasy have their own implementations)