Building a RESTful Web Service with Spring

By Ludovic Dewailly
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
About this book

REST is an architectural style that tackles the challenges of building scalable web services. In today’s connected world, APIs have taken a central role on the web. APIs provide the fabric through which systems interact, and REST has become synonymous with APIs.

The depth, breadth, and ease of use of Spring makes it one of the most attractive frameworks in the Java ecosystem. Marrying the two technologies is therefore a very natural choice.

This book takes you through the design of RESTful web services and leverages the Spring Framework to implement these services. Starting from the basics of the philosophy behind REST, you’ll go through the steps of designing and implementing an enterprise-grade RESTful web service. Taking a practical approach, each chapter provides code samples that you can apply to your own circumstances.

This book goes beyond the use of Spring and explores approaches to tackle resilience, security, and scalability concerns. You’ll learn techniques to deal with security in Spring and discover how to implement unit and integration test strategies.

Finally, the book ends by walking you through building a Java client for your RESTful web service, along with some scaling techniques for it.

Publication date:
October 2015


Chapter 1. A Few Basics

With the prominence of the Internet and the ubiquity of HTTP in today's world, web services have become the main means for web-based systems to interoperate with each other. A web service is an interface that provides access to a web-facing system for clients and other services to consume.

Simple Object Access Protocol (SOAP) used to be the de facto choice for building such services. SOAP is an XML-based communication protocol, leveraging open standards. However, in recent years Representational State Transfer (REST) has become a very popular alternative to traditional SOAP web services. So, let's take a look at the principles behind REST. This chapter will cover the following topics:

  • Discussions of the REST principles

  • How the Spring Framework can help in the building of RESTful web services

  • A sample RESTful web service that will provide the backdrop for the rest of this book


REST principles

REST is a software architecture approach for creating scalable web services. The term REST was coined by Roy Fielding in his PhD dissertation, and revolves around a number of principles. These principles underpin the architecture of RESTful web services and are described in the following sections.

Uniform interface

At the core of REST are resources, and resources are identified using Uniform Resource Identifiers (URIs). Conceptually, resources are separate from their representation (that is, the format in which they are provided to clients). REST does not mandate any specific format, but typically includes XML and JSON (which will be discussed in Chapter 4, Data Representation).

In addition, resource representations are self-descriptive. In more concrete terms, this means that sufficient information must be returned for the successful processing of responses.

Another distinctive property of REST is that clients interact entirely through hypermedia, which is dynamically provided by the application servers. Apart from endpoints, clients need no prior knowledge of how to interact with a RESTful service. This constraint is referred to as Hypermedia as the Engine of Application State (HATEOAS).


The client-server model that REST embraces enables the separation of client concerns, such as user interaction or user state management, from that of server concerns such as data storage and scalability.

This decoupling ensures that, provided an interface that is agreed upon, the development of client and server can be done independently. It also helps reduce complexity and improve the effectiveness of performance tuning.


REST advocates statelessness. No client state is stored on the server. All the information needed to perform operations is contained in the requests (as part of the URL, request body, or as HTTP headers).


RESTful web services must provide caching capabilities. Servers can indicate how and for how long to cache responses. Clients can use cached responses instead of contacting the server.


This principle has significant advantages for scalability. Caching techniques will be discussed in Chapter 6, Performance.

Since REST typically leverages HTTP, it inherits all the caching properties that HTTP offers.

Layered system

Given the style of communication between clients and servers, clients are not aware of which specific server they are interacting with. This property allows the introduction of intermediate servers that can, for example, handle security or offer load-balancing capabilities. These architectural concepts are discussed in more detail in Chapter 10, Scaling a RESTful Web Service.

Code on demand

Even though it's part of the REST architecture, this principal is optional. Servers can temporarily extend the functionality of clients by transferring executable code. For example, JavaScript can be provided to web-based clients to customize functionality.

For a service to be considered RESTful, it should abide by the preceding principles.


