Getting Up and Running with REST and Spring Boot
To design a RESTful app, the urls should be like this,
- Retrieve all Users - GET /users
- Create a User - POST /users
- Retrieve one User - GET /users/{id} -> /users/1
- Delete a User - DELETE /users/{id} -> /users/1
- Retrieve all posts for a User - GET /users/{id}/posts
- Create a post for a User - POST /users/{id}/posts
- Retrieve details of a post - GET /users/{id}/posts/{post_id}
1. Initializing a RESTful Service Project with Spring Boot
- Creating a project using SPRING INITIALIZER in
start.spring.io. We need to specifyproject type (Maven),Language (Java),Spring Boot version (2.2.0 snapshop),Project Metadata (Group - com.example, Artifact - todoList),Dependencies (Web, DevTools, JPA, h2). Then we can generate our project.
2. Review of Spring Boot Auto Confinuration and Dispatcher Servlet
- What is dispatcher servlet?
Mapping servelt: 'dispatacherServlet' to [/]. So this is the root of the web application. It is handling all the requests. - Who is configuring dispatcher servlet?
- What does dispatcher servlet do? It handling the request first. This is following a pattern called front controller. Dispatcher servlet is the front controller for Spring web MVC framework. Dispatcher servlet knows all the different mappings which are present in the application. So once it gets the request, it determines which is the right controller to execute that request. So it looks at the URI and the request method.
After it gets the response, due to the@ResponseBodyin@RestController, then the response would be mapped by a message converter into some other format. Here the message converter which is going to be used is Jackson. - How does the HelloWorldBean object get converted to JSON? It is because of Spring Boot auto configuration. Because message converters and the Jackson beans are getting initialized.
- Who is configuring the error mapping? Again Spring Boot auto configuration. It creates a default error page for us.
Tip: In file application.properties, we can change the logging level in spring framework.
3. Enhancing the service with a Path Variable
The input of our method, we use @PathVariable. Path variable is a critical part of creating REST resources.