February 9, 2021

Spring Boot – Write GET Methods

In this lesson, we are going to write the GET methods to get list of items. So we would write methods to return list of users. Then we would write method to return list of Posts. Finally, we write method to return list of Locations.

We’ll cover the following:

  1. Write and Test a GET Method
  2. Write the Method to return List of Users
  3. Write the Method to return List of Posts
  4. Write the Method to return List of Locations

 

1. Write and Test a GET Method

So we would first write a GET method. This method would just return a string “Welcome to Spring Boot” when the someone accesses /welcome. To do this, create a new class and name it welcomeController.

Inside this file write a function that write  function welcome() that returns a string “Welcome to Spring Boot”

Annotate the class with @RestConroller annotation

Annotate the function with @RestMapping annotation

If you have done everything right, the content of you welcomeController file would be as shown below.

 

package com.kindsonthegenius.social;

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

@RestController
public class welcomeController {
	
	@RequestMapping(value="/welcome")
	public static String welcome() {
		return "Welcome to Spring Boot";
	}
	
}

Listing 1.0: Content of the welcomeController.java

 

Now you can start the application. Then open the browser and enter http://localhost:8080/welcome

 

2. Write the Method to return List of Users

Here we will write the function that would return list of all the users in our SocialAPI.

Open the UserController file you created in the previous tutorial. Inside this file you will do the following things:

create a function and name if getAllUsers()

annotate this function with @RestMapping annotation

inside this function create a hard-coded list of users

 

package com.kindsonthegenius.social.user;

import java.util.Arrays;
import java.util.List;

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

import com.kindsonthegenius.social.location.Location;

@RestController
public class userController {
	
   @RequestMapping(value="/users")
   public List<User> getAllUsers() {
	User user1 = new User(
		"u1", 
		"Jany", 
		"Lawrence",
		new Location("l1", "Lagos"),
		"[email protected]");
		
	User user2 = new User(
		"u2", 
		"Jadon", 
		"Mills",
		new Location("l2", "Asaba"),
		"[email protected]");
		
	return Arrays.asList(user1, user2);	
	
   }
}

Listing 1.1: Content of the userController.java file

 

Now you can test the application.

Right-click on the project and Run As SpringBoot Application. Then go to the broser and access http://localhost:8080/users. You will get a list of users.

If not let me know in the comment box below.

 

3. Write the Method to return List of Posts

Here we will write the function that would return list of all the posts in our SocialAPI.

Open the PostController file you created in the previous tutorial. Inside this file you will do the following things:

create a function and name if getAllPosts()

annotate this function with @RestMapping annotation. See the video

inside this function create a hard-coded list of posts

 

package com.kindsonthegenius.social.post;

import java.util.Arrays;
import java.util.List;

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

import com.kindsonthegenius.social.location.Location;
import com.kindsonthegenius.social.user.User;

@RestController
public class PostController {
	
   @RequestMapping(value = "/posts")
   public List<Post> getAllPosts() {
		
	User user1 = new User(
		"u1", 
		"Jany", 
		"Lawrence",
		new Location("l1", "Lagos"),
		"[email protected]");
		
	User user2 = new User(
		"u2", 
		"Jadon", 
		"Mills",
		new Location("l2", "Asaba"),
		"[email protected]");
		
	Post post1 = new Post(
		"p1",
		"01-Jan-19",
		user1,
	        "Its good to love and be loved");
		
	Post post2 = new Post(
		"p2",
	        "02-Jan-19",
		user2,
		"We all need someone");		
		
	return Arrays.asList(post1, post2);
 
   }
}

Listing 1.2: Content of the postController.java file

 

Now you can test the getAllPosts method.

Right-click on the project and Run As SpringBoot Application. Then go to the browser and access http://localhost:8080/posts. You will get a list of posts.

If not let me know in the comment box below.

 

4. Write the Method to return List of Locations

Here we will write the function that would return list of all the posts in our SocialAPI. This would be easier than the previous two.

