RESTful Java Web Services, Second Edition - Jobinesh Purushothaman - E-Book

RESTful Java Web Services, Second Edition E-Book

Jobinesh Purushothaman

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

REST (REpresentational State Transfer) is a simple yet powerful software architecture style to create scalable web services and allow them to be simple, lightweight, and fast. The REST API uses HTTP and JSON, so that it can be used with many programming languages such as Ruby, Java, Python, and Scala. Its use in Java seems to be the most popular though, because of the API's reusability.
This book is a guide to developing RESTful web services in Java using the popular RESTful framework APIs available today. You will begin with gaining an in-depth knowledge of the RESTful software architectural style and its relevance in modern applications. Further, you will understand the APIs to parse, generate, transform, and query JSON effectively. Then, you will see how to build a simple RESTful service using the popular JAX-RS 2.0 API along with some real-world examples. This book will introduce you to the Jersey framework API, which is used to simplify your web services.
You will also see how to secure your services with various authentication mechanisms. You will get to grips with various solutions to describe, produce, consume, and visualize RESTful web services. Finally, you will see how to design your web services to equip them for the future technological advances, be it Cloud or mobile computing.
By the end of this book, you will be able to efficiently build robust, scalable, and secure RESTful web services, making use of the JAX-RS and Jersey framework extensions.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 446

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

RESTful Java Web Services Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
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
1. Introducing the REST Architectural Style
The REST architectural style
Introducing HTTP
HTTP versions
Understanding the HTTP request-response model
Uniform resource identifier
Understanding 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
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
Description and discovery of RESTful web services
Java tools and frameworks for building RESTful web services
Summary
2. Java APIs for JSON Processing
A brief overview of JSON
Understanding the JSON data syntax
Basic data types available with JSON
A 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
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
Summary
3. 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
Specifying the @Path annotation on a resource class
Specifying the @Path annotation on a resource class method
Specifying variables in the URI path template
Restricting values for path variables with regular expressions
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
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 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
4. Advanced Features in the JAX-RS API
Understanding subresources and subresource locators in JAX-RS
Subresources in JAX-RS
Subresource locators in JAX-RS
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 a custom entity provider
Marshalling Java objects to the CSV representation with MessageBodyWriter
Marshalling CSV representation to Java objects with MessageBodyReader
Asynchronous RESTful web services
Asynchronous RESTful web service client
Managing 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 lifecycle
Summary
5. Introducing the Jersey Framework Extensions
Specifying dependencies for Jersey
Programmatically configuring JAX-RS resources during deployment
A quick look at the static resource configurations
Modifying JAX-RS resources during deployment using ModelProcessor
What is Jersey ModelProcessor and how does it work?
A brief look at the ModelProcessor interface
Building Hypermedia as the Engine of Application State (HATEOAS) APIs
Formats for specifying JSON REST API hypermedia links
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
Enable Jersey declarative linking feature for the application
Declaratively adding links to resource representation
Grouping multiple links using @InjectLinks
Declaratively building HTTP link headers using @InjectLinks
Reading and writing binary large objects using Jersey APIs
Building RESTful web service for storing images
Building RESTful web service for reading images
Generating chunked output using Jersey APIs
Jersey client API for reading chunked input
Supporting Server Sent Event in RESTful web services
Understanding the Jersey server-side configuration properties
Monitoring RESTful web services using Jersey APIs
Summary
6. 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 JAX-RS application for basic authentication
Defining groups and users in the GlassFish server
HTTP digest authentication
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 with the Jersey framework
Using Jersey's role-based entity data filtering
Input validation
Summary
7. The Description and Discovery of RESTful Web Services
Introduction to RESTful web services
Web Application Description Language
An overview of the WADL structure
Generating WADL from JAX-RS
Generating the Java client from WADL
Market adoption of WADL
RESTful API Modeling Language
An 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 Swagger's structure
An overview of Swagger APIs
Generating Swagger from JAX-RS
Specifying dependency to Swagger
Configuring the Swagger definition
Adding Swagger annotations on a JAX-RS resource class
Generating Java client from Swagger
A glance at the market adoption of Swagger
Revisiting the features offered in WADL, RAML, and Swagger
Summary
8. RESTful API Design Guidelines
Identifying resources in a problem domain
Transforming operations to HTTP methods
Understanding the difference between PUT and POST
Naming RESTful web resources
Fine-grained and coarse-grained resource APIs
Using header parameter 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 resource collection
Implementing search and sort operations
Using HATEOAS in response representation
Hypertext Application Language
RFC 5988 – Web Linking
Versioning RESTful web APIs
Including the version in resource URI – the URI versioning
Including the version in a custom HTTP request header – HTTP header versioning
Including the version in a HTTP Accept header – the 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 applications
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
A. 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 tests
Adding Arquillian test classes to the project
Running Arquillian tests
Implementing PATCH support in JAX-RS resources
Defining the @PATCH annotation
Defining a resource method to handle HTTP PATCH requests
Using third-party entity provider frameworks with Jersey
Transforming the JPA model in to 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
Index