The Spring Framework and REST

It is assumed that the reader is familiar with the Spring Framework (referred to as Spring from here on). We will therefore focus on the specificities of building RESTful web services with Spring, in this section.

Since REST hinges on URIs, the Spring Web MVC framework provides all the necessary tools for building RESTful endpoints. Annotations, such as org.springframework.web.bind.annotation.RequestMapping and org.springframework.web.bind.annotation.RequestParam for mapping URLs and parameters form the basis for creating such endpoints. Chapter 3, The First Endpoint, will discuss these annotations and offer code samples to illustrate their use.


Reference documentation about the Spring Web MVC can be found at

With the technological context laid out, let's now look at one such RESTful service. Throughout this book, we will be building a sample web service that helps manage hotels and B&Bs.


Our RESTful web service

One common piece of software in use in the hospitality industry is a property management system (careful readers will notice the unfortunate acronym for these systems). It allows automating the operations of hotels and B&Bs. For the purpose of this book, we will build such a system using Spring. Each component of this system will expose a RESTful API that will be consumed by a simple web interface.


Designing effective Application Programming Interfaces is a topic that deserves its own treaty. It is beyond the scope of this book to discuss these concerns in detail. The main characteristics that one should bear in mind when designing APIs are: ease of use, consistency, exposing as little as necessary, extensibility, and forward compatibility.


Our property management system will be formed of the four components, as illustrated in the following figure:

The four components are explained as follows:

  • Inventory Service: This component provides the necessary functionality to manage and describe rooms and room types.

  • Availability Service: This component lets users see what rooms are available on specific dates.

  • Booking Service: This component will be responsible for taking bookings. It will rely on the Inventory Service and Availability Service components to validate bookings.

  • Billing Service: Once a booking is made, this component will offer the ability to generate an invoice.

Data model

In this section, we will look at the data model that will support our web service. The following entity relationship diagram provides an overview of this model:

The entities that constitute our model are as follows:

  • Room: This object represents the physical rooms that are part of our hotel. Rooms have a name and a description as well as photos.

  • RoomCategory: Each room belongs to a category (for example, double room). Categories provide a description, and are linked to a pricing model.

  • Pricing: This object encapsulates how rooms are priced (for example, a fixed price, or a sliding price based on the number of guests).

  • Booking: The reservation of rooms is modeled on bookings. Bookings will capture the reserved room, dates, and contact details for guests.

  • Invoice: This provides invoices to guests upon booking. They contain the relevant information regarding the booking, and the amount to be settled.

The data access layer will be implemented using Object-Relational Mapping (ORM) with Hibernate 4.3.8.


We will not delve into the specificities of Hibernate ORM in this book. However, documentation is available on at

In addition, for the purpose of simplifying the development and testing of our web service, we will use an embedded H2 database.


Documentation about H2 can be found at

Hibernate supports H2 out of the box, so no specific setup is required to use it as our embedded database.


While an embedded database is great for development, it is not fit for a production deployment.



Now that we had a look at the topics that we will cover in this book, and what our RESTful web service will do, let's discuss how we are going to build it.

In the next chapter, we will see the description of several tools available to help us create our sample web service.

About the Author
  • Ludovic Dewailly

    Ludovic Dewailly is a senior, hands-on software engineer and development manager with over 12 years of experience in designing and building software solutions on platforms ranging from resource-constrained mobile devices to cloud computing systems. He is currently helping FancyGiving (a social shopping, wishing, and gifting platform) with designing and building their system. Ludovic's interests lie in software architecture and tackling web scale challenges.

    Browse publications by this author
Latest Reviews (4 reviews total)
Good and precise content.
Very superficial. It deals with a specific topic but it doesn't explain anything in detail. I have the feeling that the writer isn't an expert in the topic.
very good book for learning Spring RestFull word!
Building a RESTful Web Service with Spring
Unlock this book and the full library FREE for 7 days
Start now