41,99 €
Master core REST concepts and create RESTful web services in Java
If you are a web developer with a basic understanding of the REST concepts and envisage to get acquainted with the idea of designing and developing RESTful web services, this is the book for you. As all the code samples for the book are written in Java, proficiency in Java is a must.
Representational State Transfer (REST) is a simple yet powerful software architecture style to create lightweight and scalable web services. The RESTful web services use HTTP as the transport protocol and can use any message formats, including XML, JSON(widely used), CSV, and many more, which makes it easily inter-operable across different languages and platforms.
This successful book is currently in its 3rd edition and has been used by thousands of developers. It serves as an excellent guide for developing RESTful web services in Java.
This book attempts to familiarize the reader with the concepts of REST. It is a pragmatic guide for designing and developing web services using Java APIs for real-life use cases following best practices and for learning to secure REST APIs using OAuth and JWT. Finally, you will learn the role of RESTful web services for future technological advances, be it cloud, IoT or social media.
By the end of this book, you will be able to efficiently build robust, scalable, and secure RESTful web services using Java APIs.
Step-by-step guide to designing and developing robust RESTful web services. Each topic is explained in a simple and easy-to-understand manner with lots of real-life use-cases and their solutions.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 462
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2009
Second edition: September 2015
Third edition: November 2017
Production reference: 1151117
ISBN 978-1-78829-404-1
www.packtpub.com
Author
Bogunuva Mohanram Balachandar
Copy Editor
Muktikant Garimella
Reviewer
Mohamed Sanaulla
Project Coordinator
Ulhas Kambali
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Denim Pinto
Indexer
Tejal Daruwale Soni
ContentDevelopmentEditor
Vikas Tiwari
Production Coordinator
Arvindkumar Gupta
Technical Editor
Madhunikita Sunil Chindarkar
Jash Bavishi
Cover Work
Arvindkumar Gupta
Bogunuva Mohanram Balachandar works as associate director for a leading American multinational corporation, listed in NASDAQ-100, that provides digital, technology, consulting, and operations services. He has extensive experience in the design and development of multiple enterprise application integration projects, using various tools and technologies such as Oracle SOA Suite, Oracle Service Bus, Oracle AIA, IBM WebSphere Process Server, web services, RESTful services, Business Process Execution Language (BPEL), IBM WebSphere MQ, TIBCO EMS, Java, JMS, and Spring Integration.
He is certified in SOA, web services, and cloud technologies and has over 16 years of IT industry experience in software design and development. Prior to joining his current employer, he worked with IBM, Accenture, and Wipro.
Balachandar, in his current role, is responsible for designing the integration landscape for a leading bank.
Balachandar currently lives in London, UK with his wife, Lakshmi, and daughters, VeenaSri and NavyaSree.
There is a famous saying in India, Matha, Pitha, Guru, Deivam, which sets the order in which a person must show respect, starting with Matha (mother), and going on to Pitha (father), then Guru (teacher), and finally, Deivam (God).
First and foremost, I would like to thank my parents, Mr. BN Mohanram and Mrs. S Rajeswari, for laying the foundation of the core values required to become a responsible citizen. I have no words to explain the extensive support provided by them in every stage of my life; all I can say is that I am blessed to have them as my parents.
My teachers, Dr. SM Kannan and the late Dr. Sri Krishna, from KLN College of Engineering, incubated the desire for knowledge and innovation in me. I would like to thank them for their guidance and also for giving me opportunities on several occasions to interact with the young engineers of my college, be it as a guest lecturer or during brainstorming discussions on the latest technology trends.
"A woman not only protects herself but tirelessly takes care of her husband and preserves the family reputation." I would like to thank my wife, Mrs GL Lakshmi, for taking care of me and my family without any expectations. My special thanks to my daughters for sacrificing some of their play time so as not to disturb me while I wrote this book.
I would like to thank Packt for giving me this opportunity. My special thanks to Packt team members, Mr. Anurag Ghogre, Mr. Vikas Tiwari, Mr. Ulhas Kambali, and Mr. Denim Pinto for their extensive support whenever required. My sincere thanks to the technical reviewer, Mr. Mohamed Sanaulla, for detailed feedback on all the chapters and ensuring the quality of the content. My special thanks to my colleague Mr. Raja Malleswara Rao Pattamsetti for connecting me with Packt.
My sincere thanks to my elder brother, Mr. BM Karthikeyan, my relatives, and my friends for their unconditional support and well wishes.
Finally, I strongly believe all this has been possible only with the blessings of the Almighty. My thanks to the Almighty and I hope he brings peace and prosperity to this planet.
Mohamed Sanaulla is a software developer with more than 7 years of experience in developing enterprise applications and Java-based backend solutions for e-commerce applications. His interests include enterprise software development, refactoring and redesigning applications, designing and implementing RESTful web services, troubleshooting Java applications for performance issues, and TDD. He has a strong expertise in Java-based application development, ADF (JSF-based JavaEE web framework), SQL, PL/SQL, JUnit, designing RESTful services, Spring, Struts, Elasticsearch, and MongoDB. He is also a Sun Certified Java Programmer for the Java 6 platform. He is a moderator for https://javaranch.com/. He likes to share findings on his blog (https://sanaulla.info).
For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788294041.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Introducing the REST Architectural Style
The REST architectural style
Introducing HTTP
HTTP versions
Understanding the HTTP request-response model
Uniform resource identifier
Understating the HTTP request methods
Representing content types using HTTP header fields
HTTP status codes
The evolution of RESTful web services
The core architectural elements of a RESTful system
Data elements
Resources
URI
The representation of resources
Generic interaction semantics for REST resources
The HTTP GET method
The HTTP POST method
The HTTP PUT method
The HTTP DELETE method
Hypermedia as the Engine of Application State
Connectors
Components
The description and discovery of RESTful web services
Java tools and frameworks for building RESTful web services
Summary
Java APIs for JSON Processing
A brief overview of JSON
Understanding the JSON data syntax
Basic data types available with JSON
Sample JSON file representing employee objects
Processing JSON data
Using JSR 353 – Java API for processing JSON
Processing JSON with JSR 353 object model APIs
Generating the object model from the JSON representation
JSON value types
Generating the JSON representation from the object model
Processing JSON with JSR 353 streaming APIs
Using streaming APIs to parse JSON data
Using streaming APIs to generate JSON
Using the Jackson API for processing JSON
Processing JSON with Jackson tree model APIs
Using Jackson tree model APIs to query and update data
Processing JSON with Jackson data binding APIs
Simple Jackson data binding with generalized objects
Full Jackson data binding with specialized objects
Processing JSON with Jackson streaming APIs
Using Jackson streaming APIs to parse JSON data
Using Jackson streaming APIs to generate JSON
Using the Gson API for processing JSON
Processing JSON with object model APIs in Gson
Generating the object model from the JSON representation
Generating the parameterized Java collection from the JSON representation
Generating the JSON representation from the object model
Processing JSON with Gson streaming APIs
Reading JSON data with Gson streaming APIs
Writing JSON data with Gson streaming APIs
Java EE 8 enhancements for processing JSON
Using the JSR 374 – Java API for JSON Processing 1.1
Understanding the JSON Pointer
Processing JSON using JSON Pointer
Understanding the JSON Patch
Processing JSON using JSON Patch
Using the JSR 367 – Java API for JSON Binding
Processing JSON using JSON-B
Summary
Introducing the JAX-RS API
An overview of JAX-RS
JAX-RS annotations
Specifying the dependency of the JAX-RS API
Using JAX-RS annotations to build RESTful web services
Annotations for defining a RESTful resource
@Path
Annotations for specifying request-response media types
@Produces
@Consumes
Annotations for processing HTTP request methods
@GET
@PUT
@POST
@DELETE
@HEAD
@OPTIONS
Annotations for accessing request parameters
@PathParam
@QueryParam
@MatrixParam
@HeaderParam
@CookieParam
@FormParam
@DefaultValue
@Context
@BeanParam
@Encoded
Annotation inheritance
Returning additional metadata with responses
Understanding data binding rules in JAX-RS
Mapping the path variable with Java types
Mapping the request and response entity body with Java types
Using JAXB to manage the mapping of the request and response entity body to Java objects
Building your first RESTful web service with JAX-RS
Setting up the environment
Building a simple RESTful web service application using the NetBeans IDE
Adding CRUD operations on the REST resource class
Client APIs for accessing RESTful web services
Specifying a dependency of the JAX-RS client API
Calling REST APIs using the JAX-RS client
Simplified client APIs for accessing REST APIs
Summary
Advanced Features in the JAX-RS APIs
Understanding subresources and subresource locators in JAX-RS
Subresources in JAX-RS
Subresource locators in JAX-RS
Dynamic dispatching
Request matching
JAX-RS response builder explained
Exception handling in JAX-RS
Reporting errors using ResponseBuilder
Reporting errors using WebApplicationException
Reporting errors using application exceptions
Mapping exceptions to a response message using ExceptionMapper
Introducing validations in JAX-RS applications
A brief introduction to Bean Validation
Building custom validation constraints
What happens when Bean Validation fails in a JAX-RS application?
Supporting custom request-response message formats
Building custom entity provider
Marshaling Java objects to the CSV representation with MessageBodyWriter
Marshaling CSV representation to Java objects with MessageBodyReader
Asynchronous RESTful web services
Asynchronous RESTful web service client
Server-sent events
Managing an HTTP cache in a RESTful web service
Using the Expires header to control the validity of the HTTP cache
Using Cache-Control directives to manage the HTTP cache
Conditional request processing with the Last-Modified HTTP response header
Conditional request processing with the ETag HTTP response header
Conditional data update in RESTful web services
Understanding filters and interceptors in JAX-RS
Modifying request and response parameters with JAX-RS filters
Implementing server-side request message filters
Postmatching server-side request message filters
Prematching server-side request message filters
Implementing server-side response message filters
Implementing client-side request message filters
Implementing client-side response message filters
Modifying request and response message bodies with JAX-RS interceptors
Implementing request message body interceptors
Implementing response message body interceptors
Managing the order of execution for filters and interceptors
Selectively applying filters and interceptors on REST resources by using @NameBinding
Dynamically applying filters and interceptors on REST resources using DynamicFeature
Understanding the JAX-RS resource life cycle
Summary
Introducing JAX-RS Implementation Framework Extensions
Jersey framework extensions
Dynamically configuring JAX-RS resources during deployment
A quick look at the static resource configurations
Modifying JAX-RS resources during deployment using ModelProcessor
What is the Jersey model processor and how it works?
A brief look at the ModelProcessor interface
Building Hypermedia As The Engine Of Application State (HATEOAS) APIs
Programmatically building entity body links using JAX-RS APIs
Programmatically building header links using JAX-RS APIs
Declaratively building links using Jersey annotations
Specifying the dependency to use Jersey declarative linking
Enabling the Jersey declarative linking feature for the application
Declaratively adding links to the resource representation
Grouping multiple links using @InjectLinks
Declaratively building HTTP link headers using @InjectLinks
Reading and writing large binary objects using Jersey APIs
Building RESTful web services for storing images
Building RESTful web service for reading images
Generating a chunked output using Jersey APIs
Jersey client API for reading chunked input
Supporting server-sent events in RESTful web services
Understanding the Jersey server-side configuration properties
Monitoring RESTful web services using Jersey APIs
RESTEasy framework extensions
Caching using RESTEasy
Cache-control annotations
Client-side caching
GZIP compression/decompression
Multipart content handling
Summary
Securing RESTful Web Services
Securing and authenticating web services
HTTP basic authentication
Building JAX-RS clients with basic authentication
Securing JAX-RS services with basic authentication
Configuring the basic authentication
Defining groups and users in the GlassFish server
HTTP digest authentication
JWT authentication
JSON Web Token (JWT) overview
Using JWT to secure RESTful services
Securing RESTful web services with OAuth
Understanding the OAuth 1.0 protocol
Building the OAuth 1.0 client using Jersey APIs
Understanding the OAuth 2.0 protocol
Understanding the grant types in OAuth 2.0
Building the OAuth 2.0 client using Jersey APIs
Authorizing the RESTful web service accesses via the security APIs
Using SecurityContext APIs to control access
Using the javax.annotation.security annotations to control access
Using Jersey's role-based entity data filtering
Input validation
Key considerations for securing RESTful services
Summary
Description and Discovery of RESTful Web Services
The need for an interface contract
Web Application Description Language
Overview of the WADL structure
Generating WADL from JAX-RS
Generating a Java client from WADL
Market adoption of WADL
RESTful API Modeling Language
Overview of the RAML structure
Generating RAML from JAX-RS
Generating RAML from JAX-RS via CLI
Generating JAX-RS from RAML
Generating JAX-RS from RAML via CLI
A glance at the market adoption of RAML
Swagger
A quick overview of the Swagger structure
An overview of Swagger APIs
Generating Swagger from JAX-RS
Specifying dependency to Swagger
Configuring the Swagger definition
Adding a Swagger annotation on a JAX-RS resource class
Generating a Java client from Swagger
A glance at the market adoption of Swagger
Revisiting the features offered in WADL, RAML, and Swagger
Summary
RESTful API Design Guidelines
Designing RESTful web APIs
Identifying resources in a problem domain
Transforming operations to HTTP methods
Understanding the difference between PUT and POST
Naming RESTful web resources
Using HATEOAS in response representation
Hypertext Application Language
RFC 5988 - web linking
Fine-grained and coarse-grained resource APIs
Using header parameters for content negotiation
Multilingual RESTful web API resources
Representing date and time in RESTful web resources
Implementing partial response
Implementing partial update
Returning modified resources to the caller
Paging a resource collection
Implementing search and sort operations
Versioning RESTful web APIs
Including the version in the resource URI – URI versioning
Including the version in a custom HTTP request header – HTTP header versioning
Including the version in the HTTP Accept header – media type versioning
Hybrid approach for versioning APIs
Caching RESTful web API results
HTTP Cache-Control directive
HTTP conditional requests
Using HTTP status codes in RESTful web APIs
Overriding HTTP methods
Documenting RESTful web APIs
Asynchronous execution of RESTful web APIs
Microservice architecture style for RESTful web application
A quick recap
Summary
The Role of RESTful APIs in Emerging Technologies
Cloud services
Cloud characteristics
Cloud offering models
RESTful API Role in cloud services
Provisioning IT resources using RESTful APIs
Locating the REST API endpoint
Generating an authentication cookie
Provisioning a virtual machine instance
Internet of things
IoT platform
IoT benefits
RESTful API role in the IoT
Modern web applications
Single-page applications
RESTFul API role in single-page applications
Social media
Social media platforms
Social media benefits
RESTful API role in social media
Using Open Data Protocol with RESTful web APIs
A quick look at OData
URI convention for OData-based REST APIs
Reading resources
Querying data
Modifying data
Relationship operations
Summary
Useful Features and Techniques
Tools for building a JAX-RS application
Integration testing of JAX-RS resources with Arquillian
Adding Arquillian dependencies to the Maven-based project
Configuring the container for running the tests
Adding Arquillian test classes to the project
Running Arquillian tests
Using third-party entity provider frameworks with Jersey
Transforming the JPA model into OData-enabled RESTful web services
Packaging and deploying JAX-RS applications
Packaging JAX-RS applications with an Application subclass
Packaging the JAX-RS applications with web.xml and an Application subclass
Configuring web.xml for a servlet 2.x container
Configuring web.xml for a servlet 3.x container
Packaging the JAX-RS applications with web.xml and without an Application subclass
Configuring web.xml for the servlet 2.x container
Configuring web.xml for the servlet 3.x container
Summary
The World Wide Web (also known as WWW) has been the backbone of the information age, connecting distributed systems over networks. It has become an integral part of our day-to-day life; take, for example, reading a newspaper, checking the weather, searching for information via Google, or any other search engine. It is essential to note that all the information used by the systems is dispersed across the networks and transmitted via the WWW. Given the reach of the WWW, have you ever thought what are the architecture or design principles to be considered while developing an application for internet usage? How can you improve the scalability of a web application? With the advent of emerging technologies such as cloud, social media, and the Internet of Things, what considerations must be taken while developing a web application? I believe similar questions may have been in the mind of Roy Thomas Fielding. Roy Thomas Fielding's research on Architectural Styles and the Design of Network-Based Software Architectures (http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm) comes up with answers to these questions, with a novel architectural style for distributed hypermedia systems, popularly known as REpresentational State Transfer, abbreviated to REST.
This book familiarizes the reader with the concepts of REST. It serves as a practical guide for developing web applications following the REST architectural style, using Java APIs. This book is organized with plenty of real-life examples each chapter to help the reader gain hands-on experience and boost their confidence in applying what they have learned.
Chapter 1, Introducing the REST Architectural Style, covers the REST software architectural style and the core architectural elements that form a RESTful system.
Chapter 2, Java APIs for JSON Processing, gives an overview of the JSON messaging format and the popular tools and frameworks around JSON.
Chapter 3, Introducing the JAX-RS API, introduces the JAX-RS APIs. This chapter will explain how we can build RESTful web services with the JAX-RS APIs.
Chapter 4, Advanced Features in the JAX-RS APIs, takes a deeper look into the advanced JAX-RS APIs, with many real-life use cases.
Chapter 5, Introducing JAX-RS Implementation Framework Extensions, discusses some of the very useful JAX-RS implementation framework extension APIs that are not yet a part of the JAX-RS standard.
Chapter 6, Securing RESTful Web Services, explores how to secure RESTful web services using different authentication and authorization techniques.
Chapter 7, Description and Discovery of RESTful Web Services, describes the popular solutions that are available today for describing, producing, consuming, and visualizing RESTful web services.
Chapter 8, RESTful API Design Guidelines, discusses best practices and design guidelines that developers will find useful while building RESTful web services.
Chapter 9, The Role of RESTful APIs in Emerging Technologies, discusses the applicability of the RESTful API in recent technology trends such as cloud, IoT, single-page applications, and open data protocol.
Appendix, Useful Features and Techniques, discusses on the tools needed for building and testing JAX-RS application with various packaging or deployment models. Also covers the technique to convert JPA models into OData-enabled RESTful web services.
The examples discussed in this book were built using the following software and tools:
The Java SE Development Kit 8, or newer versions
NetBeans IDE 8.2 (with the Java EE bundle), or newer versions
Glassfish Server 4.1, or newer versions
Maven 3.2.3, or newer versions
Oracle Database Express Edition 11g Release 2, or newer versions
The HR sample schema that comes with the Oracle database
The Oracle database JDBC driver (
ojdbc7.jar
or newer versions)
Detailed instructions for setting up all the tools required to run the examples used in this book are discussed in the Appendix, Useful Features and Techniques.
This book is for Java developers who want to design and develop scalable and robust RESTful web services with the Java APIs. Contents are structured by keeping an eye on real life use cases from the RESTful API world and their solutions. Although the JAX-RS API solves many of the common RESTful web service use cases, some solutions are yet to be standardized as JAX-RS APIs. Keeping this in mind, a chapter is dedicated in this book for discussing extension APIs, which takes you beyond JAX-RS. This book also discusses the best practices and design guidelines for your REST APIs. In a nutshell, you will find this book useful while dealing with many real life use cases, such as dynamic resource configuration, message broadcasting with the server-sent event, HATEOAS, and so on.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The DynamicFeature interface is executed at deployment time for each resource method."
A block of code is set as follows:
[{"departmentId":10,"departmentName":"IT","manager":"John Chen"}, {"departmentId":20,"departmentName":"Marketing","manager":"Ameya J"}, {"departmentId":30,"departmentName":"HR","manager":"Pat Fay"}]
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Navigate to Configurations | server-config | Security | Realms | File."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/RESTful-Java-Web-Services-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover the Representational State Transfer (REST) software architectural style, as described in Roy Fielding's PhD dissertation. You may find a brief discussion on HTTP before getting into the details of REST. Once the base is set, we will be ready for the next step. We will then discuss the set of constraints, the main components, and the abstractions that make a software system RESTful. Here is the list of topics covered in this chapter:
The REST architectural style
Introducing HTTP
The evolution of RESTful web services
The core architectural elements of a RESTful system
The description and discovery of RESTful web services
Java tools and frameworks for building RESTful web services
REST is not an architecture; rather, it is a set of constraints that creates a software architectural style, which can be used for building distributed applications. A major challenge to the distributed applications is attributed to the diversity of systems in an enterprise offering silos of business information, as depicted in the following diagram:
Often, an enterprise demands simplified access and updates to data residing in different systems. Fielding arrived at REST by evaluating all the networking resources and technologies available for creating distributed applications. He observed that without any constraints, one may end up developing applications with no rules or limits that are hard to maintain and extend. After considerable research on building a better architecture for a distributed application, he ended up with the following constraints that define a RESTful system:
Client-server
: This constraint keeps the client and server loosely coupled. In this case, the client does not need to know the implementation details in the server, and the server is not worried about how the data is used by the client. However, a common interface is maintained between the client and server to ease communication.
Stateless
: There should be no need for the service to keep user sessions. In other words, each request should be independent of the others. This improves scalability, as the server does not need to manage the state across multiple requests, with some trade-off on the network performance.
Cacheable
: This constraint has to support a caching system. The network infrastructure should support a cache at different levels. Caching can avoid repeated round trips between the client and the server for retrieving the same resource.
Uniform interface
: This constraint indicates a generic interface to manage all the interactions between the client and server in a unified way, which simplifies and decouples the architecture. This constraint indicates that each resource exposed for use by the client must have a unique address and should be accessible through a generic interface. The client can act on the resources by using a generic set of methods.
Layered system
: The server can have multiple layers for implementation. This layered architecture helps to improve scalability by enabling load balancing. It also improves the performance by providing shared caches at different levels.
Being the door to the system,
the top layer can enforce security policies as well.
Code on demand
: This constraint is optional. This constraint indicates that the functionality of the client applications can be extended at runtime by allowing a code download from the server and executing the code. Some examples are the applets and the JavaScript code that get transferred and executed at the client side at runtime.
The following diagram illustrates a high-level architectural view of a RESTful system:
The preceding constraints do not dictate what kind of technology to use; they only define how the data is transferred between components and the benefits of the guidelines. Therefore, a RESTful system can be implemented in any available networking architecture. More importantly, there is no need for us to invent new technologies or networking protocols. We can very well use the existing networking infrastructures, such as the World Wide Web (WWW), to create RESTful architectures. Consequently, a RESTful architecture is one that is maintainable, extendable, and distributed.
Before all the REST constraints were formalized, we already had a working example of a RESTful system—the web. Now, you may ask why introduce these RESTful requirements to web application development when it is agreed that the web is already RESTful.
Here is the answer, we first need to qualify what it means for the web to be RESTful. On one hand, the static web is RESTful because static websites follow Fielding's definition of a RESTful architecture. For instance, the existing web infrastructure provides caching systems, stateless connections, and unique hyperlinks to resources, where resources include all the documents available on every website, and the representation of these documents is already set by files being browser-readable (the HTML files, for example). Therefore, the static web is a system built in the REST-like architectural style. In simple words, we can say that REST leverages these amazing features of the web with some constraints.
On the other hand, traditional dynamic web applications have not always been RESTful because they typically break some of the outlined constraints. For instance, most dynamic applications are not stateless, as servers require tracking users through the container sessions or client-side cookie schemes. Therefore, we conclude that the dynamic web is not normally built in the REST-like architectural style.
Now, you may be curious to learn more about a RESTful system. The rest of the chapter will definitely help you to know the internals. However, the topics on the RESTful system that we are going to discuss in the coming sections may need some basic knowledge of HTTP. So, let's take a crash course on HTTP to learn some basics and then proceed with our discussions thereafter. You can skip the next section if you are already familiar with HTTP.
Hypertext Transfer Protocol (HTTP) is the foundation of data communication for WWW. To comprehend HTTP, it is essential to understand the etymology of hypertext. The major constraint of written text is its linearity, that is, not being able to easily reference other text that the user can easily access. Hypertext overcomes this constraint, with the concept of hyperlinks, which allows the user to easily navigate to the referenced section. HTTP is an application layer protocol that defines how hypertext messages are formatted, transmitted, and processed over the internet. Let's have a quick recap of HTTP in this section.
HTTP has been consistently evolving over time. So far, there have been three versions. HTTP/0.9 was the first documented version, which was released in the year 1991. This was very primitive and supported only the GET method. Later, HTTP/1.0 was released in the year 1996 with more features and corrections for the shortcomings of the previous release. HTTP/1.0 supported more request methods such as GET, HEAD, and POST. The next release was HTTP/1.1 in the year 1999. This was a revision of HTTP/1.0. This version is in common use today.
HTTP/2 (originally named HTTP 2.0) was published in 2015. It is mainly focused on how the data is framed and transported between the client and server. It is currently supported by major browsers and as of May 2017, 13.7% of the top 10 million websites support HTTP/2.
HTTP works in a request-response manner. Let's take an example to understand this model better.
The following example illustrates the basic request-response model of communication between a web browser and a server over HTTP. The following sequence diagram illustrates the request and response messages sent between the client and server:
Here is the detailed explanation for the sequence of actions shown in the preceding diagram.
The user enters http://www.example.com/index.html in the browser and then submits the request. The browser establishes a connection with the server and sends a request to the server in the form of a request method (URI) and a protocol version, followed by a message containing the request modifiers, client information, and possible body content. The sample request looks as follows:
GET /index.html HTTP/1.1 Host: www.example.com User-Agent: Mozilla/5.0 Accept: text/htmlAccept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive
Let's take a minute to understand the structure of the preceding message. The following code is what you see in the first lines of request in our example:
GET /index.html HTTP/1.1
The general format for the request line is an HTTP command, followed by the resource to retrieve and the HTTP version supported by the client. The client can be any application that understands HTTP, although this example refers to a web browser as the client. The request line and other header fields must end with a carriage return character followed by a line-feed character. In the preceding example, the browser instructs the server to get the index.html file through the HTTP 1.1 protocol.
The rest of the information that you may see in the request message is the HTTP header values for use by the server. The header fields are colon-separated key-value pairs in the plain-text format, terminated by a carriage return and followed by a line feed character. The header fields in the request, such as the acceptable content types, languages, and connection type, are the operating parameters for an HTTP transaction. The server can use this information while preparing the response to the request. A blank line is used at the end of the header to indicate the end of the header portion in a request.
The last part of an HTTP request is the HTTP body. Typically, the body is left blank unless the client has some data to submit to the server. In our example, the body part is empty as this is a GET request for retrieving a page from the server.
So far, we have been discussing the HTTP request sent by the client. Now, let's take a look at what happens on the server when the message is received. Once the server receives the HTTP request, it will process the message and return a response to the client. The response is made up of the reply status code from the server, followed by the HTTP header and a response content body:
HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=604800 Content-Type: text/html Date: Wed, 03 Dec 2014 15:05:59 GMT Content-Length: 1270 <html> <head> <title>An Example Page</title> </head> <body> Hello World ! </body> </html>.
The first line in the response is a status line. It contains the HTTP version that the server is using, followed by a numeric status code and its associated textual phrase. The status code indicates one of the following parameters: informational codes, success of the request, client error, server error, or redirection of the request. In our example, the status line is as follows:
HTTP/1.1 200 OK
The next item in the response is the HTTP response header. Similar to the request header, the response header follows the colon-separated name-value pair format terminated by a carriage return and line feed characters. The HTTP response header can contain useful information about the resource being fetched, the server hosting the resource, and some parameters controlling the client behavior while dealing with resource, such as content type, cache expiry, and refresh rate.
The last part of the response is the response body. Upon successful processing of the request, the server will add the requested resource in the HTTP response body. It can be HTML, binary data, image, video, text, XML, JSON, and so on. Once the response body has been sent to the requestor, the HTTP server will disconnect if the connection created during the request is not of the keep-alive type (using the Connection: keep-alive header).
You may see the term Uniform Resource Identifier (URI) used very frequently in the rest of the chapter. A URI is a text that identifies any resource or name on the internet. One can further classify a URI as a Uniform Resource Locator (URL) if the text used for identifying the resource also holds the means for accessing the resource, such as HTTP or FTP. The following is one such example:
https://www.packtpub.com/application-development
In the previous session, we discussed about the HTTP GET request method for retrieving a page from the server. More request methods similar to GET are available with HTTP, each performing specific actions on the target resource. Let's learn about these methods and their role in client-server communication over HTTP.
The set of common methods for HTTP/1.1 is listed in the following table:
Method
Description
GET
This method is used for retrieving resources from the server by using the given URI.
HEAD
This method is the same as the GET request, but it only transfers the status line and the header section without the response body.
POST
This method is used for posting data to the server. The server stores the data (entity) as a new subordinate of the resource identified by the URI. If you execute POST multiple times on a resource, it may yield different results.
PUT
This method is used for updating the resource pointed by the URI. If the URI does not point to an existing resource, the server can create the resource with that URI.
DELETE
This method deletes the resource pointed by the URI.
TRACE
This method is used for echoing the contents of the received request. This is useful for the debugging purpose with which the client can see what changes (if any) have been made by the intermediate servers.
OPTIONS
This method returns the HTTP methods that the server supports for the specified URI.
CONNECT
This method is used for establishing a connection to the target server over HTTP.
PATCH
This method is used for applying partial modifications to a resource identified by the URI.
We may use some of these HTTP methods, such as GET, POST, PUT, and DELETE, while building RESTful web services in the later chapters.
Continuing our discussion on HTTP, the next section discusses the HTTP header parameter, which identifies the content type for the message body.
When we discussed the HTTP request-response model in the Understanding the HTTP request-response model section, we talked about the HTTP header parameters (the name-value pairs) that define the operating parameters of an HTTP transaction. In this section, we will cover the header parameter used for describing the content types present in the request and the response message body.
The Content-Type header in an HTTP request or response describes the content type for the message body. The Accept header in the request tells the server the content types that the client is expecting in the response body. The content types are represented using the internet media type. The internet media type (also known as the MIME type) indicates the type of data that a file contains. Here is an example:
Content-Type: text/html
This header indicates that the body content is presented in the html format. The format of the content type values is a primary type/subtype followed by optional semicolon-delimited attribute-value pairs (known as parameters).
The internet media types are broadly classified into the following categories on the basis of the primary (or initial) Content-Type header:
text
: This type indicates that the content is a plain text and no special software is required to read the contents. The subtype represents more specific details about the content, which can be used by the client for special processing, if any. For instance,
Content-Type: text/html
indicates that the body content is
html
, and the client can use this hint to kick off an appropriate rendering engine while displaying the response.
multipart
: As the name indicates, this type consists of multiple parts of independent data types. For instance,
Content-Type: multipart/form-data
is used for submitting forms that contain the files, non-ASCII data, and binary data.
message
: This type encapsulates more messages. It allows messages to contain other messages or pointers to other messages. For instance, the
Content-Type: message/partial
content type allows for large messages to be broken up into smaller messages. The full message can then be read by the client (user agent) by putting all the broken messages together.
image
: This type represents the image data. For instance,
Content-Type: image/png
indicates that the body content is a
.png
image.
audio
: This type indicates the audio data. For instance,
Content-Type: audio/mpeg
indicates that the body content is MP3 or other MPEG audio.
video
: This type indicates the video data. For instance,
Content-Type: video/mp4
indicates that the body content is an MP4 video.
application
: This type represents the application data or binary data. For instance,
Content-Type: application/json; charset=utf-8
designates the content to be in the
JavaScript Object Notation
(
JSON
) format, encoded with UTF-8 character encoding.
We may need to use some of these content types in the next chapters while developing the RESTful web services. This hint will be used by the client to correctly process the response body.
The next topic, a simple but important one, is on HTTP status codes.
For every HTTP request, the server returns a status code indicating the processing status of the request. In this section, we will see some of the frequently used HTTP status codes. A basic understanding of status codes will definitely help us later while designing RESTful web services:
1xx Informational
: This series of status codes indicates informational content. This means that the request is received and processing is going on. Here are the frequently used informational status codes:
100 Continue
: This code indicates that the server has received the request header and the client can now send the body content. In this case, the client first makes a request (with the
Expect: 100-continue
header) to check whether it can start with a partial request. The server can then respond either with
100 Continue (OK)
or
417 Expectation Failed (No)
along with an appropriate reason.
101 Switching Protocols
: This code indicates that the server is OK for a protocol switch request from the client.
102 Processing
: This code is an informational status code used for long running processing to prevent the client from timing out. This tells the client to wait for the future response, which will have the actual response body.
2xx Success
: This series of status codes indicates the successful processing of requests. Some of the frequently used status codes in this class are as follows:
200 OK
: This code indicates that the request is successful and the response content is returned to the client as appropriate.
201 Created
: This code indicates that the request is successful and a new resource is created.
204 No Content
: This code indicates that the request is processed successfully, but there's no return value for this request. For instance, you may find such status codes in response to the deletion of a resource.
3xx Redirection
: This series of status codes indicates that the client needs to perform further actions to logically end the request. A frequently used status code in this class is as follows:
304 Not Modified
: This status indicates that the resource has not been modified since it was last accessed. This code is returned only when allowed by the client via setting the request headers as
If-Modified-Since
or
If-None-Match
. The client can take appropriate action on the basis of this status code.
4xx Client Error
: This series of status codes indicates an error in processing the request. Some of the frequently used status codes in this class are as follows:
400 Bad Request
: This code indicates that the server failed to process the request because of malformed syntax in the request. The client can try again after correcting the request.
401 Unauthorized
: This code indicates that authentication is required for the resource. The client can try again with appropriate authentication.
403 Forbidden
: This code indicates that the server is refusing to respond to the request even if the request is valid. The reason will be listed in the body content if the request is not a
HEAD
method.
404 Not Found
: This code indicates that the requested resource is not found at the location specified in the request.
405 Method Not Allowed
: This code indicates that the HTTP method specified in the request is not allowed on the resource identified by the URI.
408 Request Timeout
: This code indicates that the client failed to respond within the time window set on the server.
409 Conflict
: This code indicates that the request cannot be completed because it conflicts with some rules established on resources, such as validation failure.
5xx Server Error
: This series of status codes indicates server failures while processing a valid request. Here is one of the frequently used status codes in this class:
500 Internal Server Error
: This code indicates a generic error message, and it tells that an unexpected error occurred on the server and that the request cannot be fulfilled.
With this topic, we have finished the crash course on HTTP basics. We will be resuming our discussion on RESTful web services in the next section. Take a deep breath and be ready for an exciting journey.
Before getting into the details of REST-enabled web services, let's take a step back and define what a web service is. Then, we will see what makes a web service RESTful.
A web service is one of the most popular methods of communication between the client and server applications over the internet. In simple words, web services are web application components that can be published, found, and used over the web. Typically, a web service has an interface describing the web service APIs, which is known as Web Services Description Language (WSDL). A WSDL file can be easily processed by machines, which blows out the integration complexities that you may see with large systems. Other systems interact with the web service by using Simple Object Access Protocol (SOAP) messages. The contract for communication is driven by the WSDL exposed by the web service. Typically, communication happens over HTTP with XML in conjunction with other web-related standards.
What kind of problems do the web services solve? There are two main areas where web services are used:
Many of the companies specializing in internet-related services and products have opened their doors to developers using publicly available APIs. For instance, companies such as Google, Yahoo, Amazon, and Facebook are using web services to offer new products that rely on their massive hardware infrastructures. Google and Yahoo offer their search services, Amazon offers its on-demand hosting storage infrastructure, and Facebook offers its platform for targeted marketing and advertising campaigns. With the help of web services, these companies have opened the door to the creation of products that did not exist some years ago.
Web services are being used within enterprises to connect previously disjointed departments such as marketing and manufacturing. Each department or
Line Of Business
(
LOB
) can expose its business processes as a web service, which can be consumed by the other departments.
By connecting more than one department to share information by using web services, we begin to enter the territory of
Service-Oriented Architecture
(
SOA
). SOA is essentially a collection of services, each talking to one another in a well-defined manner, in order to complete relatively large and logically complete business processes.
All these points lead to the fact that web services have evolved as a powerful and effective channel of communication between client and server over a period of time. The good news is that we can integrate RESTful systems into a web service-oriented computing environment without much effort. Although you may have a fair idea of RESTful web services by now, let's see the formal definition before proceeding further.
Remember that REST is not the system's architecture in itself, but it is a set of constraints that when applied to the system's design leads to a RESTful architecture. As our definition of a web service does not dictate the implementation details of a computing unit, we can easily incorporate RESTful web services to solve large-scale problems. We can even fully use RESTful web services in the larger umbrella of the SOA, given that it inherently meets the basic values of SOA, as depicted in the following image:
With this larger view of SOA, we begin to see how REST has the potential to impact the new computing models being developed.
Having learned the basics of a RESTful system, you are now ready to meet more exciting concepts around REST. In this section, you will learn the core architectural elements that make a system RESTful.