RESTful Java Web Services Second Edition

RESTful Java Web Services Second Edition

Copyright © 2015 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

Production reference: 1160915

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78439-909-2

www.packtpub.com

This book is an update to RESTful Java Web Services by Jose Sandoval.

Credits

Author

Jobinesh Purushothaman

Reviewers

Erik Azar

Giuliano Araujo Bertoti

Ludovic Dewailly

Debasis Roy

Commissioning Editor

Nadeem N. Bagban

Acquisition Editor

Harsha Bharwani

Content Development Editor

Amey Varangaonkar

Technical Editors

Novina Kewalramani

Shiny Poojary

Copy Editors

Tani Kothari

Angad Singh

Project Coordinator

Suzanne Coutinho

Proofreader

Safis Editing

Indexer

Tejal Soni

Graphics

Jason Monteiro

Abhinash Sahu

Production Coordinator

Manu Joseph

Cover Work

Manu Joseph

About the Author

Jobinesh Purushothaman works with Oracle as a consulting solutions architect. In his current role, he is involved in the design and architectural decisions of various products that use Java EE and Oracle Application Development Framework technologies. Occasionally, he speaks at industry conferences, such as JavaOne and the Oracle Technology Network Developer Day. Jobinesh authored his first book, Oracle ADF Real World Developer's Guide, in 2012 for Packt Publishing. You can find his blog at http://www.jobinesh.com.

He holds a master of science (MSc) degree in computer science from Bharathiar University, India, and a master of business administration (MBA) degree from Indira Gandhi National Open University (IGNOU), India. After completing his MSc in computer science, Jobinesh started his career in 1999 with MicroObjects Private Limited, India. His career has taken him to different countries and various companies, where he has worked as a developer, technical leader, mentor, and technical architect. Jobinesh joined Oracle India Private Limited in 2008. Prior to joining Oracle, he worked as a senior software engineer at Emirates Group IT, Dubai from 2004 to 2008, where he was part of an IT strategy and architecture team.

Jobinesh currently lives in Bangalore, India, with his wife, Remya, son, Chinmay, and daughter, Ameya.

Acknowledgments

First and foremost, I would like to thank my parents, Mr. Purushothaman M.R and Mrs. Ratnam K.N, for allowing me to realize my own potential. All the support and encouragement they have provided me over the years were the greatest gifts that anyone has ever given me. I would like to thank my elder brother, Mr. Biju P Manakkattil, with all my heart for all the support he gave me throughout my life.

A thank you to my lovely wife, Remya, for her love, care, understanding, and sacrifices. Thanks to my son, Chinmay, for being my true inspiration for this work. Thanks to my sweet little daughter, Ameya, for filling my life with fun and joy. I could not have done this without their support.

Thanks to my nephews, Devadathan and Dhananjay, and sister-in-law, Mrs. Kavitha Biju, for all their support and well wishes. Thanks to my parents-in-law, Mr. Mohanan P.C and Mrs. Presanna P.N, for their love and care.

