How to disable content negotiation and always return JSON from WCF data service? - json

Let's say I have a northwind database and I use ADO.NET Entity Data Model which I automatically generate from the tables in database. Then I add a new WCF data service that inherits from DataService. When I start the web application, that runs the service I can request data like this:
http://machine/Northwind.svc/Orders
This will return all orders from order table in atom/xml format. The problem is I do not want XML. I want JSON. I think I tried all kinds of settings (web.config) and attributes in my application, but I still get XML. No matter what. I can only get JSON, when I use fiddler and change the request header to accept JSON.
I do not like the concept of content negotiation. I want always to return data in JSON format. How can I achieve that?
Keep in mind that I did not create any model objects, they are automatically created based on database tables and relationships.

Well - content negotiation comes with HTTP. In any case, you could intercept the incoming request and add/overwrite the Accept header to always specify the JSON. There's a sample how to support JSONP which uses a similar trick, I think you should be able to modify it to always return JSON as well. http://archive.msdn.microsoft.com/DataServicesJSONP.

The behavior you criticize is defined by specification of OData protocol. OData defaults to Atom and client can control media type of the representation either by Accept HTTP header or by $format parameter in query string (but I'm not sure if WCF Data services already support this).

Related

How to Use Content Negotiation in Spring Data Rest?

I am trying to expose my data via Rest Api in difetents formats (xml,json,rdf,jsonld) and I am using Spring-Data-Rest-Framework and I know that it is posible using #RequestMapping in the Controller, buts in Spring Data Rest I only have a entity and a repository that use #RepositoryRestResource notation that does not support #RequestMapping notation.
Can somebody explain me the way to achieve expose my data in difente formats using Spring Data Rest ?
I would like to expecifice the format at the end of the URL like ( ?format=json or ?format=xml)
http://docs.spring.io/spring-data/rest/docs/current/reference/html/#representations.mapping
Currently, only JSON representations are supported. Other
representation types can be supported in the future by adding an
appropriate converter and updating the controller methods with the
appropriate content-type.
You would have to build your own converter for XML or other types. As well the standard way to define content type is in the Accept header. If you want to use an override then you need to add a filter to read the query parameter and set the header.

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.

wsdl for JSON returned REST services

I'm new to REST Web based services and trying to understanding how the contract is created for JSON returned REST services.
From my understanding, any XML based SOAP/REST services will have a WSDL document.
What document is created for JSON based REST Services?
a REST web service doesn't have any auto explanation document like wsdl, you need to know how the webservice works, reading the documentation provided with it. Generally it works with common requests. Assuming that you have a products REST webservice, you could have:
GET /products -> read all products
GET /products/1 -> read the product 1
POST /products -> create a new product
PUT /products/1 -> update product 1
DELETE /products/1 -> delete product 1
but you have to know which parameters you need to send to any request. I hope I was clear...
Every HTTP response has metadata in HTTP headers. One of those HTTP headers is ContentType. The content type identifies a media type which is the contract that the response payload must conform to. The specifications for media types can be found here http://www.iana.org/assignments/media-types/media-types.xhtml
One of the major differences between SOAP and HTTP (as an application protocol) is that SOAP defines the contract at design time, whereas with HTTP the contract is specified in the response message so it can change over time. Therefore it is important for the client to read the content type on each response to know how to process the response.
There is WADL (http://en.wikipedia.org/wiki/Web_Application_Description_Language) although it is not so much used as WSDL for SOAP. REST services written in Java EE automatically generate it as .../application.wadl, PHP suppor is pretty poor as far as I know.
As the others mentioned a web service definition is not necessary for RESTful services, however if you want to create something similar for your API the industry standard is Swagger/OpenAPI, though GraphQL schemas are also becoming a defacto standard too.
There are also a few other options you can also explore (see wikipedia).
Here is a list of the most common options:
swagger.json or openapi.json files in the OpenAPI Spec
GraphQL Schemas with full spec here
Postman Collections which can be published online.
RAML
RSDL

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.

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)