Open the LocationController file you created in the previous tutorial. Inside this file you will do the following things:

create a function and name if getAllLocations()

annotate this function with @RestMapping annotation. See the video

inside this function create a hard-coded list of locations

 

import java.util.Arrays;
import java.util.List;

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

@RestController
public class LocationController {
	
   @RequestMapping(value = "/locations")
   public List<Location> getAllLocations() 
   {
	Location location1 = new Location("l1", "Lagos");
	Location location2 = new Location("l2", "Asaba");
	Location location3 = new Location("l3", "Budapest");	
		
	return Arrays.asList(location1, location2, location3);
   }		

}

Listing 1.3: Content of the LocationController.java file

 

As usual, go ahead to test the getAllLocations method.

If you completed this part successfully, then thumbs up to you! Next we would see how to write POST methods.

0 0 vote
Article Rating
Subscribe
Notify of
guest
16 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Spring Boot – Write GET Methods […]

trackback

[…] Spring Boot – Write GET Methods […]

Johannes Bester
Johannes Bester
1 year ago

Kindson, I follow your turotials and have a question re: Spring Boot Tutorial 12
I need to “Consume” the REST POSTED data in another app and my JSON need to look slightly different

Your JSON is an JSON ARRAY
[{“locationId”:”l1″,”locationName”:”Lagos”},{“locationId”:”l2″,”locationName”:”Asaba”},{“locationId”:”l3″,”locationName”:”Budapest”}]

