Spring Boot – Add REST Controllers

In this lesson, we are going to add REST controllers to our application. Remember that in the last tutorial, we added a business service.

Now the question is: What is a REST Controller? Let’s see

 

  1. What is a Rest Controller
  2. Add the User Controller
  3. Add the Post Controller
  4. Add the Location Controller

 

1. What is a REST Controller?

A REST is a java class that is annotated with the @RestController annotation. But what does a REST Controller do? A REST controller contains the function that executes when a url request is received.

So a REST controller is the endpoint that receives requests coming from a client. Additionally, a REST controller the code that sends back a response to the client after the request is executed.

Finally, a REST controller provides mappings that map particular url patterns to methods defined in the controller

 

2. Add the User Controller

You need to add a controller that responds to user-related requests. For example, request for list of users. Or maybe request for a single user. Or even to add or delete a user.

Add a new file to to the users package. Name it UserController. I’ve written the content out for you. So you can copy and paste.

 

package user;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

}

 

3. Add the Post Controller

You need to add a controller that responds to post-related requests. For example, request for list of posts. Or maybe request for posts by user or by date. Or even to add or delete a post.

Add a new file to to the post package. Name it PostController. I’ve written the content out for you. So you can copy and paste.

 

package post;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class PostController {

}

 

4. Add the Location Controller

You need to add a controller that responds to location-related requests. For example, request for list of Locations. Or maybe request for a single location. Or even to add or delete a location.

Add a new file to to the location package. Name it LocationController. I’ve written the content out for you. So you can copy and paste.

package location;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class LocationController {
	

}

 

In the next tutorial, we would then add logic for all these methods.