March 23, 2020
Estimated Post Reading Time ~

Overview on Building Restful Web Services Part – 2

Here in this post, we will see a few examples of how to create REST APIs.
REST API examples:
1) HTTP GET method example:
Create a sample class – MyRestApi as shown below:
MyRestApi.java: 
@Path("/sayHello") 
public class MyRestApi { 
    @GET 
    @Produces(MediaType.TEXT_HTML) 
    public String sayHello() { 
        return "<p>Hello</p>"; 
    }  
}

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 workspace and build project. Once the build is successful, deploy the project on tomcat server by following the steps below:
1.    Go to the 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:
@Path("/user") 
public class UserInformation { 
    UserLoginInfo loginInfo; 
    @Path("/info") 
    @POST 
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
    @Produces(MediaType.TEXT_PLAIN) 
    public String login(@FormParam("username") String username, @FormParam("password") String password) { 
        loginInfo= new UserLoginInfo(); 
        String userCredentials = loginInfo.getUserdetails(username, password); 
        if (userCredentials  != null) 
            return userCredentials; 
        else 
            return "{\"error\":\"invalid user\"}";  
}

UserLoginInfo.java: 
public class UserLoginInfo{  
         public String getUserdetails(String username, String password) {  
                  String uname  = username;          
                  String pwd = password;          
                  String credentails = uname  + "###" + pwd;          
                  return credentails;      
         }  
}

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 the Send button to see the output as shown in the following screenshot:
Output:
3) File Upload Example:
FileUpload.java:
@Path("/file")
public class FileUpload {
         @Path("/upload")
         @POST
         @Produces(MediaType.TEXT_PLAIN)
         @Consumes(MediaType.MULTIPART_FORM_DATA)
         public String uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
         @FormDataParam("file") FormDataContentDisposition fileDetail) {
                  String fileLocation = "D:\\" + fileDetail.getFileName();
                  try {
                           FileOutputStream out = new FileOutputStream(new File(fileLocation));
                           int read = 0;
                           byte[] bytes = new byte[1024];
                           out = new FileOutputStream(new File(fileLocation));
                           while ((read = uploadedInputStream.read(bytes)) != -1) {
                                    out.write(bytes, 0, read);
                           }
                           out.flush();
                           out.close();
                  } catch (IOException e) {
                           e.printStackTrace();
                  }
         String output = "File is successfully uploaded to:" + fileLocation;
         return output;
         }
}

Output:
This way you can build and test RESTful web services.

Source: https://labs.tadigital.com/index.php/2018/08/22/building-restful-web-services-part-2/



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.