Day 19: RESTful API in Java with JAX-RS Framework
It’s first of the month, so re-kickstarting the challenge with freshness after a brief break . Let’s jump right into some coding action!
Project (1 hour): Build a RESTful service using JAX-RS the JAVA API for RESTful Web Services that will service user information.
All the code for this project can be found on my github
Step 1: Installation
- Download the latest version of JAX-RS from here.
- Assuming you have Eclipse already installed, setup tomcat webserver using the instructions here.
Step 2: Create project
- Create a new “Dynamic Web Project” in Eclipse, I created “RESTResourceServer”
- Add the downloaded JAX-RS jars (from /api, /ext, /lib) into “WEB-INF/lib” directory in the project.
- Add these jars from WEB-INF/lib into the library build path of the project by selecting “Add Jar”
- Create a package in your project, here we create “com.resourceserver”
- Create the following three classes User.java, UserDao.java and UserService.java
Note: We setup the web service using @Path annotation to UserService. Also we use the same annotation to set it to a method for UserService.
- Create Web.xml (available in github repo link above).
Step 3: Deploy the app
- Export the project as a “war” file and place it under webapps directory where tomcat server is installed.
- Start the web server using tomcat
Step 4: Submit request to RESTful app
- You can either use browser or an app such as postman in case you want to see results in more formatted way.
- Make a request to your app to get list of all the users using GET request http://localhost:8080/RESTResourceServer/rest/UserService/users
Day 19 of #100DaysOfCode DONE
If you enjoyed this, please click 👏 so that others can enjoy it as well. Follow me on Twitter @HariniLabs to get the latest updates or just to say Hi :)