I sincerely thank and appreciate the team at Packt Publishing for their unconditional support, professionalism, and commitment through this project. Special thanks to Amey Varangaonkar, Harsha Bharwani, and Nadeem Bagban for all their support throughout this project. Thanks to all the technical reviewers for ensuring the quality of this book. They include Erik Azar, Ludovic Dewailly, Giuliano Araujo Bertoti, and Debasis Roy.

Special thanks to my managers at Oracle—Sharad Medhavi, who is a senior director at Oracle, and Chris Tonas, vice president at Oracle—for their support throughout this project. Thanks to Rekha Mathew, the technical manager at Oracle, for her help with Appendix, Useful Features and Techniques, in this book. Thanks to Vinay Agarwal, the principal product manager at Oracle, for his valuable insights on the REST metadata formats.

Thanks to the members of the Java EE, Jersey framework, and Apache Olingo communities for their timely responses to the questions that I raised in the discussion forums and mailing lists. A special thanks to all my friends for their encouragement and unconditional support throughout my life.

About the Reviewers

Erik Azar has been a professional software architect and developer for over 20 years. He has worked in diverse positions for companies ranging from start-ups to Fortune 500 companies, developing software such as systems and network management platforms, enterprise business applications in the insurance industry (specializing in healthcare, both personal and commercial), and benefit management.

He's currently a senior technical architect at Availity, LLC. He works with a small core team, developing Availity's next-generation healthcare REST API platform. He currently resides in Jacksonville, Florida, USA, with his partner, Rebecca; their three teenage children, Patrick, Kyra, and Cassandra; and their three dogs.

In his spare time, Erik enjoys exploring various open source operating systems, such as Haiku (BeOS). He has been a Linux hobbyist since the days of the original Slackware and Debian distros in the early 90s. Today, he's most interested in embedded devices and building REST APIs to manage IoT devices on the cloud. When he's not behind a computer, you can find him out riding his Harley, out with friends enjoying the local Jacksonville music scene, or working with non-profit organizations to help them understand how they can use technology to help market, fundraise, and manage their information.

I would like to use this opportunity to extend a special acknowledgement to my family for their support during the course of this book's development.

And I'd also like to acknowledge Suzanne Coutinho from the Packt Publishing team for her support in dealing with my challenging workload and schedule with my job during the development of this book.

Giuliano Araujo Bertoti is a master of science in electronics and computer engineering from the Aeronautics Institute of Technology (ITA), Brazil. He teaches software engineering and human-computer interaction disciplines at FATEC, which is an institute of technology in Brazil. In his free time, he walks with his beautiful wife and son in the gardens and plays soccer.

