Building A RESTful Web Service
Building A RESTful Web Service
Building A RESTful Web Service
This guide walks you through the process of creating a "hello world" RESTful web
service with Spring.
You can customize the greeting with an optional name parameter in the query string:
http://localhost:8080/greeting?name=User
The name parameter value overrides the default value of "World" and is reflected in the
response:
{"id":1,"content":"Hello, User!"}
About 15 minutes
You can also import the code from this guide as well as view the web page directly
intoSpring Tool Suite (STS) and work your way through it from there.
Like most Spring Getting Started guides, you can start from scratch and complete each
step, or you can bypass basic setup steps that are already familiar to you. Either way, you
end up with working code.
To start from scratch, move on to Build with Gradle.
To skip the basics, do the following:
Download and unzip the source repository for this guide, or clone it using Git:git
clone https://github.com/spring-guides/gs-rest-service.git
cd into gs-rest-service/initial
When youre finished, you can check your results against the code in gs-restservice/complete.
The id field is a unique identifier for the greeting, and content is the textual representation
of the greeting.
To model the greeting representation, you create a resource representation class. Provide a
plain old java object with fields, constructors, and accessors for the id and content data:
src/main/java/hello/Greeting.java
package hello;
As you see in steps below, Spring uses the Jackson JSON library to automatically marshal
instances of type Greeting into JSON.
Next you create the resource controller that will serve these greetings.
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World")
String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
This controller is concise and simple, but theres plenty going on under the hood. Lets
break it down step by step.
The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to
the greeting() method.
The above example does not specify GET vs. PUT, POST, and so forth,
because@RequestMapping maps all HTTP operations by default.
Use @RequestMapping(method=GET)to narrow this mapping.
@RequestParam binds the value of the query string parameter name into
the name parameter of the greeting() method. This query string parameter is not required;
if it 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 idand content attributes based on the next value from the counter, and formats the
givenname by using the greeting template.
A key difference between a traditional MVC controller and the RESTful web service
controller above is the way that the HTTP response body is created. Rather than relying on
a view technology to perform server-side rendering of the greeting data to HTML, this
RESTful web service controller simply populates and returns a Greeting object. The object
data will be written directly to the HTTP response as JSON.
This code uses Spring 4s new @RestController annotation, which marks the class as a
controller where every method returns a domain object instead of a view. Its shorthand
for@Controller and @ResponseBody rolled together.
The Greeting object must be converted to JSON. Thanks to Springs HTTP message
converter support, you dont need to do this conversion manually. Because Jackson 2 is on
the classpath, Springs MappingJackson2HttpMessageConverter is automatically chosen to
convert the Greeting instance to JSON.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
context.
@EnableAutoConfiguration tells Spring Boot to start adding beans based on
adds it automatically when it sees spring-webmvc on the classpath. This flags the
application as a web application and activates key behaviors such as setting up
a DispatcherServlet.
@ComponentScan tells Spring to look for other components, configurations, and
If you are using Maven, you can run the application using mvn spring-boot:run. Or you can
build the JAR file with mvn clean package and run the JAR by typing:
java -jar target/gs-rest-service-0.1.0.jar
The procedure above will create a runnable JAR. You can also opt to build a classic WAR
file instead.
Logging output is displayed. The service should be up and running within a few seconds.
Summary
Congratulations! Youve just developed a RESTful web service with Spring.