Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Lifecycle of a Request-Response Process for a Spring REST API

DZone's Guide to

Lifecycle of a Request-Response Process for a Spring REST API

The steps involved in the lifecycle of a request process and how the request is mapped to the appropriate controller method and then returned to the client.

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

Developing a REST API or microservice using the Spring Boot framework accelerates the development process, and allows API developers to only focus on writing the core business logic and not worry about all the underlying configurations and setup. This article describes the steps involved in the lifecycle of a request process and how the request is mapped to the appropriate controller method and how a response is returned to the client.

In order to create a REST API to serve a client with a list of users, the tasks involved are

  • Create a class with the @RestController annotation. Due to the annotation, this class will be auto-detected through classpath scanning and the methods annotated with @RequestMapping annotation will be exposed as HTTP endpoints. When an incoming request matches the requirements specified by the @RequestMapping annotation, the method will execute to serve the request.

For our example of a users API, the controller class will look like this:

@RestController

@RequestMapping("/users")
public class UserController {

                @Autowired
                UserService userService

                @RequestMapping(method = RequestMethod.GET)
                public List<UserDTO> findAllUsers() {

                                return userService.findAllUsers();

                }

}
  • Create a class for business logic.
  • Create a class to fetch data from the user table.
  • From a developer’s perspective, the flow to fetch the list of users from the database can be viewed as below:

    Image title

    However, with Spring doing a lot of work for us behind the scenes, the lifecycle of the entire process for making an HTTP request to a resource to serving the response back to the client in either XML/JSON format involves many more steps.

    This article describes the entire request to response lifecycle with steps which are managed by Spring.

    When a user makes a request for a resource, for example:

    Request: http://localhost:8080/users 

    Accept: application/json  

    This incoming request is handled by the DispatcherServlet, which is auto-configured by Spring Boot. While creating a project through the Spring Boot framework, and when we mention the Spring Boot Starter Web as a dependency in pom.xml, Spring Boot’s auto-configuration feature configures dispatcherServlet, a default error page, and other dependent jar files.

    When a Spring boot application is run, the log will have a message like this:

    [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]

    DispatcherServlet is the front controller and all incoming request goes through this single servlet. 

    The process from a request to response is shown in the below flow chart:

    Image title

    The blocks in the green are the ones which are implemented by developers.

    In our request for /users resources, the activities below are performed in each step:

    1. In Step 1, the dispatcher servlet will intercept the request for the resource /users. 

    2. In Step 2, the servlet determines the handler for the request (a good link on this topic).

    3. In Step 3, Spring checks which controller method matches the incoming lookup path of the “/users” request. Spring maintains a list of all mapping registries fetched from the @RequestMapping of the controller class and iterates the list to look for the matching method in the controller class implemented by the developer.

    4. In Step 4, after determining the right method it executes the controller method.

    5. Step 5 returns an ArrayList of users.

    6. The response type accepted by the client can be either JSON or XML. Therefore, Step 6 does the job of marshaling the Java object to the response type requested by the client. Spring takes the ArrayList of users and uses the message converter method to marshal it to the type requested by the client. If the converted message is not available, then the client will get a 406 error. In the case of users, as the requested type is JSON, thus a JSON object for users is returned as a response.

    Conclusion

    Understanding the lifecycle of the request and response process and other classes involved helps one to understand the issues better and troubleshoot it more easily. To check the process lifecycle, open the Eclipse Open Type DispatcherServlet class and add a breakpoint at the doDispatch method.

    Thanks a lot for reading this article! If you have any questions or suggestions, then please drop a note and I'll try to answer your question.

    Download A Buyer's Guide to Application and Data Integration, your one-stop-shop for research, checklists, and explanations for an application and data integration solution.

    Topics:
    java rest api ,integration ,api requests ,api integration

    Opinions expressed by DZone contributors are their own.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}