Spring Boot – Get Item by Id

In this chapter, we are going to write the methods to get resources by Id.

Remember that in the previous chapter(Write GET Methods), we wrote methods, to get all resources. For example, getAllUsers, getAllPosts and getAllLocation. But this time we would write methods for getUser, getPost and getLocation.

This methods would take parameter, which is the id of the item to get.

 

  1. Get a Single User
  2. Get a Single Post
  3. Get a Single Location
  4. Test the Application

 

1. Get a Single User

So this method would be written in the UserService file. We call this method GetUser. On way to do this is to loop through the user and find a match for the passed in id parameter. But in this tutorial we would use the stream API.

The method is as shown below:

 

public User getUser(String id) {
    User user = users.stream()
		.filter(t -> id.equals(t.getId()))
		.findFirst()
		.orElse(null);
		
    return user;
}

Listing 1.0: getUser Method using Stream API

 

Now, we go to the UserController. We’ll write a method that handles a request to /User/id. For example the request to /User/u1 should return the user with id of u1. Similarly request to /User/u2 should return the user with id of u2. And so on.

The method is shown below

 

@RequestMapping(value = "/users/{id}")
public User getUser(@PathVariable String id) {
    return userService.getUser(id);
}

 

 

2. Get a Single Post

We then write the methods to return a single post. It follows the same pattern as returning a single user.

The method for the PostService is given below;

 

public Post getPost(String id) {
    	Post post = posts.stream()
		.filter(t -> id.equals(t.getId()))
		.findFirst()
		.orElse(null);
		
	return post;
}

 

The method for the PostController is given below as well

 

@RequestMapping(value = "/posts/{id}")
public Post getPost(@PathVariable String id) {
    return postService.getPost( id);
}

 

 

3. Get a Single Location

In the same way, we write the getLocation method for the LocationService and LocationController files.

 

Put the code below in the LocationService class

public Location getLocation(String id) {
    Location location = locations.stream()
	.filter(t -> id.equals(t.getId()))
	.findFirst()
	.orElse(null);
		
    return location;
}

 

Put the code below in the LocationController class

@RequestMapping(value = "/locations/{id}")
public Location getLocation(@PathVariable String id) {
	return locationService.getLocation(id);
}

 

 

4. Test the Application

Now, it’s time to test the application.

So right-click on the application. Choose Run As > Spring Boot Application

Then Open the browser and visit the following urls:

  • http://localhost:8080/users/u1
  • http://localhost:8080/posts/p1
  • http://localhost:8080/locations/l1

If you have any challenges, please mention it in the comment box below.