Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Developing RESTful Endpoints with Spring WebMVC

Notes May 13 1

Constructing the web service layer is a fundamental task when building Spring Boot applications. Most modern internet systems rely on exposing various endpoints via HTTP. To meet these needs, Spring Boot provides several specialized solutions for creating lightweight web services.

The first approach is Spring WebMVC, a classic component built on the Model-View-Controller architecture. It allows developers to use a standard set of annotations to build controllers and expose RESTful HTTP endpoints. For client-side interactions, the RestTemplate utility is commonly used.

The second solution is Spring HATEOAS, which aligns with the highest level of the REST maturity model. It enables the creation of hypermedia-driven components, allowing APIs to be self-descriptive through links.

Finally, for complex data requirements in decoupled front-end and back-end environments, Spring GraphQL offers a graph-driven query language. This allows clients to specify the exact data structure and results they need, optimizing request frequency and payload size.

Building Services with Spring WebMVC

Spring WebMVC follows a decoupled architecture that facilitates the creation of flexible HTTP endpoints. Implementing a web service generally involves two stages: service definition (server-side) and service consumption (client-side).

Service Implementation

In Spring Boot, the core task of service creation revolves around the Controller. After defining a controller, you must manage incoming HTTP requests and return appropriate response data.

@RestController
@RequestMapping(value = "api/employees")
public class EmployeeController {

    @GetMapping(value = "/{empId}")
    public Employee fetchEmployeeById(@PathVariable String empId) {
        Employee emp = new Employee();
        emp.setEmployeeId(empId);
        emp.setFullName("John Doe");
        emp.setDepartment("Engineering");
        return emp;
    }
}

The Employee entity might look like this:

public class Employee {
    private String employeeId;
    private String fullName;
    private String department;
    private Integer yearsOfService;
    private List<String> projectCodes;

    // Getters and Setters
    public String getEmployeeId() { return employeeId; }
    public void setEmployeeId(String employeeId) { this.employeeId = employeeId; }
    public String getFullName() { return fullName; }
    public void setFullName(String fullName) { this.fullName = fullName; }
    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }
    public Integer getYearsOfService() { return yearsOfService; }
    public void setYearsOfService(Integer yearsOfService) { this.yearsOfService = yearsOfService; }
    public List<String> getProjectCodes() { return projectCodes; }
    public void setProjectCodes(List<String> projectCodes) { this.projectCodes = projectCodes; }
}

The @RestController annotation simplifies development by combining @Controller and @ResponseBody. This ensures that data is automatically serialized and deserialized into formats like JSON.

Method-level annotations such as @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping provide a clear way to specify HTTP verbs. These are specialized versions of the generic @RequestMapping annotation.

Handling Web Requests

Managing web requests involves mapping input parameters and generating responses. Spring Boot provides specific annotations to capture data from different parts of an HTTP request.

@PathVariable is used to extract values directly from the URL path. For example, in a route like /api/employees/{empId}, the value in the braces is mapped to a method argument.

@PostMapping(value = "/register/{dept}/{role}")
public Employee createEmployee(@PathVariable("dept") String dept, @PathVariable("role") String role) {
    Employee emp = new Employee();
    emp.setDepartment(dept);
    return emp;
}

You can also define the media type produced by the controller using the produces attribute in the mapping annotation, typically set to application/json.

To handle complex data sent in request body, @RequestBody is used. This annotation binds the incoming JSON payload to a Java object.

@PostMapping(value = "/save")
public Employee persistEmployee(@RequestBody Employee employee) {
    // Logic to save the employee object
    return employee;
}

Consuming Web Services

Once a controller is exposed, other services or clients need a way to consume those endpoints. Spring Boot offers the RestTemplate for this purpose.

Initializing RestTemplate

A common practice is to define RestTemplate as a Bean so it can be injected throughout the application context.

@SpringBootApplication
public class WebClientConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Executing Requests

RestTemplate utilizes JSON for serialization by default. It provides several methods to interact with remote services, mapping HTTP methods to Java methods such as getForObject(), postForEntity(), and exchange().

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.