Overview

In a previous article, I showed how to use start.spring.io to create a new Spring Boot application. In this article, I will show how to extend that application and create a REST API.

REST (short for "Representational State Transfer") is an architectural pattern that allows you to access, create, and manipulate backend resources over HTTP.

Spring Boot uses the Model-View-Controller (MVC) pattern for web apps, which separates the business logic, the data model, and the user interface into different components. A web service does not have a user interface, but it returns data to the client - typically as JSON - and we can think of this as the interface.

In the demo described here, we will begin with the sample application created using start.spring.io in the previous article.

Controllers

In an MVC application, a Controller contains or calls the business logic. By convention, we add controllers to a folder named "controllers".

Create a file named "GreetingsController.java" with a GreetingsController class in the controllers folder. Add a method named "greet" that accepts no parameters and returns a String, as in the following code:

public class GreetingsController {
    public String greet() {
        return "Hello";
    }
}

Your project should look similar to Fig. 1.

Controller Class
Fig. 1

Identify this class as a controller by decorating the class with the @RestController attribute.

We want to map the greet method to a route, so that users can access it via HTTP. A route specifies the relative URL that maps to a specific method in a controller. An example will help to demonstrate this.

To make Spring recognize this as an MVC controller, decorate the class with the @RequestMapping attribute. Add the parameter "/greetings" to the RestController attribute to indicate the route path of the controller.

We can then make the greet method accessible via HTTP by decorating this method with the @GetMapping attribute with the parameter "greet". GetMapping makes this method available via the HTTP GET verb.

Here is the code, as described so far:

package com.dgtest.dgtest.controllers;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("greetings")
@RestController
public class GreetingsController {
    @GetMapping("greet")
    public String greet() {
        return "Hello";
    }
}

When you run or debug this application locally, it displays output similar to that in Fig. 2.

Run Output
Fig. 2

Notice that it is running locally on port 8080 (I have highlighted the relevant output). Therefore, the host will be http://localhost:8080.

To access methods in the controller class, we append the RequestMapping parameter (in this case "greetings") to the URL. To call a specific method via HTTP GET, we append the GetMethod parameter (in this case "greet" for the greet() method.

So, when the application runs locally, we can call the greet method by sending an HTTP GET request to http://localhost:8080/greetings/greet

Try this by opening a browser and navigating to http://localhost:8080/greetings/greet. This sends an HTTP GET request to that URL.

The string "Hello" should appear in the browser, as shown in Fig. 3.

Http Get
Fig. 3

NOTE: If I deploy this to another web server, the host part of the URL will change. For example, I could create a site named "https://davidsawesomewebaapi.azurewebsites.net" and the URL mapped to this method would be https://davidsawesomewebaapi.azurewebsites.net/greetings/greet

Returning a ResponseEntity

In the example above, we returned a string. This is useful, but HTTP has the ability to return metadata with that string. For example, we may want to know where the request came from or any error information. Information like this can be included in the Header of an HTTP response. Spring provides a ResponsEntity object that returns a full HTTP response to the client, allowing you to customize it, as needed.

The code is shown below:

@GetMapping("greet")
public ResponseEntity greet() {
 return new ResponseEntity("Hello", HttpStatus.OK);
}

A ResponsEntity contains an object within it, which will be the body that is returned in the HTTP response. In this case, the body will be the string ("Hello") that we returned to the client in the example above. The difference is that we are returning a full HTTP response. The HttpStatus.OK represents the value 200, which is a standard HTTP response code, indicating that everything worked correctly. Later, when I cover error handling, we can return a different HTTP response code and more information about the error. We can also manipulate the headers of the response before returning it, but that is beyond the scope of this article.

Passing parameters to a REST request

There are a number of ways to pass parameters to a GET request. Spring's MVC capabilities provide a simple way to add extra information to a URL. For example, we may want to create a method similar to greet that accepts a person's name as an argument and call it using a local URL similar to the following:

http://localhost:8080/greetings/greet/David

Currently, the greet method does not accept parameters, so we will create in our controller a new method named "greetPerson" that accepts the personName parameter, as in the following listing:

public ResponseEntity greetPerson(String personName) {
 String greeting = "Hello, " + personName;
 return new ResponseEntity(greeting, HttpStatus.OK);
}

We must tell the method where to find the value of this parameter. In this case, it is part of the URL, so we modify GetMapping argument and we decorate the personName parameter with the @PathVariable attribute, as shown below:

@GetMapping("greet/{personName}")
public ResponseEntity greetPerson(@PathVariable("personName")String personName) {
 String greeting = "Hello, " + personName;
 return new ResponseEntity(greeting, HttpStatus.OK);
}

The curly braces around personName in the GetMapping path indicate that this is a variable value provided at runtime. The is stored in a temporary variable named "personName" and the PathVariable argument indicates that we should pull the personName value from the URL and assign it to the personName parameter.

Now, when we navigate to http://localhost:8080/greetings/greet/David in a browser, it returns the results shown in Fig. 4.

Parameter
Fig. 4

Conclusion

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

You can find the source code for this article at https://github.com/DavidGiard/Demo-Spring-App/releases/tag/start.spring.io