RESTful Web Services

Building a RESTful Web Service

This guide walks you through the process of creating a “Hello, World” RESTful web service with Spring.

Spring is an open-source framework used to build standalone production-grade Spring applications with as minimum configuration as possible. The flexibility of Spring boot allows its applications to be bundled as fat/uber files which can be deployed as a simple jar file. This is why Spring boot makes an excellent choice for developing microservice applications in Java.

Spring is the programmer’s favorite application framework for developing enterprise Java applications and REST is the de facto standard for developing web APIs.

This guide and many others can be found on Getting Started Spring Guides.

What You Will Build

You will build a service that will accept HTTP GET requests at http://localhost:8080/greeting. It will respond with a JSON representation of a greeting, as the following listing shows:

{"id":1,"content":"Hello, World!"}

You can customize the greeting with an optional name parameter in the query string, as the following listing shows:

http://localhost:8080/greeting?name=User

The name parameter value overrides the default value of World and is reflected in the response, as the following listing shows:

{"id":1,"content":"Hello, User!"}

Required software

Make sure that you have installed the software described on Required software.

Step 1 — Create a Spring project

To initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
  2. Use Maven to manage the dependencies
  3. Select the default programming language as Java and jar as packaging and your installed Java version. For this project, we will be using Java 11.
  4. The last important step is to add the necessary dependencies. For this project we will only be using the Spring Web dependency. So, click Dependencies and select Spring Web.
  5. Click Generate
  6. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices

Step 2 — Import your project to your IDE

Next, we will be importing our project into our IDE. For this step, you can use any IDE of your choice. For this project we will be using the Eclipse IDE.

Locate the zip file you downloaded and extract it into any folder. Launch your IDE, go to File, import, Maven, Existing Maven Projects. Navigate to the folder where you extracted your project and click OK to open.

Step 3 — Creating the REST Endpoint

Create a Resource Representation Class

Now that you have set up the project and build system, you can create your web service.

The service will handle GET requests for /greeting, optionally with a name parameter in the query string. The GET request should return a 200 OK response with JSON in the body that represents a greeting. It should resemble the following output:

{
    "id": 1,
    "content": "Hello, World!"
}

The id field is a unique identifier for the greeting, and content is the textual representation of the greeting.

To model the greeting representation, create a resource representation class. To do so, provide a plain old Java object with fields, constructors, and accessors for the id and content data, as the following listing shows:

package com.example.restservice;

public class Greeting {
	private final long id;
	private final String content;
	public Greeting(long id, String content) {
		this.id = id;
		this.content = content;
	}
	public long getId() {
		return id;
	}
	public String getContent() {
		return content;
	}
}

This application uses the Jackson JSON library to automatically marshal instances of type Greeting into JSON. Jackson is included by default by the web starter.

Create a Resource Controller

In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller.

These components are identified by the @RestController annotation, and the GreetingController shown in the following listing handles GET requests for /greeting by returning a new instance of the Greeting class:

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

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

@RestController
public class GreetingController {

	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}
```java


The `@GetMapping` annotation ensures that `HTTP GET` requests to `/greeting` are mapped to the `greeting()` method.

`@RequestParam` binds the value of the query string parameter name into the name parameter of the `greeting()` method. 
If the `name` parameter is absent in the request, the `defaultValue` of World is used.

The implementation of the method body creates and returns a new `Greeting` object with `id` and `content` attributes based on the next value from the 
counter and formats the given name by using the greeting template.

This code uses Spring `@RestController` annotation, which marks the class as a controller where every method returns a domain object instead of a view. 
It is shorthand for including both `@Controller` and `@ResponseBody`.

The `Greeting` object must be converted to JSON. Thanks to Spring's HTTP message converter support, you need not do this conversion manually. 
Because Jackson is on the classpath, Spring's `MappingJackson2HttpMessageConverter` is automatically chosen to convert the `Greeting` instance to JSON.

## Step 4  Test your Spring RESTful Web Service

Run the `Application` class as a Java application, you should see Spring logo appears and some logging messages. 

Notice this line:
> `Tomcat started on port(s): 8080 (http) with context path`

That means your Spring RESTful application is deployed on Tomcat server listening on port 8080. 

### Build an executable JAR

If you use Maven, you can run the application by using `./mvnw spring-boot:run`. 
Alternatively, you can build the JAR file with `./mvnw clean package` and then run the JAR file, as follows:

```sh
java -jar target/gs-rest-service-0.1.0.jar

Test the Service

Now that the service is up, visit http://localhost:8080/greeting, where you should see:

{"id":1,"content":"Hello, World!"}

Provide a name query string parameter by visiting http://localhost:8080/greeting?name=Georgios. Notice how the value of the content attribute changes from Hello, World! to Hello, Georgios!, as the following listing shows:

{"id":2,"content":"Hello, Georgios!"}

Other Materials

You can now try the following tutorial to learn how to handle different HTTP methods, read JSON data, specify HTTP status codes, etc:

Spring tutorial by Nam Ha Minh

Or discover Spring MVC via a slideshare presentation:

Spring Slideshare Presentation

Previous
Next