Table of contents
1.
📜Introduction
2.
💡@Request Body
3.
💡@Path Mapping
4.
⏳Steps to Create a User Resource and Post it Through POST Method
5.
💡Enhancing POST Method to Return HTTP Code and Status Location
5.1.
📚Response Entity Class
5.2.
⏳Steps to Follow
6.
Frequently Asked Questions
6.1.
What does Spring Boot's post function do?
6.2.
Can we use the POST method to update data in API?
6.3.
Can we build a resource using Put rather than POST?
6.4.
What does spring boot's @RestController annotation mean?
6.5.
Can @component take the place of @controller?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Implementing the POST Method to Create User Resource

Author Mayank Goyal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

📜Introduction

This article will use the POST method to post the user resource for the specific URL. But what are POST methods? Well, the POST method is a type of method that sends an entity to the specified resource, frequently leading to a server state change or unintended consequences. For instance, when submitting data using jQuery/AJAX requests or HTML form data to the server, browsers use the HTTP POST request method.

💡@Request Body

The @RequestBody annotation links the method parameter to the web request's body. An HTTP Message Converter receives the request's body and converts it. Depending on the request's content type, it resolves the method argument. We can apply the automated validation by adding the optional annotation @Valid to the argument.

In the later article, we will see that it maps to the user parameter when we pass the @RequestBody in the createUser() method.

💡@Path Mapping

The @RequestMapping annotation, which serves as a shortcut for @RequestMapping(method=RequestMethod=POST), is specialized in the @PathMapping annotation. The @PostMapping function handles the HTTP POST requests matched with the supplied URL.

Steps to Create a User Resource and Post it Through POST Method

👉Open CreateUserResource.java and add @PostMapping("/user").

👉Now, create a method createUser() and pass the User class's object as the body of the web.

👉Next, we save the created user.

🧑‍💻Our CreateUserResource.java will look like this:

package com.javatpoint.server.main.user;  
import java.util.List;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController;  


@RestController  
public class UserResource   
{  
@Autowired  
private UserDaoService service;  


@GetMapping("/users")  
public List<User> retriveAllUsers()  
{  
return service.findAll();  
}  


//retrieves a specific user.  
@GetMapping("/users/{id}")  
public User retriveUser(@PathVariable int id)  
{  
return service.findOne(id);  
}  


//method that posts a new user detail   
@PostMapping("/users")  
public void createUser(@RequestBody User user)  
{  
User sevedUser=service.save(user);    
}  
}  


The get request is returned when the page is refreshed. However, a POST request must be sent. Through the REST client, we may send POST requests. A client called a REST client is made to utilize a server's RESTful services.

Now, we will see how to use the rest client. For that, signup to the postman and create an account. 

After creating an account, follow the steps below: 

👉First, we will check for the get request. Enter the URL in the address bar and hit the send button.

output

Now, we will send a POST request. For the POST request, do the below steps:

output

👉Copy the response body from "/users."

👉Click on the Body tab. Then, create a body for the POST request.

👉Choose the raw option that creates a raw request.

👉Paste the content.

👉Remove the id because it increments automatically.

👉Make the required changes(i.e., create a new user).

👉Inplace of Text, we are sending the data in JSON format. So select JSON (application/JSON).

👉Type the URL the same as above and click on the Send button.

👉Click on the Get request.

👉We will again send a get request, so change the URL and click the Send button. It displays all the users, including the ones we created now.

💡Enhancing POST Method to Return HTTP Code and Status Location

Now, we will return the status and URL of the user recourse we have created.

📚Response Entity Class

The ResponseEntity class extends the HttpEntity and HttpStatus. It is defined in org.springframework.http.RequestEntity.

👉It is utilized in the @Controller and RestTemplate functions.

👉It is a parameter in the exchange() and getForEntity() methods.

👉Additionally, Spring MVC uses it as a parameter in a @Controller method.

Methods Syntax Description
created()

public static ResponseEntity.BodyBuilder created(URI location)  

 

It is a static function of the RequestEntity class. The location header is set to the specified URI, and a new builder is created with the status CREATED.

Parameter: It accepts the location URI.

Returns: It returns the created builder.

fromCurrentRequest()

 

fromCurrentRequest(HttpServletRequest) Except that RequestContextHolder retrieves the request, it is comparable to the fromRequest(HttpServletRequest) method.
path() public UriBuilderBuilder path(String path)  

The UriComponentsBuilder class's path() method adds the specified path to the builder's already-existing path. URI template variables might be present in the provided path.

Parameter: It accepts a path.

Returns: It returns the UriComponentsBuilder.

buildAndExpand() 

 

public UriComponents buildAndExpand(Object...uriVariableValues)  

 

The UriComponents object is created, and the values taken from an array are used to replace the URI template variables. It is a shortcut method that calls build() first, followed by UriComponents. Expand.

Parameter: It accepts the URI variable values.

Returns: It returns the URI components with extended values.

build()

public UriComponents build()  

 

From the various components in the builder, it creates an instance of UriComponents.

Parameter: It does not accept any parameter.

Returns: It returns the Uri Components.

Moving on, let's see the steps to return the status of the created resource and how to set the URL of the created resource in the response.

Steps to Follow

👉We create a method that creates a user resource and returns the ResponseEntity.

👉Now open Postman and create a POST request.

👉Click on the POST request under the History tab.

👉Click on the Body tab and change the user name to James.

👉Ensure you have selected the JSON (application/JSON) media type.

👉Click on the Send button.

On the right-hand side of the window, if we can see the Status: 201 Created,i.e., it means the resource has been properly created.

Now click on the Headers tab to see the location. Location is the URI of the created resource.

Frequently Asked Questions

What does Spring Boot's post function do?

The Spring Boot applications that handle client post requests with JSON data in the header typically utilize the PostMapping() annotation. Launching the project's Spring web.

Can we use the POST method to update data in API?

Yes, we can.

Can we build a resource using Put rather than POST?

You can build or edit a resource using either POST or PUT, as both can be used to submit data. Because PUT is idempotent, it is preferred by many web developers for creating a resource on the server. No matter how often you call PUT, the resource's condition won't be in danger.

What does spring boot's @RestController annotation mean?

The @Controller and @ResponseBody annotations are already present in the Spring RestController annotation, which is a convenience annotation. Applying this annotation to a class designates it as a request handler. The Spring MVC annotation, Spring RestController, is used to build RESTful web services.

Can @component take the place of @controller?

There is no difference between @Component, @Service, @Controller, and @Repository. The generic annotation @Component is used to represent the component of our MVC.

Conclusion

This article taught us about the post method in spring-boot and how to implement the same. Further, we saw how to enhance the http post method to return the location. That’s all from the article. I hope you all like it.

If you want to learn more, check out our articles on Construct the Full K-ary Tree from its Preorder TraversalRegular and Bipartite graphsWhat Is Web2Py?Why To Use Web2py?Postbacks and Internationalization in web2pyThird Party Modules In Web2pyTasks In Web2py, and  XML in Web2py.

Happy Coding!

Live masterclass