I need it to be an JSON OBJECT (Something Like This

{“_embedded”: {“locations”: [{“locationId”: “l1”, “locationName”: “Lagos”}, {“locationId”: “l2”, “locationName”: “Asaba”}, {“locationId”: “l3”, “locationName”: “Budapest”}]}}

Is this possible and How?

Djaitai Koffi
Djaitai Koffi
1 year ago

I got null values when I execute the program.

[{“id”:null,”firstname”:null,”lastname”:null,”location”:null,”email”:null},{“id”:null,”firstname”:null,”lastname”:null,”location”:null,”email”:null}]

dioufAH
dioufAH
1 year ago
Reply to  Djaitai Koffi

hi Djaitai Koffi test this code
in the class Location

/******package location*********/

package com.socialapi.demo.location;

public class Location {

private String id;
private String name;

public Location(String id, String name) {
this.id=id;
this.name=name;
}

public Location() {

}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

in the class: LocationController
package com.socialapi.demo.location;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class LocationController {

@RequestMapping(value = “/locations”)
public List getAllLocations()
{
Location location1 = new Location(“l1”, “Lagos”);
Location location2 = new Location(“l2”, “Asaba”);
Location location3 = new Location(“l3”, “Budapest”);

return Arrays.asList(location1, location2, location3);
}
}

in the class: user
package com.socialapi.demo.user;

import com.socialapi.demo.location.Location;

public class User {

private String id;
private String firstname;
private String lastname;
private String location;
private String email;

public User(String id, String firstname, String lastname, Location location, String email) {
this.id=id;
this.firstname=firstname;
this.lastname=lastname;
this.setLocation(location.getId());
this.setLocation(location.getName());
this.email=email;
}

public User() {

}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

/**********package user*********/

in the class: User
package com.socialapi.demo.user;

import com.socialapi.demo.location.Location;

public class User {

private String id;
private String firstname;
private String lastname;
private String location;
private String email;

public User(String id, String firstname, String lastname, Location location, String email) {
this.id=id;
this.firstname=firstname;
this.lastname=lastname;
this.setLocation(location.getId());
this.setLocation(location.getName());
this.email=email;
}

public User() {

}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

/***************************
in the class UserController

***************************/
package com.socialapi.demo.user;

import com.socialapi.demo.location.Location;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
public class UserController {

@RequestMapping(value=”/users”)
public List getAllUsers() {
User user1 = new User(
“u1”,
“Jany”,
“Lawrence”,
new Location(“l1”, “Lagos”),
[email protected]”);

User user2 = new User(
“u2”,
“Jadon”,
“Mills”,
new Location(“l2”, “Asaba”),
[email protected]”);

return Arrays.asList(user1, user2);

}

}

/********package post**********/

/******class Post************/
package com.socialapi.demo.post;

import com.socialapi.demo.user.User;

public class Post {

private String id;
private String postdate;
private User user;
private String details;

public Post(String id, String postdate, User user, String details) {
this.id=id;
this.postdate=postdate;//this.setLocation(location.getName());
this.user=user;
this.details=details;
}

public Post() {

}

/*public Post(String id, String postdate, User user, String details) {
this.id=id;
this.postdate=postdate;//this.setLocation(location.getName());
this.setUser(user.setFirstname());
}
public Post() {

}*/

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getPostdate() {
return postdate;
}

public void setPostdate(String postdate) {
this.postdate = postdate;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

public String getDetails() {
return details;
}

public void setDetails(String details) {
this.details = details;
}
}

/***********PostController**********/
package com.socialapi.demo.post;

import com.socialapi.demo.location.Location;
import com.socialapi.demo.user.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
public class PostController {

@RequestMapping(value = “/posts”)
public List getAllPosts() {

User user1 = new User(
“u1”,
“Jany”,
“Lawrence”,
new Location(“l1”, “Lagos”),
[email protected]”);

User user2 = new User(
“u2”,
“Jadon”,
“Mills”,
new Location(“l2”, “Asaba”),
[email protected]”);

Post post1 = new Post(
“p1”,
“01-Jan-19”,
user1,
“Its good to love and be loved”);

Post post2 = new Post(
“p2”,
“02-Jan-19”,
user2,
“We all need someone”);

return Arrays.asList(post1, post2);

}
}

Star
Star
11 months ago

Hi Kindson,

Firstly, thank you for sharing your knowledge and skills freely. May good tidings be your companion always.
I have started following and watching your videos recently and I am awed. I just want to ask why you don’t add devtools to your springboot since you don’t need to restart the server often and also just adding spring web will take care of tomcat and springmvc.

sindhusha
sindhusha
11 months ago

while running the spring boot application after adding users I am getting whiteable error page. can you please say me how to resolve this

Ashu
Ashu
9 months ago

What to add in the application.properties file i am getting the error for this that class path is not specified..

Ashu
Ashu
8 months ago

I am also getting the same error msg will you tell me how to resolve this…
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun May 10 16:22:49 IST 2020
There was an unexpected error (type=Not Found, status=404).
No message available

chaitu
chaitu
5 months ago
Reply to  Ashu

use the right pakage

ifiok ukpong
ifiok ukpong
8 months ago

Hello Kindsonthegenius, i rally appreciate what u r doing here but on the user controller i keep getting this error the constructor ( String, String, String, Location, String) is undefined…i tried creating a constructor on user pojo, and aftr running it the result displayed is not complete…i.e i have some values that are null…kindly help me

okpara obinna
okpara obinna
8 months ago

when i added user to the controller the attribute is underlined with red and i am still trying to know why, please help out

jerry
jerry
7 months ago

I tried to use your code in my IDE but I got error say “The constructor User(String, String, String, Location, String) is undefined”

how can I do

my code is the same like this bellow
package com.tpdf.FirstProject.user;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

import com.tpdf.FirstProject.location.Location;

@RestController
public class UserController {
@RequestMapping(value=”/karibu”)

public List getAllUsers() {
User user1 = new User(
“u1”,
“Jany”,
“Lawrence”,
new Location(“l1”, “Lagos”),
[email protected]”);

User user2 = new User(
“u2”,
“Jadon”,
“Mills”,
new Location(“l2”, “Asaba”),
[email protected]”);

return Arrays.asList(user1, user2);

}
}

Mel Bali
Mel Bali
6 months ago

In the main class make sure to have these annotations it will fix all the issues above.

@SpringBootApplication
@ComponentScan(basePackages={“user”})
@ComponentScan(basePackages={“post”})
@ComponentScan(basePackages={“location”})