Overview

In a previous article, I showed how to create a simple REST API in a Spring Boot application. I only covered the GET HTTP verb in that article. In this article, I will show how to implement other HTTP verbs and pass models to and from a REST service.

HTTP Supports the following verbs with a request: GET, POST, PUT, PATCH, and DELETE. These verbs map well to common data operations (GET to read data; POST to add data; PUT and PATCH to update data; and DELETE to delete data), but this mapping is not required and developers do not always adhere to it. One advantage a POST request has over a GET request is that you can send large and more complex data in the body of a POST request. A POST request often includes data in the JSON format in its body.

NOTE: The code for the previous article can be found at https://github.com/DavidGiard/Demo-Spring-App/releases/tag/Spring-Boot-REST-API

Models

A model is a class designed to hold data. When we create an instance of a model class, we can use that instance to represent a real or conceptual object and all the properties of that object.

In Java, a model class is created no differently than any other class. I like to create a folder named "models" in which to store model classes. Here, I will create two classes: GreetingInput and GreetingOutput, as shown below

GreetingInput.java:

package com.dgtest.models;
public class GreetingInput {
    public GreetingInput(String personName) {
        this.personName = personName;
    }
    public GreetingInput() {
    }

    private String personName;
    public String getPersonName() {
        return personName;
    }
    public void setPersonName(String personName) {
        this.personName = personName;
    }
}

GreetingOutput.java:

package com.dgtest.models;
public class GreetingOutput {
    public GreetingOutput(String greeting) {
        this.greeting = greeting;
    }
    public GreetingOutput() {
    }

    private String greeting;
    public String getGreeting() {
        return greeting;
    }
    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }
}

GreetingInput has one property (personName), along with a setter and a getter for that property.

GreetingOutput has on (greeting), along with a setter and a getter for that property.

In addition, each class contains an overloaded constructor, along with one to set the property's value when an instance is created.

More Controller Methods / More Verbs

As you have probably guessed, we will pass an instance of the GreetingInput class as an input to our method, which will return an instance of the GreetingOutput class. Because we are dealing with HTTP, this data will be passed in JSON format and Java/Spring will automatically convert it into a POJO ("Plain Old Java Object").

Testing

My previous article handled HTTP GET requests; but Spring Boot can handle other HTTP verbs, such as POST, PUT, PATCH, and DELETE.

Add the following method to your controller to handle a POST request:

@PostMapping(path="hello", consumes="application/json", produces="application/json")
public ResponseEntity greetPersonPost(@RequestBody GreetingInput greetingInput) {
	String personName = greetingInput.getPersonName();
	String greeting = "Hello, " + personName;
	GreetingOutput greetingOutput = new GreetingOutput(greeting);
	return new ResponseEntity(greetingOutput, HttpStatus.OK);
}

There are four things to call out in this method:

NOTE: If you do not yet have a Controller method, see this article.

  1. The @PostMapping attribute
  2. The ResponseEntity return type
  3. The GreetingInput input parameter
  4. The @RequestBody attribute

@PostMapping attribute

Notice the @PostMapping attribute on the method. This tells Spring that it will run in response to an HTTP POST request. This attribute contains the following arguments:

  • path="hello": This identifies the relative path in the URL to which the POST request is submitted
  • consumes="application/json": This tells Spring to expect data in the body of the request to be formatted as JSON.
  • produces="application/json": This tells Spring to return response data in JSON format

The ResponseEntity return type

The method returns a ResponseEntity containing an object of type GreetingOutput. We created this class earlier. It has one property: greeting. Although the code generates an instance of a POJO, Spring will automatically convert the object to JSON when sending a response to the client, thanks to the produces argument in the @PostMapping attribute.

The GreetingInput input parameter

This method accepts an object of type GreetingInput - a class we created above that contains one property: personName. The client will supply this in JSON format and Spring will automatically convert it to a POJO, thanks to the consumes argument in the @PostMapping attribute.

The @RequestBody attribute

The greetingInput parameter is decorated with the @RequestBody attribute. This tells Spring to look for the value of the parameter in the Body of the HTTP request.

Calling the Method

The code in this method performs a similar function to the greetPerson method created in the previous article. The main difference is that we return an object, rather than a string.

To test the method, we run or debug it locally; then submit an HTTP POST request to http://localhost:8080/greetings/hello. The body of this request will contain a JSON object with the same properties as the greetingInput class, similar to the following:

{
    "personName" : "David"
}

You may choose your favourite tool to submit a POST request. I prefer PostMan, which is a free cross-platform tool that you can download from https://www.postman.com/downloads/

Fig. 1 shows the PostMan interface with the important values highlighted.

PostMan
Fig. 1

Run or Debug the application locally, then complete the following in PostMan:

At the HTTP verb dropdown, select "POST".

At the Request URL field, enter "http://localhost:8080/greetings/hello"

At the Request Body field, select the "raw" radio button and the JSON data format and enter the following text:

{
    "personName" : "David"
}

Click the [Send] button

You should see a response code of "Status: 200 OK" and the following value in the response body:

{
    "greeting": "Hello, David"
}

If you receive an error, verify that the app is running and that your URL is correct. Pay attention to the route and the port number. You may also get a clue in the error response message.

Other HTTP Verbs

The process is nearly identical in handling HTTP PUT, PATCH, and DELETE requests. Spring provides the @PutMapping, @PatchMapping, and @DeleteMapping attributes, which work in a very similar way to the @PostMapping attribute.

Conclusion

In this article, I showed you how to implement a method to handle HTTP POST requests from a Java Spring application. You can see the completed code at https://github.com/DavidGiard/Demo-Spring-App/releases/tag/Handle-HTTP-POST-Requests