Lab
APIs respond with JSON representations of data.
Including the Jackson jars, which we discussed earlier, automatically maps returned Java objects to json or primitive types to a string representation.
-
Open the project we configured with ping/pong,
MyFirstRestProject. -
Create a package called
com.example.rest.data. - Create a
Userclass. - A
Usershould have a name, username, email, and password. - Create all the appropriate getters and setters for these fields.
- Create a constructor that takes these 4 values, as well as a no-arg.
-
Generate a
toString. -
The Jackson Library uses these gets and sets to generate the json, so if they aren't included, your program will fail.
-
In the controller create another method
getUser(). Assign the URL/userspath to this method using@RequestMapping. Inside of the methods, instantiate a new instance of aUserand return the created object. (Your instance will use hardcoded data, like the example below.)
@GetMapping("api/users/1")
public User getUser(){
return new User("Julia Cousins", "JCousins", "JC@gmail.com", "wombat1");
}
- Using Postman, hit the URL
http://localhost:8080/api/users/1. You should get the json representation of theUserobject as a response. If you are getting errors make sure you have properly included all gets and sets in theUserclass.
{
"name":"Julia Cousins",
"username" : "JCousins",
"email":"JC@gmail.com",
"password":"wombat1"
}
- Add a post method in the controller:
@PostMapping("api/users")
public String addUser(@RequestBody String userParam){
System.out.println(userParam);
return userParam;
}
- Create a test request in Postman with the method POST, URL
http://localhost:8080/api/users, and a *Body with typerawandapplication/json. Enter a JSON request body:
{
"name": "Froderick Fronkensteen",
"username": "froderick",
"email": "FF@gmail.com",
"password": "tapdance"
}
Send the request, and observe the response in Postman as well as the console output from Spring.
- Change the parameter type and the return type from
StringtoUser:
@PostMapping("api/users")
public User addUser(@RequestBody User userParam){
System.out.println(userParam);
return userParam;
}
Send the request, and observe the response in Postman as well as the console output from Spring.