What's the best RESTful web framework to use with Java


Introduction

Let us talk about what’s the best Java RESTful web framework to use with Java language. We know there are a lot of frameworks available but the “Spring Boot” is the best choice among other Java frameworks.

Here we will talk about the usage of the RestTemplate and integration of various data formats including JSON, XML, and HTML using the Spring Boot framework. We will also discuss various approaches to handling HTTP requests. We will learn why Spring Boot is the ideal framework for creating RESTful web services in Java by understanding this article.

Support of HTTP in Spring Boot:

The HTTP support is a very important part of RESTful web services and Spring Boot and Spring Boot provides us with excellent features to handle various HTTP methods.

In this programming example we will learn about how to support of HTTP in Spring Boot.

Example

public class UserController 
{
private UserService userService; 
   public UserController(UserService userService)
 {
      this.userService = userService;
   }
   @GetMapping("/{id}")
   public User getUser(@PathVariable("id") int id)
 {
      // Get information about the user
      return userService.getUserById(id);
   }
   @PostMapping
   public User createUser(@RequestBody User user) 
{
      return userService.saveUser(user);
   }
   @PutMapping("/{id}")
   public User updateUser(@PathVariable("id") int id, @RequestBody User user) 
{
      // Update about the user
      return userService.updateUser(id, user);
   }
   @DeleteMapping("/{id}")
   public void deleteUser(@PathVariable("id") int id) 
{
      // Deletion part
      userService.deleteUser(id);
   }
}

We have defined a class named UserController and inside this function we have called the constructor of the class named usercontroller and passed the value of userService inside its parenthesis. To initialize the value, we have called “this” operator.

public UserController(UserService userService)
 {
    this.userService = userService;
 }

After that we have got map id and get the information of the user.

public User getUser(@PathVariable("id") int id)
{
   return userService.getUserById(id);
}

Now we have deleted the mapping.

public void deleteUser(@PathVariable("id") int id) 
{
   userService.deleteUser(id);
}	

Use of spring boot framework with RestTemplate

The RestTemplate class in Spring Boot offer us an excellent and efficient method for using RESTful APIs. A simpler approach for managing HTTP requests and responses is provided by RestTemplate and this is a component of the Spring Web framework. It makes it simpler for our Spring Boot application to use external APIs by abstracting away the technical aspects of HTTP communication.

Example

In this particular programming example, we will see how to use of spring boot framework with RestTemplate.

import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/personn")
public class UserController 
{
   @GetMapping("/{id}")
   public ResponseEntity< personn > getUser(@PathVariable("id") int id)
 {
      RestTemplate restTemplate = new RestTemplate ();
      String apiUrl = "https://api.example.com/users/{id}";
      ResponseEntity< personn > responseEntity = restTemplate.exchange (apiUrl, HttpMethod.GET, null, User.class, id);
      return ResponseEntity.ok().body(responseEntity.getBody());
   }
}
 ** person.java class **
public class personn 
{
   private int id;
   private String name;
}

To do this at first, we have imported some important packages.

org.springframework.http.HttpMethod;
org.springframework.http.ResponseEntity;
org.springframework.web.bind.annotation.*;

After that we have done the request mapping for the user and define a class named UserController.

public class UserController 
{
   @GetMapping("/{id}")
   public ResponseEntity< personn > getUser(@PathVariable("id") int id)
   Then we will declare a string named “apiurl” and assign ther user id.
   tring apiUrl = "https://api.example.com/users/{id}";
}

Lastly, we have defined another class named Person and inside the class we have declared two variables named “id” which is string type another one is “name” which is string type.

public class personn 
{
   private int id;
   private String name;
}

Spring Boot Framework Supports JSON, XML, and HTML Formats

In this programming example we will learn about how Spring Boot Framework Supports JSON, XML, and HTML Formats.

Example

In this programming example we will learn about how Spring Boot Framework Supports JSON, XML, and HTML Formats.

@RestController
@RequestMapping("/users")
public class UserController 
{
   @GetMapping(value = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_HTML_VALUE})
   public ResponseEntity<User> getUser(@PathVariable("id") int id) 
{
      User user = getUserFromDatabase (id);
      // Return different representations based on requested media type
      if (MediaType.APPLICATION_JSON_VALUE.equals(getRequestedMediaType())) {
         return ResponseEntity.ok().body (user);
      } else if (MediaType.APPLICATION_XML_VALUE.equals(getRequestedMediaType())) {
         return ResponseEntity.ok().header("Content-Type", MediaType.APPLICATION_XML_VALUE).body (user);
      } else if (MediaType.TEXT_HTML_VALUE.equals(getRequestedMediaType())) {
         String userHtml = generateUserHtml (user);
         return ResponseEntity.ok().header("Content-Type", MediaType.TEXT_HTML_VALUE).body(userHtml);
      } else {
         return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build();
      }
   }
   private User getUserFromDatabase (int id) 
{
      return new User(id, "Aditi Dey");
   }
   private String getRequestedMediaType() 
{
      String requestedMediaType = "application/json"; 
// Default to JSON
      String requestedMediaTypeQueryParam = "mediaType";
      if (StringUtils.isNotBlank(requestedMediaTypeQueryParam)) 
{
         requestedMediaType = requestedMediaTypeQueryParam;
      }
      return requestedMediaType;
   }
   private String generateUserHtml(User user) 
{
      return "<h1>User Details</h1><p>ID: " + user.getId () + "</p><p>Name: " + user.getName () + "</p>";
}

To do this at first, we have defined a class named UserController for mapping the user id. Inside the class we have done the mapping work.

@GetMapping(value = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_HTML_VALUE})

Now we have called a function named getUserFromDatabase () and pass the id inside the parenthesis of this function as an argument. Then we have Returned different representations based on requested media type.

if (MediaType.APPLICATION_JSON_VALUE.equals(getRequestedMediaType())) {
   return ResponseEntity.ok().body (user);
} else if (MediaType.APPLICATION_XML_VALUE.equals(getRequestedMediaType())) 

Now we have got the user id from calling another function named getUserFromDataBase () and passed the id as an argument. Now we have got the media type by calling another function named getUserRequestedMediaType ().

private String getRequestedMediaType()
{
String requestedMediaType = "application/json";

if (StringUtils.isNotBlank(requestedMediaTypeQueryParam)) 
{
   requestedMediaType = requestedMediaTypeQueryParam;
}

Now the server can return the user information from the data base pool as response to the client.

private String generateUserHtml (User user)
{
   return "<h1>User Details</h1><p>ID: " + user.getId () + "</p><p>Name: " + user.getName () + "</p>";
}

Conclusion

Restful web framework to use with java is a very important concept in today’s software industry. It has a lot of prospect and application according to the requirement of client. For this it is really needed to learn this concept in a serious note. Hopefully all the learners get helped by this tutorial regarding this important concept in java.

Updated on: 04-Oct-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements