Partial response in Spring MVC - json

Our RESTful application need to support 'partial responses' to limit bandwith.
By this I mean that the REST client tells the URI service which fields of the resource it is interested in.
For instance: api/v1/users/123/fields=firstName,lastName,birthDate
We're using Jackson parser to convert our DTO's to a JSON structure.
The problem is that we cannot tell at runtime to 'skip' some properties.
We should need to create a class at runtime with a variable amount of properties to accomplish this. But I don't think this is possible in Java, it is a static language after all.
While searching the internet we found some semi-solutions by just returning a java.util.Map containing the requested properties or filtering out properties by the Jackson parser.
Especially the latter seems a 'hacking solution' to me. It seems that Spring MVC doesn't provide an out-of-the-box solution for this issue...
Is there any alternative in the Java world we can use to solve this issue?

How about Yoga
Yoga extends JAX-RS and SpringMVC RESTful servers to provide GData and LinkedIn style field selectors.
Choose which fields you want to see at call-time
Navigate entity relationships in a single call for complex views
Much faster speeds in high-latency (e.g. mobile) apps
Streamline client development
Browsable APIs

Related

What is the difference between Spring REST service, Jersey REST service and Spring+Jersey solutions?

I want to build a RESTful service/API. I used some framework like play to build it but I want to try other more efficient ways. I heard that Jersey is a common library for building a REST API, and Spring is also a good framework. But I also saw some solutions like Spring+Jersey. Thus, I am a little confused about those REST API solutions.
Can anyone tell me what is the difference among those? Jersey REST, Spring REST and Spring+Jersey REST?
My goal is building a couple of REST APIs that take JSON as input/output. I have jar file as the backend process logic to process the input a JSON/object and return a JSON/object.
Jersey is the JAX-RS API example implementation provided by Sun, while Spring REST is of course Spring's implementation of the same API/JSRs. The major difference is that Spring REST easily integrates into other Spring APIs (if you wish) such as Spring Data Rest.
There are a few noteworthy differences between them - you can "embed" Jersey Resources (known in Spring as Controllers) within each other, to enable a separate class that is responsible for the sub-path of a certain path, while this doesn't appear to be available in Spring right now (you have to define the full path). Also, in my opinion Jersey gives better "out of the box" error responses (such as why it can not map a JSON payload to a Java bean using Jackson) while Spring is a bit more configurable but plainer without some additional work.
In the end the difference in choosing between them usually comes down to - are you already or do you plan to integrate any other Spring libraries into your application? If so Spring REST is the way to go as you'll have a much easier time integrating it, otherwise it is really just personal preference which you'd prefer to use. Personally I like Jersey but the power of other related Spring projects (such as Spring HATEOAS which I highly recommend) makes Spring the better choice. I don't think there will be a real determining factor in your case.
As your "gold" target is a simple API with JSON input/output, I'd recommend you follow the Spring REST guide.
One major difference is in the area of unit testing support.
Jersey Test Framework does not lend itself for mocking server side code - For example, if your REST Resource depended on a Service, you would like to mock the service when testing resource methods. However, Jersey Tests run a separate container and unit tests sort of make calls to the running instance of your REST resource - at this point of time, I have not found any documentation or way for mocking server side code.
On the contrary, Spring MVC tests do not require any containers - and are more well integrated with its controllers. Dependency Injection can be used to inject mock services / DAOs to have better unit tests.
I also find that documentation on Spring projects are more mature when compared to Jersey.
One subtle difference is in the instantiation of the resource (Jersey) or controller (Spring) objects.
Jersey new's a resource object for each request. Whereas, by default Spring treats controllers as beans with default scope of singleton. This can be overridden with a #Scope annotation (although if you do that it will get flagged by Sonar).
This default behavior of Spring has bitten our application several times. With the controller class being a singleton, all class members are effectively static. So values set handling one request will still be there for the next.
This is something to be aware of if your using Spring. My suggestion is to #Scope the controller class as prototype, even though that will earn you a warning if you do Sonar scans.

How to create simple JSON API, e.g. with Jetty?

