DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • Scalable Client-Server Communication With WebSockets and Spring Boot (Part II)
  • A General Overview of TCPCopy Architecture

Trending

  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • How to Create a Successful API Ecosystem
  1. DZone
  2. Coding
  3. Frameworks
  4. Simple Spring Boot: Post

Simple Spring Boot: Post

Making a Spring Boot Rest Controller that takes POST requests is a straightforward process. Let's get it started, then test our work with Postman and code alike.

By 
Dan Newton user avatar
Dan Newton
·
Apr. 06, 17 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
222.5K Views

Join the DZone community and get the full member experience.

Join For Free

Let's dive into a very quick tutorial covering sending a POST request to a Rest Controller in Spring Boot.

Have a look at Spring’s starter guide if you're starting from scratch. The setup that is not described in this post is covered there.

The Maven dependencies required in this post are:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>


And here's the Rest Controller:

@RestController
public class PersonRestController {

    @Autowired private PersonService personService;

    @Autowired private PersonRepository personRepository;

    @RequestMapping(value = "/persistPerson", method = RequestMethod.POST)
    public ResponseEntity < String > persistPerson(@RequestBody PersonDTO person) {
        if (personService.isValid(person)) {
            personRepository.persist(person);
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }
        return ResponseEntity.status(HttpStatus.I_AM_A_TEAPOT).build();
    }
}


The first thing to notice is that the class is annotated with @RestController, allowing it to accept the requests that are sent to its path, which is “/”, as one has not been defined in this example. Some beans have been injected in using the @Autowired annotation, allowing them to be used in this controller.

Onto the more POST-specific code. @RequestMapping defines the path that the annotated method can accept requests from and specifies that this method accepts POST requests.

This method accepts requests from:

the rest of the request .../persistPerson


For example:

localhost:8080/persistPerson


By default, if no method is mentioned, it will accept GET requests. @RequestBody marks that the person input is retrieved from the body/content of the POST request. This is a notable difference between GET and POST as the GET request does not contain a body.

As POST requests are meant to be used to save new data to a database, this example does just that, although none of the actual persistence code is actually implemented. If the input person is valid, then it will call the repositories' persist method and return an HttpStatus.CREATED (201) response code. This is the response code that is normally returned from a successful POST request. If the person was not valid, then it returns a different response code. I used I_AM_A_TEAPOT (418), as it looked silly but it should probably be NO_CONTENT (204) or CONFLICT (409) (although there does not seem to be a consensus on what the correct response is).

To manually test this, I used Postman to send a POST request to the Rest Controller:

  • Set the request type to POST
  • Set the content type in the header to application/json; charset=UTF-8
  • Add the JSON for the PersonDTO to the body of the request (in the raw option)
  • Add the request path
  • Press send

If you haven’t already, start up your server before you try to send the request or, obviously, it won't work.

Request path:

localhost:8080/persistPerson


Body:

{
    "firstName": "First name",
    "secondName": "Second name",
    "dateOfBirth": "01/12/2020",
    "profession": "Software Developer",
    "salary": 0
}


These two pictures below should help make this clearer

Postman-Post-Example-1

Postman-Post-Example-2.PNG

It’s probably also a good idea to test the code. So let's look at how to do so.

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(PersonRestController.class)
public class PersonRestControllerTest {

    @Autowired private MockMvc mockMvc;

    @Autowired private ObjectMapper objectMapper;

    @MockBean private PersonService personService;

    @MockBean private PersonRepository personRepository;

    private JacksonTester < PersonDTO > jsonTester;

    private PersonDTO personDTO;

    @Before
    public void setup() {
        JacksonTester.initFields(this, objectMapper);
        personDTO = new PersonDTO();
    }

    @Test
    public void persistPerson_IsValid_PersonPersisted() throws Exception {
        final String personDTOJson = jsonTester.write(personDTO).getJson();
        given(personService.isValid(any(PersonDTO.class))).willReturn(true);
        mockMvc
            .perform(post("/persistPerson").content(personDTOJson).contentType(APPLICATION_JSON_UTF8))
            .andExpect(status().isCreated());
        verify(personRepository).persist(any(PersonDTO.class));
    }

    @Test
    public void persistPerson_IsNotValid_PersonNotPersisted() throws Exception {
        final String personDTOJson = jsonTester.write(personDTO).getJson();
        given(personService.isValid(any(PersonDTO.class))).willReturn(false);
        mockMvc
            .perform(post("/persistPerson").content(personDTOJson).contentType(APPLICATION_JSON_UTF8))
            .andExpect(status().isIAmATeapot());
        verify(personRepository, times(0)).persist(any(PersonDTO.class));
    }
}


The @WebMvcTest annotation is used, which will disable full auto-configuration and only apply configuration relevant to MVC tests, including setting up the MockMvc used in this test. The PersonRestController has been marked in the annotation, as it is the test subject. Using MockMvc provides a faster way of testing MVC controllers, like the PersonRestController, as it removes the need to fully start a HTTP server. @MockBean is used on each bean that was injected into the PersonRestController so that they are then mocked in the tests.

Each test converts the personDTO into JSON using the JacksonTester and sends a POST request that includes the JSON in its body/content. The tests will pass if the correct response code is returned and if personRespository.persist was called the correct number of times. Mockito is used to mock the return of the personService.isValid method and to verify if personRepository.persist was called or not.

By now, you should be able write a simple Rest Controller that can accept POST requests. You should also be able to manually test it with Postman or automatically test it yourself.

The code used in this post can be found on my GitHub.

POST (HTTP) Requests Spring Framework Testing

Published at DZone with permission of Dan Newton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body
  • Scalable Client-Server Communication With WebSockets and Spring Boot (Part II)
  • A General Overview of TCPCopy Architecture

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!