Over a million developers have joined DZone.

Build a REST Web Service Using Spring

DZone's Guide to

Build a REST Web Service Using Spring

This tutorial provides a step-by-step guide for building and configuring a REST web service in Java using the Spring framework.

· Integration Zone ·
Free Resource

The State of API Integration 2018: Get Cloud Elements’ report for the most comprehensive breakdown of the API integration industry’s past, present, and future.

This tutorial provides a step-by-step guide for building a REST web service using the Spring framework.


  • Eclipse IDE (Mars release)
  • Java 1.8
  • Apache Tomcat 8

1. Create a Maven Web Project

Create a Maven web project using this tutorial and name your project SpringRestService.

The structure of the generated project looks like the following:

2. Add Spring Dependencies

After creating the web project, the first step is to add Spring dependencies into pom.xml, like so:




In this tutorial, we use Spring 4.3.0 and we're interested in the following modules:

  • spring-core: this is the core module of the Spring framework; it should be used in any Spring-based application.
  • spring-web, spring-webmvc: these are the web modules which allow you to create either REST resources or standard controllers.
  • jackson-databind: this library provides implicit conversion between JSON and POJO classes. When this library is imported into pom.xml, you don't have to worry about converting JSON requests into POJO or POJO responses into JSON; this is fully handled implicitly by this library. In case you're interested in XML data type, then use jackson-xml-databind.

To learn more about Spring modules, check this out.

After adding the above dependencies, the following jars are automatically imported into your project under Maven Dependencies:

3. Implement REST Resources

Now that we're able to create our first REST application using Spring.

We're going to implement a very basic payment API which charges customers for buying items.

Our API will only accept JSON requests and respond back with JSON responses thanks to the Jackson library, which allows us to deal with requests and responses as POJO classes without worrying about JSON/POJO conversions.

Following is the payment request class which should be submitted by clients on each payment request:

package com.programmer.gate;

public class PaymentRequest {

 private int userId;
 private String itemId;
 private double discount;

 public String getItemId() {
  return itemId;

 public void setItemId(String itemId) {
  this.itemId = itemId;

 public double getDiscount() {
  return discount;

 public void setDiscount(double discount) {
  this.discount = discount;

 public int getUserId() {
  return userId;

 public void setUserId(int userId) {
  this.userId = userId;


And this is the base response returned back from our service:

package com.programmer.gate;

public class BaseResponse {

 private String status;
 private Integer code;

 public String getStatus() {
  return status;

 public void setStatus(String status) {
  this.status = status;

 public Integer getCode() {
  return code;

 public void setCode(Integer code) {
  this.code = code;


The most important class in our API is the controller which acts as the interface for client/server communication, each controller acts as a resource which exposes some services and is accessed via specific url.

In our example, we define one resource called PaymentController, which exposes the payment service to the customers.

Our controller looks like the following:

package com.programmer.gate;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

public class PaymentController {

 private final String sharedKey = "SHARED_KEY";

 private static final String SUCCESS_STATUS = "success";
 private static final String ERROR_STATUS = "error";
 private static final int CODE_SUCCESS = 100;
 private static final int AUTH_FAILURE = 102;

 @RequestMapping(value = "/pay", method = RequestMethod.POST)
 public BaseResponse pay(@RequestParam(value = "key") String key, @RequestBody PaymentRequest request) {

  BaseResponse response = new BaseResponse();
  if (sharedKey.equalsIgnoreCase(key)) {
   int userId = request.getUserId();
   String itemId = request.getItemId();
   double discount = request.getDiscount();

   // Process the request
   // ....
   // Return success response to the client.

  } else {
  return response;

The only service exposed by our controller is the pay() method, which looks very straightforward; it validates the client request using a predefined shared key, processes the request and responds back with the operation status.

Following are the common annotations used by our controller:

  • @RestController: this annotation marks the class as a Resource, it defines implicitly both @Controller and @ResponseBody MVC annotations, when annotating a class with @RestController, it's not necessary to write @ResponseBody beside the POJO classes returned from your methods.
  • @RequestMapping: this annotation defines the url of the resource in addition to the method type: GET/POST, in our example we expose the payment service as POST which is accessed through /payment/pay.
  • @RequestParam: this annotation represents a specific request parameter, in our example, we map a request parameter called key to an argument key of type String.
  • @RequestBody: this annotation represents the body of the request, in our example, we map the body of the request to a POJO class of type PaymentRequest(Jackson handles the JSON/POJO conversion).

As noticed the response is represented as BaseResponse and there is no need to annotate it, Jackson converts it implicitly to JSON.

4. Configure the REST API

After implementing our resource and defining the requests and responses of our API, now we need to configure the context url of our API and instruct our servlet container to load the resource on startup. Without this configuration section, your resources wouldn't be exposed to clients.

Spring 4.3.0 supports several configuration annotations, there is no more need to define configurations in web.xml.

Basically, we need to create two classes:

  • ApplicationInitializer: this is an initializer class which is loaded at the startup of the application, it defines the configuration class of the application along with the context url.
  • ApplicationConfiguration: this is the configuration class of the application, it is basically used to instruct the servlet container to load REST resources from a specific package.

Here we go:

package com.programmer.gate;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@ComponentScan(basePackages = "com.programmer.gate")
public class ApplicationConfiguration {

package com.programmer.gate;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

 protected Class < ? > [] getRootConfigClasses() {
  return new Class[] {

 protected Class < ? > [] getServletConfigClasses() {
  return null;

 protected String[] getServletMappings() {
  return new String[] {


In our example, we're instructing the servlet container to load the resources from the com.programmer.gate package, and we're exposing our API through /rest url.

5. Deploy the REST API

Now that our API is ready for deployment, so we deploy it on Tomcat 1.8/JRE8 (if you haven't set up Tomcat on Eclipse, then follow this guide). 

In order to test our API, we use the Advanced REST client plugin from chrome and we initiate 2 different requests:

Successful request: in this request we pass a valid shared key as a request parameter along with item details in the request body. This is how it looks:

And this is our response:

 "status": "success",
 "code": 100

Failure request: this request looks similar to the above but with an invalid shared key, this is what we get from our API:

 "status": "error",
 "code": 102


That's it; I hope you find it useful.

Your API is not enough. Learn why (and how) leading SaaS providers are turning their products into platforms with API integration in the ebook, Build Platforms, Not Products from Cloud Elements.

spring ,java ,rest ,web services ,integration

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}