this seems pretty basic, but I am rather new to web development so I am a bit stuck here. I have MongoDB running on the backend, which contains geo-spatial objects that in the front end should be displayed on a map. The communication between backend and web frontend is where I have knowledge gaps.
The user should be able to zoom to an area on a map that he is interested in, then press "Search". The backend would then find every entry in the database that has coordinates that are on the users current screen. It would transmit these to the frontend, ideally as a list of JSON objects. The frontend displays these on a map.
I have a front end mock up, code that puts data into MongoDB and code that queries MongoDB. I know that I am missing a server that can be queried from the frontend. I thought I use Jetty. But what do I need to do then? I guess I need Jetty to provide a JSON API that I can query from JavaScript. Could someone point me to the Jetty class or interface that I need to implement and maybe give a few lines of code on how to query this from JavaScript?
You have a very open question here.
To start with, Jetty is merely a Java Web Container (following a subset of the Java EE Web Profile), while it does have some AJAX/JSON capabilities, it is extremely fundamental and not hooked up into any sort of query API.
You would do better do use Jetty along with a proper REST/JSON API library for your project.
Some examples (these are not the only choices available):
jersey - Jersey - an Open Source JAX-RS (JSR 311) implementation for RESTful web services, with JSON Support - Here's Lars Vogel's Tutorial on JAX-RS using Jersey.
restlet - Restlet - another RESTful web API, with a JSON extension
resteasy - RESTEasy - another JAX-RS implementation for RESTful web services, with JSON marshalling.
Also note that there are many flavors of Java based JSON APIs and Libraries, you should probably be aware of them as you will encounter them in your journey to success.
In the end I found the Dropwizard framework (there might be others), which does a lot of the work that is necessary to get a simple JSON API up out of the box:
http://dropwizard.io/

How can I create documentation or a JSON schema from Java classes compatible with Google Gson?

I am currently implementing a set of web services intended to be used by JavaScript clients and am using Google Gson for JSON serialization/deserialization. My service contracts are thus defined in Java classes. I now need a way of generating documentation of these message interfaces in a way intended to be used by JavaScript developers.
Ideally, I would like a tool along the lines of JavaDoc that generated JSON examples, JSON schemas or other Web developer friendly documentation of my types, that could easily be integrated with Maven to produce HTML based documentation for types with a certain annotation.
I can point them to the generated JavaDoc, but it will require them to understand and hunt through all private fields to work out how to format requests, and also does not take into account Gson type converters etc.
Are there any relevant tools available in this area?
I have used Swagger in the past. It is simple to implement, yet generates powerful API doc.
Please look at this documentation. I think this is what you are looking for.
http://petstore.swagger.wordnik.com/

Using WebAPI or MVC to return JSON in ASP.NET

I'm building an ASP.NET MVC application that is client-script heavy, it will use JSON and jQuery to manipulate the DOM.
My understanding is both Web API Controller and MVC Controller can return JSON.
Given my scenario, should I use a Web API Controller or an MVC Controller?
Web API Controllers can be created and hosted in any ASP.NET Application, not just MVC applications. Thus, an obvious reason to create a Web API is if you do not have an MVC front-end (e.g. classic, RESTful web-services hosted by your company/organization.)
MVC Controllers typically rely on the MVC Framework, if you look at default templates and most of the work done by the community and your peers you will notice that almost all MVC Controllers are implemented with the View in mind.
Personally, I use MVC Controllers when I intend to respond with a View(), and I'll use a Web API for anything that isn't dependent on a particular view.
There are caveats, of course, but generally speaking if you don't require the Model Binding behavior of MVC, your service is data-centric, and operations are Data-centric (e.g. CRUD operations) then you likely want a 'Web API Controller' instead of a 'Model-View Controller'. Conversely, if your operations are View-centric (e.g. delivering a user admin page to the user), or you need MVC's Model Binding to generate 'ajax partials' (very unlikely), then you will want an MVC Controller instead.
Personally, I use Web API controllers for driving JSON-based RESTful clients, I use MVC controllers for handling basic browser routing and delivery of the SPA.
WebAPI is for making an API. If you want someone to be able to consume your API in XML, JSON, etc. You can make a web api.
In your case you only need to talk to client in JSON.
Even though your website is mostly client script driven you would still be using ASP.NET MVC Controller right? And since you may have already logically divided your controllers based on entities then it make sense to add those json serving methods in it as opposed to making another class specifically for web api.
So for your particular situation (if i understand correctly), I would stick with Controllers.
The answer boils down to separation of concerns, fasten the creation of services and to rely on convention rather than configuration.
Controllers main responsibility is to work as a coordinator between view and your model but where as API's main responsibility is to work on data. In the case of API's conventions make it really easy to perform CRUD operations. Below is the mapping between CRUD operation and HTTP actions
GET : Read
POST: Create
PUT: Update
DELETE: Delete
So with APIs you do not have to create separate actions and attribute them with HTTP actions.
The only concern I have with ApiController is that it is site-based not area-based.
One site can only have one apicontroller subfolder for you to name your controller methods.
There are situations you might want to duplicate controller name in different areas :
domain.com/api/area1/controller1/
domain.com/api/area2/controller1/
I remember there are some custom code settings to be able to do this but it does not work by default.
I agree with Shaun Wilson's (top answer) answer but not sure why as I am just a bit confused and still trying to understand with the following (probably incorrect) premonition -
Use WebAPI Controller to deliver JSON data to the client so that the client can handle the view manipulation. This process doe NOT require a view but rather just a response back to whatever called the method (i.e. a javascript request) so that the client can handle any client-side manipulation.
Use MVC controller when you need to use the data to manipulate a view during or right after page_load (i.e. not for SPA apps).
You see, I just don't know how I am incorrect here and am confused because the last line of Shaun's answer states "I use MVC controllers for handling basic browser routing and delivery of the SPA."
- perhaps I do not fully know what a restful client is when I assumed it could be JavaScript method that receives an response in JSON form. this is the closest post in Stackoverflow that was remotely related as an answer to my question so I'm answering this post instead of possibly duplicating questions.
In this scenario, I would recommend WebApi as it's perfect for transferring data such as this based upon Javascript requests. I will usually develop my WebApi controllers so that they return a JSON friendly object that can then be parsed easily by my Javascript.
The only real time where you would want to use an action on an MVC controller for this sort of thing would be if you wanted to generate some HTML and replace segments of your page with Javascript calls.
For example:
You have a JQuery UI Datepicker that upon selection generates a list of radio buttons that represent events on the chosen day.
In this scenario, you could use WebApi to return some JSON and then generate the necessary HTML using Javascript but generally it's bad practise to create a lot of HTML using Javascript. It would be much better to have C# build up the HTML and then return it via a partial view as this way you are less likely to encounter errors with Javascript parsing. Not to mention it makes the HTML a lot easier to write.

How, in general, can web framework support REST style?

I would like to know, what are the ways a web framework may be suitable for designing a RESTful app, in general.
One goal is for example to provide http request routing, so they are automatically sent to appropriate controllers. From architectural point of view, web framework based on MVC pattern are more suitable for REST.
What other features of web frameworks are helpful by building apps satisfying the REST constraints?
Is there any reason why you consider certain languages(python/java) or web frameworks(django/turbogears/jersey/restlets/...) as the most applicable ones?
I think the best way for a web framework to support a RESTful style is to automatically map the different HTTP verbs (GET, POST, PUT, DELETE, etc.) to corresponding methods on its controllers/request handlers. Most modern Python web frameworks do this out of the box, with the notable exception of Django (unless I missed a dramatic change).
a) You need very flexible routing.
b) You need to be able to easily generate links that correlate to resource controllers using templates and parameters.
c) The server should help you to parse all the http headers. e.g. Authorization headers, Accept headers, language headers, cookies, etags.
d) It should support serializing and deserializing all the commonly used mime types.
e) It should help parsing parameters from incoming URLs
f) It should help resolving relative urls based on the request url and any available BaseURL.
There are few ways that a web framework can NOT support REST. Its basically written with the HTTP model in mind; so just about any web framework works. The automatic routing you mention is a common expectation, but not strictly required for REST.
I would stress the ability to directly support definition of resources. In Ruby on RAils you can define a resource through scaffolding and you get a model with controller with restful verbs implemented also with views and support for different formats and readily avalaible views and routing with ids.
Aside from that having access to HTTP and supporting principles of HTTP is what you need.
I am not experienced enough to know about support in frameworks, but it would be also nice to have support for the caching and other request options.
On the “specific software recommendation” front, I've had people recommend Apache CXF as a framework for building RESTful services with Java. It appears to be even able to simultaneously support SOAP (which happens to be very useful for helping some of our customer base adopt the software). I'm still in the experimenting-with-it stage though, so you may be able to do better.