Build REST web service using Spring

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:

2. Add Spring dependencies

After creating the web project, the first step is to add Spring dependencies into pom.xml, here we go:

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.

To learn more about Spring modules, check this out.

After adding the above dependencies, the following jars are automatically imported to your project under Maven Dependencies: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:

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

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:

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:

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:

REST Client

And this is our response:

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

 

That’s it, hope you find it useful.

 

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

23
Leave a Reply

avatar
14 Comment threads
9 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
16 Comment authors
venkatnamansumon dasJesusrev Recent comment authors
newest oldest most voted
Arun
Guest
Arun

Thanks, and is a usefull piece of code.

husseinterek
Guest
husseinterek

Thank you, glad you like it

Habaga
Guest
Habaga

where is put, delete and other request type? please give me example of others

enrique
Guest
enrique

is very simple! thanks.

husseinterek
Guest
husseinterek

Thank you enrique

Salah-Eddine
Guest
Salah-Eddine

Hello
Thank you for this article …. but i have an HTTP 404 when I invoke the url http://localhost:8085/SpringRestService/rest/payment/pay?key=SHARED_KEY.
Could you please share the code source of this example (web.xml and pom.xml)
Best Regards

rohit verma
Guest
rohit verma

can you tell me jar name for this import org.springframework.web.bind.annotation.RestController

rohit verma
Guest
rohit verma

anyway .. i found it

joel
Guest
joel

can you share your web.xml

husseinterek
Guest
husseinterek

This tutorial doesn’t use web.xml, all the configuration is done via annotations as per the steps above.

chino
Guest
chino

hi, this no work, when i use the app google rest, the servre print this mensaje.

Mar 19, 2018 10:55:17 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringRestService/rest/payment/pay] in DispatcherServlet with name ‘dispatcher’

where is mapping of servlet

Eclipse oxygen, java 8, tomcat 8

husseinterek
Guest
husseinterek

Make sure that ApplicationConfiguration.java is scanning the correct package as per the example above. Regarding the servlet mapping it’s defined in getServletMappings() method of ApplicationInitializer.java.
If you still face the problem, please post your ApplicationConfiguration.java, ApplicationInitializer.java and PaymentController.java

jyoti
Guest
jyoti

hi,

Please post other topics also for rest web serice using spring. such as using other http methods and using log4j .

gshimose
Guest
gshimose

Hello husseinterek,

How can i configure timeout in service?

Thank you

Charissa
Guest
Charissa

Following the tutorial to setup the maven project and then this tutorial exactly, I am getting an unresolved type for the import org.springframework.context.annotation.Configuration and ComponentScan in the ApplicationConfiguration class. I see that the spring-context module is loaded from Maven and that it is added as a dependency just like the image you showed but still nothing. I am using Eclipse Photon so not sure if that could be problem but all others are resolved fine. Any ideas? Thanks!

Jesus
Guest
Jesus

Very useful. Thanks

sumon das
Guest
sumon das

Hi admin thank you so much for your valuable post its really a helpful post for all
web services i would like to share some opinion may be its also helpfull.
waiting and look forward to seeing your next post

naman
Guest
naman

hi…
could you share the structure of the project…thanks

venkat
Guest
venkat

how to do same thing in soap ui tool rather than rest client.please tell me that way i am using that only.thank you