Rest API Example with Java Jersey and Tomcat
The definition of the Jersey framework from their website:
Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides it’s own API that extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development. Jersey also exposes numerous extension SPIs so that developers may extend Jersey to best suit their needs.
You can read details from https://jersey.java.net
What I will try to show is creating a project from beginning and put more in time to make it a whole complete structure in this order:
- Create a project by using HTTP methods.
- Add database connection to the project and Authentication (tokens, roles)
- Add error mappings, logging requests and responses
- Jackson specific settings
I will be using Netbeans 8, Tomcat 7, Jersey 2.9.1, and Java 7.
Firstly create a new project by selecting Maven Web project.
After creating your project add dependencies as given below and we will be adding other dependencies when it is needed.
Jersey provides an abstract class Application declaring root resource and provider classes, and root resource and provider singleton instances. A Web service may extend this class to declare root resource and provider classes.
Alternatively it is possible to reuse ResourceConfig - Jersey’s own implementations of Application class that we will be using.
Simply you give the packages that you want to include in the project for deployment and register the properties like JSON and GZIP. Also you can register filters, singletons and other things as well.
At this stage if your IDE is giving error about web.xml or context.xml then simply put these files and will be used in the future posts.
web.xml
context.xml
The package I included in the main class was “com.jersey.test.data” and for the sake of simplicity I will add User model and the Users service to show methods.
These two classes have no specific property (user model and a map to put users inside while we have no database connection).
Your service definition starts with a “@Path(“/users”)” annotation which defines the root path of the class. You can add more lower levels before the methods like “@Path(“{userId}/orders”)” which will take user id as parameter and return the orders of that user. However be aware that adding conflicting classes will broke the URL schema and calling these URLs will give some runtime Exceptions.
You define the name of HTTP method with annotations as well (by using @GET, @POST, @PUT, @DELETE).
For the requests with @GET and @DELETE methods PathParam (directly in url like /users/14) or QueryParam (by using ? and values behind like /users?id=14) can be used (together or only one of them). However I highly recommend that if it is a REST-API then use PathParams to make it more readable.
Also you should read about REST a bit from this stackoverflow link. Honestly I don’t care about the talk ‘your api should match 100% to the rules otherwise your api is not a rest’ crap. The main idea is creating a standard that allows developers (for both server and client side) to make their jobs with ease. At the end call your api ‘like REST’ and then everyone will be happy.
Even though I said that is not important but at least you should be able to provide these properties.
- Proper url naming: It is quite easy and important thing since creating urls properly would make much easier to use you API.
Please do not use sentences at the urls and at least it should match the form of
- Proper usage of HTTP methods:
It should use @GET to retrieve data, @POST-@PUT to add and update data, and @DELETE to delete data. It may change with the specific methods but using this in your main models should be quite easy.
- Proper usage of HTTP Codes:
It is quite important to send proper HTTP Codes in your responses. It would be much easier to manage to responses and take action according to these codes (like if the code is 401 and can not refresh token then redirect to the login page). Again there are many codes but:
- Security with Auth Token and others if more needed (like JWT)
- Proper request responses and errors
I will continue the REST specifications in another post and return to the JERSEY.
For the requests with @POST and @PUT methods FormParam (like usual form parameter with username=msd&password=alp) or directly the object representation of request as it is used in the example (User user). However you must define the ‘ @Consumes(MediaType.APPLICATION_JSON)’ annotation for the method.
Also you may notice that some methods use the same path. Separation of unique methods are done by classical java method name and parameters on the compile time, path and http method on the runtime. Therefore you can define two methods with the same path and parameter but different HTTP method (GET or DELETE).
@Produces({MediaType.APPLICATION_JSON}) annotation takes a list of MediaType (or string like ‘application/json’) that defines the possible return types. It is possible to use two different response type in one method like
This is all the things you need for a simple project. I will be adding Redis, PostgreSQL, and Mysql for data access and caching in the next posts.