Java

Building RESTful web services Part – 2

As discussed in the previous blog, let’s now see few examples on how to create REST APIs.

REST API examples:

1HTTP GET method example:

Create a sample class – MyRestApi as shown below:

MyRestApi.java: 

There are several points in the code that need highlighting:

  • Annotations: They are defined in javax.ws.rs.*, which are part of the JAX-RS (JSR 311) specification.
  • @Path: This defines the resource base URI. Formed with context root and hostname, the resource identifier will be something like http://localhost:8080/MyProject/rest/sayHello
  • @GET: This means that the following method responds to the HTTP GET method.
  • @Produces: Defines the response content MIME type as html text

 

Now clean the eclipse work space and build project. Once the build is successful, deploy the project on tomcat server by following the steps below:

  1. Go to servers tab and add your tomcat server.
  2. Right click on the project  —> Run as —> Run on server
  3. Once the project deployment is successful and the server is up, you can start testing your REST API using POSTMAN (Postman is a powerful HTTP client for testing web services. It is available as both a Google Chrome Packaged App and a Google Chrome in-browser app) by entering the request URL, HTTP method and hit on send button to see the output as shown in the following screenshot.

 

Output:

2) HTTPPOST method example:

Create a sample classes – UserInformation and UserLoginInfo as shown below:

UserInformation.java:

UserLoginInfo.java: 

There are several points in the code that need highlighting:

  • @Path: This defines the resource base URI. Formed with context root and hostname, the resource identifier will be something like http://localhost:8080/MyProject/rest/user/info
  • @POST: This means that the following method responds to the HTTP POST method.
  • @Consumes: Declares that the method consumes an HTML FORM.
  • @FormParam: Injects the form input identified by the HTML name attribute to this method.

 

NOTE: Once you enter the request URL, parameters and mention HTTP method in POSTMAN, click on send button to see the output as shown in the following screenshot:

Output:

3) File Upload Example:

FileUpload.java:

Output:

This way you can build and test RESTful web services.  I hope you enjoyed this blog post! 

About The Author

Leave a Reply

*