RESTful Web Services with Spring Framework Part-4

Monil Joshi
5 min readJun 10, 2019

--

Please go through below posts as this post is to be a continuation of those three parts. You can read RESTful Web Services with Spring Framework Part-1, Part-2 and Part-3 here.

In this post, we are working with HTTP POST request. The POST method is used to add some information to the API server. In this method, we need to send some information which needs to be added. That information should be in the form of JSON or XML. We can send this data through a separate section call “Body”.

If you remember in the first post I mentioned CRUD operations and created 4 methods each for one operation. Out of that, we are going to use the second method createUser(). First, we need to add an annotation to the method. As we add GetMapping annotation to getUser() of a GET request. Same we have to add PostMapping annotation to createUser() of a POST request.

Http request send to particular URL like http://localhost:8080/users. It contains a body (data which we want to manipulate on the server) which is a JSON payload. When JSON payload sends to endpoints it needs to convert in java object and we can create in the createUser method.

Create a java class that can be used to hold the JSON payload contains. When this HTTP post request sends our framework will take the JSON payload and convert into java object.

Create a new package inside src/main/java named as com.example.demo.ui.model.request. Inside package create a class UserDetailsRequestModel. Create required fields (variables) in class. Make sure that the name of these class fields should match with names we have in JSON payload. Create getters and setters method for these variables. I already mentioned how to create getters and setters method in previous posts.

Now, in UserController class, use annotation @RequestBody as an argument to createUser(). Using this annotation our method can read the information from the HTTP request that is coming with an argument over data type user argument i.e object of the class which we have created above. If you are using IDE other than IntelliJ IDEA then you will have to import UserDetailsRequestModel class explicitly.

The code in your UserController.java will be like this

@PostMapping
public String createUser(@RequestBody UserDetailsRequestModel userDetailsRequestModel){
return "create user method got called";
}

When the JSON payload is read from requestBody it will convert to UserDetailRequestModel and then we can use that object in our createUser() which contains details of the user we want to create on the server.

Next challenge is how can a request accept or produce data from and to JSON/XML. In postman, We have different headers like content-type, Accept. We can set Accept: application/json or content-type:application/json. Header Accept: application/json indicates that request accepts response only in JSON format. We mostly use this header for HTTP GET request. Header content-type shows the content type of payload which we are sending with the HTTP request. HTTP POST request uses both Accept and content-type headers. As similar to this spring framework designs an API called MediaType. We will use the MediaType API in PostMapping annotation as an argument. It has two methods which we use primarily.

  1. Produces: It is equivalent to Accept header in postman that says produce information in a particular format which is acceptable.
  2. Consumes: It is equivalent to a content-type header in postman that says I am sending information is a particular format consumes and use it.

Mostly in HTTP GET request we use produces as we tell the server to produce information in JSON or XML format. And in an HTTP post method, we use to produce and consumes both to tells the server that I am sending you the information in JSON/XML format consume it and send back information only in JSON/XML format.

We are sending JSON payload with the help of consumes to the http://localhost:8080/users with HTTP POST request which creates a user and sends userId in response in JSON format with the help of produces. Add the below code.

@PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})

Change return type of createUser method to ResponseEntity <UserDetailsRest> as we want our method to return a user object. Inside method create an instance of UserDetailRest class. Call set methods from UserDetailsRest class to set values for each variable. Now while setting values using set methods values will not be hardcoded but values getting from the payload. So inside the set method we will call get methods of an object of userDetailRequestModel. If you are using IntelliJ IDEA as IDE no need to add type argument <UserDetailsRest> for ResponseEntity. Code for all this is

UserController.java@PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<UserDetailsRest> createUser(@RequestBody UserDetailsRequestModel userDetailsRequestModel){
UserDetailsRest userDetailsRest = new UserDetailsRest();
userDetailsRest.setFirstName(userDetailsRequestModel.getFirstName());
userDetailsRest.setLastName(userDetailsRequestModel.getLastName());
userDetailsRest.setEmailId(userDetailsRequestModel.getEmailId());
return new ResponseEntity<UserDetailsRest>(userDetailsRest, HttpStatus.OK);
}
UserDetailRest.javapublic class UserDetailsRest {private String firstName;
private String lastName;
private String emailId;
private String password;
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 getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Run the above code and start the application. Go to the postman. Send HTTP POST request with JSON payload. Add Accept and content-type headers and set its value application/JSON so that requests can produce and consume information in JSON format.

JSON payload
{
"firstName":"John",
"lastName":"George",
"email":"john.george@gmail.com",
"password":"1234"
}
Headers:
Accept: application/json
Content-type: application/json

Check response status and response body which return user details which is been created.

Action in Postman

You can see marked areas. JSON payload which we are sending in body and we are getting Status 200 OK and in the response body, we get user details in JSON format.

In the next post, we will see how to validate the HTTP POST request body.

--

--

Monil Joshi

I am having an 8+ years of experience in software testing. Working with Web, Mobile and API technologies. Visit my GIT https://github.com/monilj