🏷 REST
3 patterns
Topic: REST
All Java patterns related to REST — java.evolved
Enterprise
Servlet versus JAX-RS
Old
@WebServlet("/users")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("id");
res.setContentType("application/json");
res.getWriter().write("{\"id\":\"" + id + "\"}");
}
}
Modern
@Path("/users")
public class UserResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(
@QueryParam("id") String id) {
return Response.ok(new User(id)).build();
}
}
hover to see modern →
JDK 11+
learn more →
Enterprise
SOAP Web Services vs Jakarta REST
Old
@WebService
public class UserWebService {
@WebMethod
public UserResponse getUser(
@WebParam(name = "id") String id) {
User user = findUser(id);
UserResponse res = new UserResponse();
res.setId(user.getId());
res.setName(user.getName());
return res;
}
}
Modern
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
@Inject
UserService userService;
@GET
@Path("/{id}")
public User getUser(@PathParam("id") String id) {
return userService.findById(id);
}
}
hover to see modern →
JDK 11+
learn more →
Enterprise
Spring Framework 7 API Versioning
Old
// Version 1 controller
@RestController
@RequestMapping("/api/v1/products")
public class ProductControllerV1 {
@GetMapping("/{id}")
public ProductDtoV1 getProduct(
@PathVariable Long id) {
return service.getV1(id);
}
}
// Version 2 — duplicated structure
@RestController
@RequestMapping("/api/v2/products")
public class ProductControllerV2 {
@GetMapping("/{id}")
public ProductDtoV2 getProduct(
@PathVariable Long id) {
return service.getV2(id);
}
}
Modern
// Configure versioning once
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(
ApiVersionConfigurer config) {
config.useRequestHeader("X-API-Version");
}
}
// Single controller, version per method
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping(value = "/{id}", version = "1")
public ProductDtoV1 getV1(@PathVariable Long id) {
return service.getV1(id);
}
@GetMapping(value = "/{id}", version = "2")
public ProductDtoV2 getV2(@PathVariable Long id) {
return service.getV2(id);
}
}
hover to see modern →
JDK 17+
learn more →