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

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/

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.

Partial response in Spring MVC

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

Node.js SOA with JSON web-services - configuration

I am starting research on how to implement Node.js SOA (service oriented architecture) with JSON web-services.
As a small sub-question, I need an approach/framework/system to make universal configuration center for all companies web-services. So that we don't configure every application with exact address of other application, but just link to some central server to get that information.
(This should be very well worked-out topic for XML-based services, so some terminology/approaches/etc could/should be borrowed.)
Related to
RESTful JSON based SOA Registry
Service Oriented Architecture suggestions
UPDATE: This questions is about web-services configuration & orchestration.
GO for an active(having activity happening off late) framework with lean architecture.There's one called Geddy and another called Restify. If in doubt, Express can also be used for building webservices with JSON.
You can work on reading the centrally stored config from different app codebse when you use any of these.

ASP.NET web api: documenting/specifying a service

I've been looking at asp.net Web Api, and I like the simplicity of implementing a practical web service.
However, how can I document/specify the interface of a service implemented like that? For example, is there any spec I can pass on or generate to a Java guy with no .NET background that will let him easily call and consume the service? What can I give to the javascript guy?
Ideally, I'd like the benefits of SOAP/XSD or something like it (easy to deserialize with nicely typed objects) for the java guy, while retaining a service that's callable from a web browser too (i.e. supports non-crufy JSON).
Update
It's worth noting that since I originally posted this question, I discovered ServiceStack which deals with this more naturally; supporting JSON, SOAP, and WSDL out of the box for the same service, as the client chooses. If you really want SOAP+JSON, it may be a better framework than ASP.NET Web Api.
Update March 2016
It has been a while since this was answered and the tooling for documenting any Rest API has come along a lot. We are currently evaluating Swagger 2.0 now spawning out to the the Open Api Initiative, RAML and API Blueprint.
For WebAPI projects there is a tool Swashbuckle that auto creates Swagger (Open API) format documentation.
Format for documenting a REST service:
There are some attempts at structuring and standardising the description of REST services:
Web Application Desciption Language (WADL)
Web Service Description Language 2.0 (WSDL 2.0)
I think it is fair to say neither of the two approaches above have very wide adoption, but WADL does look like a nice concise format - a quick XSLT over the top and it could be a nice human readable format. There lots of examples of WADL for some famous API's at the apigee github site here.
When trying to find a documentation format that is appropriate I tend to look for "inspiration" from others.... Apigee do a lot of research in this area and have this as documentation for one of their API's here or take a look at Facebook's social graph api here.
The examples are largely in line with the advise here
How to auto document:
Using .NET: There is a good example of auto generating a WebApi "help" page here. A logical extension of this example may be to get it outing a WADL formated version as well...
Using Java: Jersey is a tool used in the Java community to generate WADL automatically.
What to share with the other developers:
Your Javascript guy will most likely want a manual like the Facebook and apigee one; giving the dev examples of the resources, urls, response codes etc. The most important thing here will be supporting JSON as the primary content type this will be the easiest for him/her to consume and work with by far.
Your Java guy would also want the manual, but also in theory they could be given example XSD for any XML representations of the resources you send/consume (assuming they make the request as "Content-Type: appplication/xml"). This may help them build proxy classes etc. JSON to Java and .NET converters are available online and given the example resources in your manual they should simply be able to use one of these types of services to quickly create proxies. Generate Java class from JSON?.
If you absolutely must have auto discovery, auto proxy generation etc then you may need to offer a choice of both REST and SOAP (with WSDL) endpoints - relevant question here: ReST Proxy Object Generator.
You can use IApiExplorer interface and ApiExplorer class in order to create a help page for your Web Api service. This help page will describe the REST methods exposed by your service so any developer who understands how REST works will be able to use it (regardless the language). Please read below links for details and samples:
ASP.NET Web API: Introducing IApiExplorer/ApiExplorer
ASP.NET Web API: Generating a Web API help page using ApiExplorer
Documenting your ASP.Net Web API’s

Creating a Groovy Portlet

I am getting started researching / creating a groovy portlet that will connect to a REST based ESB service that returns JSON; I will also need to pass the username in the headers. I was wondering if there are any examples out there on how to create the portlet and set the headers? I am new to groovy and from what I understand this can be accomplished rather easily. Essentially I want a portlet that will allow a user to search for a widget via a search box and return a list of matches. Not sure that it matters but the portlet will be deployed to the Vignette Portal. Any info would be much appreciated!
Thanks in Advance!
Doing a portlet with Java/Groovy is very doable with Spring Portlet MVC. I used some sample code from various sources a year ago but googling on it will give you more modern examples and let you pick something more applicable to your app. The real issue comes up with how you plan on building your app. Gradle is the best option for writing a Groovy web app.
However if you are talking about using Grails, then it becomes much more difficult and I would not advise learning Grails as you are trying to get it jammed into a 'portal' implementation. There are plugins for Liferay and 'portlets' in Grails but when I last looked at them earlier this year, they did not seem fully baked.
Calling REST based services with JSON or whatever from your server code doesn't have to care that you are in a 'portal'. The big issues comes up when you are trying to create the UI with your portal provider specific APIs. Don't be fooled into thinking you won't be using portal specific stuff. We used Liferay a bit and from my perspective the Portlet spec was very slim so to do much of anything interesting in a portal, you have to use some portal specific stuff, at least for UI and authentication services.
So my suggestion is build a Gradle Groovy Web project and use the Spring Portlet MVC Java examples to get something going and then you can simplify with Groovy as it makes sense. Initially you might want to simply start with Java if that is your comfort zone because integrating with your portal might be daunting enough without trying to learn a new language to boot.