I would like to thank my mom, dad, grandma, son, and wife for their support at all times.

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.com (https://www.fancygiving.com/), which is a social shopping, wishing, and gifting platform, to architect and build their system. His interests lie in software architecture and tackling the challenges of the web scale. He is the author of Building a RESTful Web Service with Spring, Packt Publishing.

I would like to thank my fiancée, Gaia, for helping me find the time to review this book during a very busy period.

Debasis Roy is working as a senior software engineer for NewsCred, in their Dhaka office. He has more than 8 years of professional experience in Java/C++/web-relevant technologies. He is enthusiastic about application architecture.

Currently, he is working on the development of the content marketing system for NewsCred. Previously, he worked at Vizrt. There, he was involved in the development of their sports analysis tool called Viz Sports (also known as LiberoVision), and the Viz Online Suite (also known as Escenic).

He has also worked on RESTful Java Web Services Security and PostgreSQL Administration Essentials, both published by Packt Publishing.

I would like to thank Packt Publishing for giving me the opportunity to review this wonderful book and for helping me learn new things.

www.PacktPub.com

Support files, eBooks, discount offers, and more

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.com and 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://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

Representational State Transfer (REST) is a simple yet powerful software architecture style that is meant for creating scalable web services. This book, RESTful Java web services, is a practical guide for developing RESTful web services using JAX-RS and Jersey extension APIs.

The book starts off with an introduction to RESTful web services and assumes that the reader has no prior knowledge of the RESTful architectural style. Each topic is explained with real-life use cases and code samples. This approach helps the reader in easily translating the theories into solutions for many kinds of real life use cases. In a nutshell, this is a practical guide on using JAX-RS and the Jersey framework extensions to build robust RESTful web services; it is not just about the theory of REST.

What this book covers

Chapter 1, Introducing the REST Architectural Style, covers the REST software architectural style and core architectural elements that form a RESTful system.

Chapter 2, Java APIs for JSON Processing, gives an overview of the JSON message format, and the popular tools and frameworks around JSON.

Chapter 3, Introducing the JAX-RS API, introduces JAX-RS APIs. This chapter will explain how to build RESTful web services with JAX-RS APIs.

Chapter 4, Advanced Features in the JAX-RS API, takes a deeper look into the advanced JAX-RS APIs, along with many real life use cases and code samples.

Chapter 5, Introducing the Jersey Framework Extensions, discusses some of the very useful Jersey 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 the HTTP basic authentication and OAuth protocols.

Chapter 7, The Description and Discovery of RESTful Web Services, describes popular solutions that are available today for describing, producing, consuming, and visualizing RESTful web services.

Chapter 8, RESTful API Design Guidelines, discusses the best practices and design guidelines that developers will find useful while building RESTful web services. Learning the best practices will help you avoid common pitfalls that others might have faced before.

Appendix, Useful Features and Techniques, covers various useful features and techniques that we had deferred while discussing specific topics in this book. This section explores tools and techniques for building, testing, extending, and packaging JAX-RS web applications.

What you need for this book

The examples discussed in this book are built using the following software and tools:

The Java SE Development Kit 8, or newer versionsNetBeans IDE 8.0.2 (with the Java EE bundle), or newer versions The Glassfish Server 4.1, or newer versionsMaven 3.2.3, or newer versionsThe Oracle Database Express Edition 11g Release 2, or newer versionsThe HR sample schema that comes with the Oracle databaseThe Oracle database JDBC driver (ojdbc7.jar or newer versions)

Detailed instructions for setting up all the required tools to run the examples used in this book are discussed in the Appendix, Useful Features and Techniques section of this book.

Who this book is for

This book is for Java developers who want to design and develop scalable and robust RESTful web services with the JAX-RS and Jersey 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 Jersey 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.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "Assume that we want to delete the Sales department from the data storage."

A block of code is set as follows:

{"departmentId":10, "departmentName":"IT", "manager":"John Chen, "links": [ { "rel": "employees", "href": "http://packtpub.com/resources/departments/IT/ employees" } ]"}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

@Path("departments") @Produces(MediaType.APPLICATION_JSON) public class DepartmentResource{ //Class implementation goes here... }

Any command-line input or output is written as follows:

mvn install –DskipTests

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Select Local Domain and click on Next to continue the wizard."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via 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 on www.packtpub.com/authors.

Customer support

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.

Downloading the example code

You can download the example code files for all Packt books you have purchased 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 e-mailed directly to you.

Instructions for running examples are available in the README.md file present in the root folder of each project.

Errata

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

Piracy of copyright 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.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Introducing the REST Architectural Style

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 styleIntroducing HTTPThe evolution of RESTful web servicesThe core architectural elements of a RESTful systemDescription and discovery of RESTful web servicesJava tools and frameworks for building RESTful web services

The REST architectural style

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.

Tip

You can read Architectural Styles and the Design of Network-Based Software Architectures, Roy Fielding, 2000, which talks about the REST architectural style by visiting http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm.

Fielding arrived at REST by evaluating all 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 with the following constraints that define a RESTful system:

Client-server: This constraint keeps the client and the 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 the server to ease the communication.Stateless: There should be no need for the service to keep users' sessions. In other words, each request should be independent of the others.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 interactions between the client and the 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 performance by providing shared caches at different levels. The top layer, being the door to the system, 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 on 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 data is transferred between components and the benefits of following 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), or simply the Web, to create RESTful architectures. Consequently, a RESTful architecture is one that is maintainable, extendable, and distributed.

Before all 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 need to first qualify what it means for the web to be RESTful. On the 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 connection, and unique hyperlinks to resources, where resources are all of the documents available on every website and the representations of these documents are 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 because servers track 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.

Note

The REST architectural style is not specific to any protocol. However, as HTTP is the primary transfer protocol for the web today, REST over HTTP is the most common implementation. In this book, when we talk about REST, we refer to REST over HTTP unless otherwise stated.

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, which 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.

Introducing HTTP

Hypertext Transfer Protocol (HTTP) is the foundation of data communication for WWW. This protocol defines how messages are formatted, transmitted, and processed over the Internet. Let's have a quick recap of HTTP in this section.

HTTP versions

HTTP has been consistently evolving over time. So far, there are 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 in 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 the revision of HTTP/1.0. This version is in common use today.

HTTP/2 (originally named HTTP 2.0) is the next planned version. It is mainly focused on how the data is framed and transported between the client and the server.

Tip

To learn more about HTTP, you can refer to the Wikipedia resources that you may find at http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol.

Understanding the HTTP request-response model

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 the server:

Here is a detailed explanation of the sequence of actions shown in the preceding diagram.

The user enters the following URL in the browser, http://www.example.com/index.html, 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 protocol version, followed by a message containing request modifiers, client information, and possible body content. The sample request looks like the following:

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 the 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 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 for 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 the 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 the resource, such as content type, cache expiry, and refresh rate.

The last part of the response is the response body. Upon the 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).

Uniform resource identifier

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 general, all URLs are URIs. To learn more about URIs, visit http://en.wikipedia.org/wiki/Uniform_resource_identifier.

Understanding the HTTP request methods

In the previous section, 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 at 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 at 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 that identifies the content type for the message body.

Representing content types using HTTP header fields

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 an optional semicolon delimited attribute-value pairs (known as parameters).

The Internet media types are broadly classified in to the following categories on the basis of the primary (or initial) Content-Type header:

text: This type indicates that the content is 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 the 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 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.

Tip

JSON is a lightweight data-interchange format. If you are not familiar with the JSON format, not to worry now; we will cover this topic in Chapter 2, Java APIs for JSON Processing.

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.

Note

We are not covering all the possible subtypes for each category of media type here. To refer to the complete list, visit the website ofInternet Assigned Numbers Authority (IANA) at http://www.iana.org/assignments/media-types/media-types.xhtml.

The next topic, a simple but important one, is on HTTP status codes.

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 the 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 the 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 frame 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 the request cannot be fulfilled.

Note

To refer to the complete list of HTTP status codes maintained by IANA, visit http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml.

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 get ready for an exciting journey.

The evolution of RESTful web services

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 very 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 asWeb 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 specialized 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 for the creation of products that did not exist some years ago.Web services are being used within the 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 the Service-Oriented Architecture (SOA). The 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 a web service has evolved into a powerful and effective channel of communication between a client and a 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 about RESTful web services by now, let's see the formal definition before proceeding further.

Note

What is a RESTful web service?

Web services that adhere to the REST architectural constraints are characterized as RESTful web services. Refer to the section, The REST architectural style, at the beginning of this chapter if you need a quick brush up on the architectural constraints for a RESTful system.

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 under the larger umbrella of the SOA.

With this larger view of the SOA, we begin to see how REST has the potential to impact the new computing models being developed.

Note

The RESTful web API or REST API is an API implemented using HTTP and the REST architectural constraints. Technically speaking, this is just another term for a RESTful web service. In this book, we will use these terms interchangeably.

The core architectural elements of a RESTful system

Having learned the basics of a RESTful system, you are now ready to meet the more exciting concepts of REST. In this section, we will learn the core architectural elements that make a system RESTful.

A uniform interface is fundamental to the architecture of any RESTful system. In plain words, this term refers to a generic interface to manage all interactions between a client and a server in a unified way. All resources (or business data) involved in the client-server interactions are dealt with by a fixed set of operations. The following are core elements that form a uniform interface for a RESTful system:

Resources and their identifiersRepresentations of resourcesGeneric interaction semantics for the REST resourcesSelf-descriptive messages