Build REST web service using Spring
ADVERTISEMENT
Table of Contents
- Introduction
- 1. Create Maven web project
- Add Spring dependencies
- 3. Implement REST resources
- 4. Configure REST API
- 5. Deploy REST API
- Summary
- Next Steps
Introduction
This tutorial provides a step-by-step guide on how to build REST web service using Spring framework.
Prerequisites:
- Eclipse IDE (Mars release)
- Java 1.8
- Apache tomcat 8
1. Create Maven web project
Create a maven web project using this tutorial and name your project as SpringRestService.
The structure of the generated project looks like the following:
Add Spring dependencies
After creating the web project, the first step is to add Spring dependencies into pom.xml, here we go:
<properties>
<springframework.version>4.3.0.RELEASE</springframework.version>
<jackson.library>2.7.5</jackson.library>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
</dependencies>
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 in 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.
After adding the above dependencies, the following jars are automatically imported to 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 would only accept JSON requests and respond back with JSON responses, thanks to 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:
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;
@RestController
@RequestMapping("/payment")
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.
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
}
else
{
response.setStatus(ERROR_STATUS);
response.setCode(AUTH_FAILURE);
}
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 respond 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 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 2 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 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;
@Configuration
@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 {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/rest/*" };
}
}
In our example, we’re instructing the servlet container to load the resources from com.programmer.gate package, and we’re exposing our API through /rest url.
5. Deploy REST API
Now that our API is ready for deployment, so we deploy it on Tomcat 1.8/JRE8 (if you haven’t setup tomcat on eclipse then follow this guide).
In order to test our API, we use 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 like:
And this is our response:
{
"status": "success",
"code": 100
}
Failure request: this request looks similar to the above but with invalid shared key, this is what we get from our API:
{
"status": "error",
"code": 102
}
That’s it, hope you find it useful.
Summary
This tutorial provides a step-by-step guide on how to build REST web service using Spring framework.
Next Steps
If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.
Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.
Final Notes
Recommended product: Coding Essentials Guidebook for Developers