Here is the third part of my Java EE series and this week it's time to tackle how to create a REST API using a proper framework. There are many existing Java frameworks that would help you achieve that, some of the most popular are Spark, RESTEasy, RESTX or Jersey. As I have no experience with any of them and no specific constraint, I picked up Jersey which seems to have a good API, descent support from the community and it's an implementation of the JAX-RS reference. So let's get started!
If you missed the two previous chapters, here are the links as I'm reusing the same project rather than starting one from scratch:
The first thing I'm going to do is to convert my project to a Maven project (obviously a prerequisite is to have Maven installed): Right-click your Eclipse project > Configure > Convert to Maven Project
This will generate a pom.xml file at the project root. Just copy all the Jersey dependencies (<dependencies> section) similarly to my pom.xml:
Then Right-click your Eclipse project > Maven > Update Project ... This should download locally all the Jersey dependencies defined in the pom.xml, sweet! ...
Make also sure those dependencies are part of the deployment package:
Right-click project > Properties > Java Build Path > Order and Export > Check Maven Dependencies
Then still from Properties > Deployment Assembly > Java Build Path Entries > Maven Dependencies
My Deployment package looks as follow:
Next we need to define a Servlet mapping, this is done by editing the web.xml. If you created a dynamic web project with module version 3.0, there are chances you don't have a web.xml, so Right-click project > Java EE Tools > Generate Deployment Descriptor Stub
From there we define a url mapping that will be redirected to the Jersey server and also a provider package: in my case all the classes part of "com.autodesk.adn.viewanddata.api" package will be considered as resource for the Jersey server.
The last step is the implementation of the API itself and if you take a look at Part II, you will notice that it is significantly more straightforward when using Jersey as it handles parsing of the url and parameters nicely:
You can then run your project from Eclipse which should launch the Tomcat server and let you test the API using a Rest client as described in Part II.
The implementation still relies on a clunky hashmap, so next time I will take a look at how to use a mongoDB connector so it will fetch the records from a real database... stay tuned!