Visit https://ebookultra.com todownload the full version and
explore more ebooks
RESTful Java With JAX RS 1st Edition Bill Burke
_____ Click the link below to download _____
https://ebookultra.com/download/restful-java-with-jax-
rs-1st-edition-bill-burke/
Explore and download more ebooks at ebookultra.com
2.
Here are somesuggested products you might be interested in.
Click the link to download
Restful Java with Jax RS 1st Edition Burke Bill
https://ebookultra.com/download/restful-java-with-jax-rs-1st-edition-
burke-bill/
RESTful Java Web Services Second Edition Jobinesh
Purushothaman
https://ebookultra.com/download/restful-java-web-services-second-
edition-jobinesh-purushothaman/
Cocoon 2 Programming Web Publishing with XML and Java 1st
Edition Bill Brogden
https://ebookultra.com/download/cocoon-2-programming-web-publishing-
with-xml-and-java-1st-edition-bill-brogden/
Pro ADO NET Data Services Working with RESTful Data 1st
Edition John Shaw
https://ebookultra.com/download/pro-ado-net-data-services-working-
with-restful-data-1st-edition-john-shaw/
3.
RESTful NET 1stEdition Jon Flanders
https://ebookultra.com/download/restful-net-1st-edition-jon-flanders/
RESTful Web APIs 1st Edition Leonard Richardson
https://ebookultra.com/download/restful-web-apis-1st-edition-leonard-
richardson/
Practical Database Programming with Java 1st Edition Ying
Bai
https://ebookultra.com/download/practical-database-programming-with-
java-1st-edition-ying-bai/
Big Java Compatible with Java 5 6 and 7 4th Edition Cay S.
Horstmann
https://ebookultra.com/download/big-java-compatible-with-
java-5-6-and-7-4th-edition-cay-s-horstmann/
Expert Oracle and Java Security Programming Secure Oracle
Database Applications with Java 1st Edition David Coffin
https://ebookultra.com/download/expert-oracle-and-java-security-
programming-secure-oracle-database-applications-with-java-1st-edition-
david-coffin/
5.
RESTful Java WithJAX RS 1st Edition Bill Burke Digital
Instant Download
Author(s): Bill Burke
ISBN(s): 9780596157074, 059615707X
Edition: 1
File Details: PDF, 2.53 MB
Year: 2009
Language: english
Leveraging Content Negotiation115
Creating New Media Types 115
Flexible Schemas 116
Wrapping Up 117
9. HATEOAS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
HATEOAS and Web Services 120
Atom Links 120
Advantages of Using HATEOAS with Web Services 121
Link Headers Versus Atom Links 124
HATEOAS and JAX-RS 125
Building URIs with UriBuilder 125
Relative URIs with UriInfo 127
Wrapping Up 130
10. Scaling JAX-RS Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Caching 131
HTTP Caching 132
Expires Header 132
Cache-Control 133
Revalidation and Conditional GETs 135
Concurrency 138
JAX-RS and Conditional Updates 139
Wrapping Up 140
11. Deployment and Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Deployment 141
The Application Class 142
Deployment Within a JAX-RS-Unaware Container 143
Deployment Within a JAX-RS-Aware Container 144
Deployment Within Java EE 6 144
Configuration 145
Older Java EE Containers 145
Within Java EE 6 Containers 149
EJB Integration 149
Spring Integration 152
Wrapping Up 154
12. Securing JAX-RS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Authentication 156
Basic Authentication 156
Digest Authentication 157
Client Certificate Authentication 158
viii | Table of Contents
16.
Authorization 159
Authentication andAuthorization in JAX-RS 159
Enforcing Encryption 161
Authorization Annotations 162
Programmatic Security 163
Wrapping Up 164
13. RESTful Java Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
java.net.URL 165
Caching 167
Authentication 167
Advantages and Disadvantages 169
Apache HttpClient 170
Authentication 172
Advantages and Disadvantages 173
RESTEasy Client Framework 174
Authentication 176
Advantages and Disadvantages 177
RESTEasy Client Proxies 177
Advantages and Disadvantages 178
Wrapping Up 178
14. JAX-RS Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Jersey 179
Embeddable Jersey 179
Client API 180
WADL 181
Data Formats 182
Model, View, and Controller 183
Component Integration 184
Apache CXF 185
Aggregating Request Parameters into Beans 185
Converting Request Parameters into Custom Types 186
Static Resolution of Subresources 187
Client API 187
Supporting Services Without JAX-RS Annotations 187
Intercepting Requests and Responses 187
Promoting XSLT and XPath As First-Class Citizens 188
Support for Suspended Invocations 188
Support for Multipart Formats 188
Integration with Distributed OSGi RI 188
Support for WADL 188
Component Integration 189
Table of Contents | ix
17.
JBoss RESTEasy 189
EmbeddedContainer 189
Asynchronous HTTP 190
Interceptor Framework 191
Client “Browser” Cache 192
Server-Side Caching 192
GZIP Compression 192
Data Formats 192
Component Integration 194
Wrapping Up 194
Part II. JAX-RS Workbook
15. Workbook Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Installing RESTEasy and the Examples 197
Example Requirements and Structure 199
Code Directory Structure 199
Environment Setup 199
16. Examples for Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Build and Run the Example Program 201
Deconstructing pom.xml 202
Running the Build 206
Examining the Source Code 207
17. Examples for Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Example ex04_1: HTTP Method Extension 211
Build and Run the Example Program 212
The Server Code 212
The Client Code 213
Example ex04_2: @Path with Expressions 214
Build and Run the Example Program 214
The Server Code 214
The Client Code 215
Example ex04_3: Subresource Locators 216
Build and Run the Example Program 216
The Server Code 216
The Client Code 217
18. Examples for Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Example ex05_1: Injecting URI Information 219
The Server Code 219
x | Table of Contents
18.
The Client Code222
Build and Run the Example Program 222
Example ex05_2: Forms and Cookies 222
The Server Code 223
Server Configuration 224
Build and Run the Example Program 225
19. Examples for Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Example ex06_1: Using JAXB 227
The Client Code 229
Changes to pom.xml 229
Build and Run the Example Program 230
Example ex06_2: Creating a Content Handler 230
The Content Handler Code 230
The Resource Class 232
The Application Class 232
The Client Code 233
Build and Run the Example Program 234
20. Examples for Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Example ex07_1: ExceptionMapper 235
The Client Code 237
Build and Run the Example Program 238
21. Examples for Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Example ex08_1: Conneg with JAX-RS 239
The Client Code 240
Build and Run the Example Program 241
Example ex08_2: Conneg via URL Patterns 241
The Server Code 241
Build and Run the Example Program 242
22. Examples for Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Example ex09_1: Atom Links 243
The Server Code 244
The Client Code 248
Build and Run the Example Program 248
Example ex09_2: Link Headers 248
The Server Code 249
The Client Code 254
Build and Run the Example Program 257
Table of Contents | xi
19.
23. Examples forChapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Example ex10_1: Caching and Concurrent Updates 259
The Server Code 259
The Client Code 262
Build and Run the Example Program 263
24. Examples for Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Example ex11_1: EJB and JAX-RS 265
Project Structure 265
The EJB Project 266
The WAR Project 272
The EAR Project 274
Build and Run the Example Program 277
Example ex11_2: Spring and JAX-RS 278
Build and Run the Example Program 280
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
xii | Table of Contents
20.
Foreword
REST is anarchitectural style that defines a set of constraints that, when applied to the
architecture of a distributed system, induce desirable properties like loose coupling and
horizontal scalability. RESTful web services are the result of applying these constraints
to services that utilize web standards such as URIs, HTTP, XML, and JSON. Such
services become part of the fabric of the Web and can take advantage of years of web
engineering to satisfy their clients’ needs.
The Java API for RESTful web services (JAX-RS) is a new API that aims to make de-
velopment of RESTful web services in Java simple and intuitive. The initial impetus for
the API came from the observation that existing Java Web APIs were generally either:
• Very low-level, leaving the developer to do a lot of repetitive and error-prone work
such as URI parsing and content negotiation, or
• Rather high-level and proscriptive, making it easy to build services that conform
to a particular pattern but lacking the necessary flexibility to tackle more general
problems.
A Java Specification Request (JSR 311) was filed with the Java Community Process
(JCP) in January 2007 and approved unanimously in February. The expert group began
work in April 2007 with the charter to design an API that was flexible, easy to use, and
that encouraged developers to follow the REST style. The resulting API, finalized in
October 2008, has already seen a remarkable level of adoption, and we were fortunate
to have multiple implementations of the API underway throughout the development
of JAX-RS. The combination of implementation experience and feedback from users
of those implementations was invaluable and allowed us to refine the specification,
clarify edge-cases, and reduce API friction.
JAX-RS is one of the latest generations of Java APIs that make use of Java annotations
to reduce the need for standard base classes, implementing required interfaces, and
out-of-band configuration files. Annotations are used to route client requests to match-
ing Java class methods and declaratively map request data to the parameters of those
methods. Annotations are also used to provide static metadata to create responses.
JAX-RS also provides more traditional classes and interfaces for dynamic access to
request data and for customizing responses.
xiii
21.
Bill Burke ledthe development of one of the JAX-RS implementations mentioned earlier
(RESTEasy) and was an active and attentive member of the expert group. His contri-
butions to expert group discussions are too numerous to list, but a few of the areas
where his input was instrumental include rules for annotation inheritance, use of reg-
ular expressions for matching request URIs, annotation-driven support for cookies and
form data, and support for streamed output.
This book, RESTful Java with JAX-RS, provides an in-depth tutorial on JAX-RS and
shows how to get the most from this new API while adhering to the REST architectural
style. I hope you enjoy the book and working with JAX-RS.
—Marc Hadley
JAX-RS Specification Lead
Sun Microsystems, Inc.
Burlington, MA
xiv | Foreword
22.
Preface
Author’s Note
The bulkof my career has been spent working with and implementing distributed
middleware. In the mid-’90s I worked for the parent company of Open Environment
Corporation, working on DCE tools. Later on, I worked for Iona, developing their next-
generation CORBA ORB. Currently, I work for the JBoss division of Red Hat, which
is entrenched in Java middleware, specifically Java EE. So, you could say that I have a
pretty rich perspective when it comes to middleware.
I must tell you that I was originally very skeptical of REST as a way of writing SOA
applications. It seemed way too simple and shortsighted, so I sort of blew it off for a
while. One day though, back in mid-2007, I ran into my old Iona boss and mentor Steve
Vinoski while grabbing a sandwich at D’Angelo in Westford, MA near Red Hat’s offi-
ces. We ended up sitting down, having lunch, and talking for hours. The first shocker
for me was that Steve had left Iona to go work for a start-up. The second was when he
said, “Bill, I’ve abandoned CORBA and WS-* for REST.” For those of you who don’t
know Steve, he contributed heavily to the CORBA specification, wrote a book on the
subject (which is basically the CORBA bible), and is a giant in the distributed com-
puting field, writing regularly for C++ Report and IEEE. How could the guy I looked
up to and was responsible for my foundation in distributed computing abandon
CORBA, WS-*, and the distributed framework landscape he was instrumental in cre-
ating? I felt a little betrayed and very unnerved (OK, maybe I’m exaggerating a little…).
We ended up arguing for a few hours on which was better, WS-*/CORBA or REST.
This conversation spilled into many other lengthy email messages, with me trying to
promote WS-* and him defending REST. The funniest thing to me was that as I re-
searched REST more and more I found that my arguments with Steve were just another
endless replay of debates that had been raging across the blogosphere for years. They
are still raging to this day.
Anyway, it took months for me to change my mind and embrace REST. You would
figure that my distributed computing background was an asset, but it was not. DCE,
CORBA, WS-*, and Java EE were all baggage. All were an invisible barrier for me to
accept REST as a viable (and better) alternative for writing SOA applications. I think
xv
23.
that’s what Iliked most about REST. It required me to rethink and reformulate the
foundation of my distributed computing knowledge. Hopefully your journey isn’t as
difficult as mine and you will be a little less stubborn and more open-minded than I was.
Who Should Read This Book
This book teaches you how to design and develop distributed web services in Java using
RESTful architectural principles on top of the HTTP protocol. It is mostly a compre-
hensive reference guide on the JAX-RS specification, which is a JCP standardized an-
notation framework for writing RESTful web services in Java.
While this book does go into many of the fundamentals of REST, it does not cover
them all and focuses more on implementation rather than theory. You can satisfy your
craving for more RESTful theory be obtaining RESTful Web Services by Leonard Ri-
chardson and Sam Ruby (O’Reilly). If you are familiar writing Java EE applications,
you will be very comfortable reading this book. If you are not, you will be at a disad-
vantage, but some experience with web application development, HTTP, and XML is
a huge plus. Before reading this book, you should also be fairly fluent in the Java lan-
guage and specifically know how to use and apply Java annotations. If you are unfa-
miliar with the Java language, I recommend Learning Java by Patrick Niemeyer and
Jonathan Knudsen (O’Reilly).
How This Book Is Organized
This book is organized into two parts: the technical manuscript, followed by the
JAX-RS workbook. The technical manuscript explains what REST and JAX-RS are,
how they work, and when to use them. The JAX-RS workbook provides step-by-step
instructions for installing, configuring, and running the JAX-RS examples from the
manuscript with the JBoss RESTEasy framework, an implementation of JAX-RS.
Part I, REST and the JAX-RS Standard
Part I starts off with a brief introduction to REST and HTTP. It then guides you through
the basics of the JAX-RS specification, and then in later chapters shows you how you
can apply JAX-RS to build RESTful web services:
Chapter 1, Introduction to REST
This chapter gives you a brief introduction to REST and HTTP.
Chapter 2, Designing RESTful Services
This chapter walks you through the design of a distributed RESTful interface for
an e-commerce order entry system.
xvi | Preface
24.
Chapter 3, YourFirst JAX-RS Service
This chapter walks you through the development of a RESTful web service written
in Java as a JAX-RS service.
Chapter 4, HTTP Method and URI Matching
This chapter defines how HTTP requests are dispatched in JAX-RS and how you
can use the @Path annotation and subresources.
Chapter 5, JAX-RS Injection
This chapter walks you through various annotations that allow you to extract in-
formation from an HTTP request (URI parameters, headers, query parameters,
form data, cookies, matrix parameters, encoding, and defining default values).
Chapter 6, JAX-RS Content Handlers
This chapter explains how to marshal HTTP message bodies to and from Java
objects using built-in handlers or writing your own custom marshallers.
Chapter 7, Response Codes, Complex Responses, and Exception Handling
This chapter walks through the JAX-RS Response object and how you use it to
return complex responses to your client (ResponseBuilder). It also explains how
exception and error handling work in JAX-RS.
Chapter 8, HTTP Content Negotiation
This chapter explains how HTTP content negotiation works, its relationship to
JAX-RS, and how you can leverage this within RESTful architectures.
Chapter 9, HATEOAS
This chapter dives into Hypermedia As The Engine Of Application State and how
it relates to JAX-RS (UriInfo and UriBuilder).
Chapter 10, Scaling JAX-RS Applications
This chapter explains how you can increase the performance of your services by
leveraging HTTP caching protocols. It also shows you how to manage concurrency
conflicts in high-volume sites.
Chapter 11, Deployment and Integration
This chapter explains how you can deploy and integrate your JAX-RS services
within Java Enterprise Edition, servlet containers, EJB, Spring, and JPA.
Chapter 12, Securing JAX-RS
This chapter walks you through the most popular mechanisms to perform authen-
tication on the Web. It then shows you how to implement secure applications with
JAX-RS.
Chapter 13, RESTful Java Clients
This chapter shows you how to write RESTful clients in Java using various libraries
and frameworks as an example (java.net.URL, Apache HTTP Client, and
RESTEasy).
Chapter 14, JAX-RS Implementations
This chapter provides a short review of available JAX-RS implementations.
Preface | xvii
25.
Part II, JAX-RSWorkbook
The JAX-RS workbook shows you how to execute examples from chapters in the book
that include at least one significant example. You’ll want to read the introduction to
the workbook to set up RESTEasy and configure it for the examples. After that, just go
to the workbook chapter that matches the chapter you’re reading. For example, if you
are reading Chapter 3 on writing your first JAX-RS service, use Chapter 16, Examples
for Chapter 3, of the workbook to develop and run the examples with RESTEasy.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, filenames, and file extensions
Constant width
Indicatesvariables,methodnames,andothercodeelements,aswellasthecontents
of files
Constant width bold
Highlights new code in an example
Constant width italic
Shows text that should be replaced with user-supplied values
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
xviii | Preface
26.
We appreciate, butdo not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “RESTful Java with JAX-RS by Bill Burke.
Copyright 2010 William J. Burke, Jr., 978-0-596-15804-0.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at permissions@oreilly.com.
We’d Like to Hear from You
Every example in this book has been tested, but occasionally you may encounter prob-
lems. Mistakes and oversights can occur and we will gratefully receive details of any
that you find, as well as any suggestions you would like to make for future editions.
You can contact the authors and editors at:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://www.oreilly.com/catalog/9780596158040
To comment or ask technical questions about this book, send email to the following,
quoting the book’s ISBN number (9780596158040):
bookquestions@oreilly.com
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:
http://www.oreilly.com
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
search over 7,500 technology and creative reference books and videos to
find the answers you need quickly.
Withasubscription,youcanreadanypageandwatchanyvideofromourlibraryonline.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. Copy and paste code samples, organize your favorites, down-
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
Preface | xix
27.
O’Reilly Media hasuploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub-
lishers, sign up for free at http://my.safaribooksonline.com.
Acknowledgments
First, I’d like to thank Steve Vinoski for introducing me to REST. Without our con-
versations and arguments, I would never have written this book. Next, I’d like to thank
Marc Hadley and Paul Sandoz, the leads of the JAX-RS specification. They ran an ex-
cellent expert group and also wrote the Foreword and contributed to Chapter 14. I’d
like to thank Sergey Beryozkin for contributing the Apache CXF section. It is cool when
competitors can be on good terms with each other. Jeff Mesnil and Michael Musgrove
were instrumental in reviewing this book and provided a lot of great feedback. Subbu
Allaraju helped tremendously in making sure my understanding and explanation of
RESTful theory was correct. By the way, I strongly suggest you check out his blog at
www.subbu.org. Heiko Braun helped on the first few chapters as far as reviewing goes.
I’d also like to thank the contributors to the RESTEasy project, specifically Solomon
Duskis, Justin Edelson, Ryan McDonough, Attila Kiraly, and Michael Brackx. Without
them, RESTEasy wouldn’t be where it is. Finally, I’d like to thank Mike Loukides, who
has been my editor throughout my O’Reilly career.
xx | Preface
CHAPTER 1
Introduction toREST
For those of us with computers, the World Wide Web is an intricate part of our lives.
We use it to read the newspaper in the morning, pay our bills, perform stock trades,
and buy goods and services, all through the browser, all over the network. “Googling”
has become a part of our daily vocabulary as we use search engines to do research for
school, find what time a movie is playing, or to just search for information on old
friends. Door-to-door encyclopedia salesmen have gone the way of the dinosaur as
Wikipedia has become the summarized source of human knowledge. People even so-
cialize over the network using sites like Facebook and MySpace. Professional social
networks are sprouting up in all industries as doctors, lawyers and all sorts of profes-
sionals use them to collaborate. As programmers, the Web is an intricate part of our
daily jobs. We search for and download open source libraries to help us develop ap-
plications and frameworks for our companies. We build web-enabled applications so
that anybody on the Internet or intranet can use a browser to interact with our systems.
Really, most of us take the Web for granted. Have you, as a programmer, sat down and
tried to understand why the Web has been so successful? How has it grown from a
simple network of researchers and academics to an interconnected worldwide com-
munity? What properties of the Web make it so viral?
One man, Roy Fielding, did ask these questions in his doctoral thesis, “Architectural
Styles and the Design of Network-based Software Architectures.”* In it, he identifies
specific architectural principles that answer the following questions:
• Why is the Web so prevalent and ubiquitous?
• What makes the Web scale?
• How can I apply the architecture of the Web to my own applications?
The set of these architectural principles is called REpresentational State Transfer
(REST) and are defined as:
* www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
3
31.
Addressable resources
The keyabstraction of information and data in REST is a resource, and each re-
source must be addressable via a URI (Uniform Resource Identifier).
A uniform, constrained interface
Use a small set of well-defined methods to manipulate your resources.
Representation-oriented
You interact with services using representations of that service. A resource refer-
enced by one URI can have different formats. Different platforms need different
formats. For example, browsers need HTML, JavaScript needs JSON (JavaScript
Object Notation), and a Java application may need XML.
Communicate statelessly
Stateless applications are easier to scale.
Hypermedia As The Engine Of Application State (HATEOAS)
Let your data formats drive state transitions in your applications.
For a PhD thesis, Roy’s paper is actually very readable and, thankfully, not very long.
It, along with Leonard Richardson and Sam Ruby’s book RESTful Web Services
(O’Reilly), is an excellent reference for understanding REST. I will give a much briefer
introduction to REST and the Internet protocol it uses (HTTP) within this chapter.
REST and the Rebirth of HTTP
REST isn’t protocol-specific, but when people talk about REST, they usually mean
REST over HTTP. Learning about REST was as much of a rediscovery and reappreci-
ation of the HTTP protocol for me as learning a new style of distributed application
development. Browser-based web applications see only a tiny fraction of the features
of HTTP. Non-RESTful technologies like SOAP and WS-* use HTTP strictly as a trans-
port protocol and thus use a very small subset of its capabilities. Many would say that
SOAP and WS-* use HTTP solely to tunnel through firewalls. HTTP is actually a very
rich application protocol that provides a multitude of interesting and useful capabilities
for application developers. You will need a good understanding of HTTP in order to
write RESTful web services.
HTTP is a synchronous request/response-based application network protocol used for
distributed, collaborative, document-based systems. It is the primary protocol used on
the Web, in particular, by browsers such as Firefox, MS Internet Explorer, Safari, and
Netscape. The protocol is very simple: the client sends a request message made up of
the HTTP method being invoked, the location of the resource you are interested in
invoking, a variable set of headers, and an optional message body that can basically be
anything you want, including HTML, plain text, XML, JSON, even binary data. Here’s
an example:
GET /resteasy/index.html HTTP/1.1
Host: jboss.org
4 | Chapter 1: Introduction to REST
32.
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language:en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Your browser would send this request if you wanted to look at http://jboss.org/resteasy/
index.html. GET is the method we are invoking on the server. /resteasy/index.html is
the object we are interested in. HTTP/1.1 is the version of the protocol. Host, User-
Agent, Accept, Accept-Language, and Accept-Encoding are all message headers. There is
no request body, as we are querying information from the server.
The response message from the server is very similar. It contains the version of HTTP
we are using, a response code, a short message that explains the response code, a var-
iable set of optional headers, and an optional message body. Here’s the message the
server might respond with using the previous GET query:
HTTP/1.1 200 OK
X-Powered-By: Servlet 2.4; JBoss-4.2.2.GA
Content-Type: text/html
<head>
<title>JBoss RESTEasy Project</title>
</head>
<body>
<h1>JBoss RESTEasy</h1>
<p>JBoss RESTEasy is an open source implementation of the JAX-RS specification...
The response code of this message is 200, and the status message is “OK.” This code
means that the request was processed successfully and that the client is receiving the
information it requested. HTTP has a large set of response codes. They can be infor-
mational codes like 200, “OK,” or error codes like 500, “Internal Server Error.” Visit
www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a more complete and verbose
listing of these codes.
This response message also has a message body that is a chunk of HTML. We know it
is HTML by the Content-Type header.
RESTful Architectural Principles
Roy Fielding’s PhD thesis describing REST was really an explanation of why the human
readable Web had become so pervasive in the past 18 years. As time went on though,
programmers started to realize that they could use the concepts of REST to build dis-
tributed services and model service-oriented architectures (SOAs).
The idea of SOA is that application developers design their systems as a set of reusable,
decoupled, distributed services. Since these services are published on the network,
conceptually, it should be easier to compose larger and more complex systems. SOA
has been around for a long time. Developers have used technologies like DCE, CORBA,
RESTful Architectural Principles | 5
33.
and Java RMIto build them in the past. Nowadays, though, when you think of SOA,
you think of SOAP-based web services.
While REST has many similarities to the more traditional ways of writing SOA appli-
cations, it is very different in many important ways. You would think that a background
in distributed computing would be an asset to understanding this new way of creating
web services, but unfortunately this is not always the case. The reason is that some of
the concepts of REST are hard to swallow, especially if you have written successful
SOAP or CORBA applications. If your career has a foundation in one of these older
technologies, there’s a bit of emotional baggage you will have to overcome. For me, it
took a few months of reading, researching, and intense arguing with REST evangelists
(aka RESTafarians). For you, it may be easier. Others will never pick REST over some-
thing like SOAP and WS-*.
Let’s examine each of the architectural principles of REST in detail and why they are
important when writing a web service.
Addressability
Addressability is the idea that every object and resource in your system is reachable
through a unique identifier. This seems like a no-brainer, but if you think about it,
standardized object identity isn’t available in many environments. If you have tried to
implement a portable J2EE application, you probably know what I mean. In J2EE,
distributed and even local references to services are not standardized, which makes
portability really difficult. This isn’t such a big deal for one application, but with the
new popularity of SOA, we’re heading to a world where disparate applications must
integrate and interact. Not having something as simple as standardized service ad-
dressability adds a whole complex dimension to integration efforts.
In the REST world, addressability is managed through the use of URIs. When you make
a request for information in your browser, you are typing in a URI. Each HTTP request
must contain the URI of the object you are requesting information from or posting
information to. The format of a URI is standardized as follows:
scheme://host:port/path?queryString#fragment
The scheme is the protocol you are using to communicate with. For RESTful web serv-
ices, it is usually http or https. The host is a DNS name or IP address. It is followed by
an optional port, which is numeric. The host and port represent the location of your
resource on the network. Following host and port is a path expression. This path ex-
pression is a set of text segments delimited by the “/” character. Think of the path
expression as a directory list of a file on your machine. Following the path expression
is an optional query string. The “?” character separates the path from the query string.
The query string is a list of parameters represented as name/value pairs. Each pair is
delimited with the “&” character. Here’s an example query string within a URI:
http://example.com/customers?lastName=Burke&zipcode=02115
6 | Chapter 1: Introduction to REST
34.
A specific parametername can be repeated in the query string. In this case, there are
multiple values for the same parameter.
The last part of the URI is the fragment. It is delimited by a “#” character. The fragment
is usually used to point to a certain place in the document you are querying.
Not all characters are allowed within a URI string. Some characters must be encoded
using the following rules. The characters a–z, A–Z, 0–9, ., -, *, and _ remain the same.
The space character is converted to +. The other characters are first converted into a
sequence of bytes using specific encoding scheme. Next, a two-digit hexadecimal num-
ber prefixed by % represents each byte.
Using a unique URI to identify each of your services makes each of your resources
linkable. Service references can be embedded in documents or even email messages.
For instance, consider the situation where somebody calls your company’s help desk
with a problem related to your SOA application. A link could represent the exact prob-
lem the user is having. Customer support can email the link to a developer who can fix
the problem. The developer can reproduce the problem by clicking on the link.
Furthermore, the data that services publish can also be composed into larger data
streams fairly easily:
<order id="111">
<customer>http://customers.myintranet.com/customers/32133</customer>
<order-entries>
<order-entry>
<quantity>5</quantity>
<product>http://products.myintranet.com/products/111</product>
...
In this example, an XML document describes an e-commerce order entry. We can
reference data provided by different divisions in a company. From this reference, we
can not only obtain information about the linked customer and products that were
bought, but we also have the identifier of the service this data comes from. We know
exactly where we can further interact and manipulate this data if we so desired.
The Uniform, Constrained Interface
The REST principle of a constrained interface is perhaps the hardest pill for an expe-
rienced CORBA or SOAP developer to swallow. The idea behind it is that you stick to
the finite set of operations of the application protocol you’re distributing your services
upon. This means that you don’t have an “action” parameter in your URI and use only
the methods of HTTP for your web services. HTTP has a small, fixed set of operational
methods. Each method has a specific purpose and meaning. Let’s review them:
RESTful Architectural Principles | 7
35.
GET
GET is aread-only operation. It is used to query the server for specific information.
It is both an idempotent and safe operation. Idempotent means that no matter how
many times you apply the operation, the result is always the same. The act of
reading an HTML document shouldn’t change the document. Safe means that
invoking a GET does not change the state of the server at all. This means that, other
than request load, the operation will not affect the server.
PUT
PUT requests that the server store the message body sent with the request under
the location provided in the HTTP message. It is usually modeled as an insert or
update. It is also idempotent. When using PUT, the client knows the identity of
the resource it is creating or updating. It is idempotent because sending the same
PUT message more than once has no effect on the underlying service. An analogy
is an MS Word document that you are editing. No matter how many times you
click the Save button, the file that stores your document will logically be the same
document.
DELETE
DELETE is used to remove resources. It is idempotent as well.
POST
POST is the only nonidempotent and unsafe operation of HTTP. Each POST
method is allowed to modify the service in a unique way. You may or may not send
information with the request. You may or may not receive information from the
response.
HEAD
HEAD is exactly like GET except that instead of returning a response body, it
returns only a response code and any headers associated with the request.
OPTIONS
OPTIONS is used to request information about the communication options of the
resource you are interested in. It allows the client to determine the capabilities of
a server and a resource without triggering any resource action or retrieval.
There are other HTTP methods (like TRACE and CONNECT), but they are unimpor-
tant when designing and implementing RESTful web services.
You may be scratching your head and thinking, “How is it possible to write a distributed
service with only four to six methods?” Well…SQL only has four operations: SELECT,
INSERT, UPDATE, and DELETE. JMS and other Message Oriented Middleware
(MOM) really only have two logical operations: send and receive. How powerful are
these tools? For both SQL and JMS, the complexity of the interaction is confined purely
to the data model. The addressability and operations are well defined and finite and
the hard stuff is delegated to the data model (in the case of SQL) or the message body
(in the case of JMS).
8 | Chapter 1: Introduction to REST
36.
Why Is theUniform Interface Important?
Constraining the interface for your web services has many more advantages than dis-
advantages. Let’s look at a few:
Familiarity
If you have a URI that points to a service, you know exactly which methods are
available on that resource. You don’t need an IDL-like file describing which meth-
ods are available. You don’t need stubs. All you need is an HTTP client library. If
you have a document that is composed of links to data provided by many different
services, you already know which method to call to pull in data from those links.
Interoperability
HTTP is a very ubiquitous protocol. Most programming languages have an HTTP
client library available to them. So, if your web service is exposed over HTTP, there
is a very high probability that people who want to use your service will be able to
do so without any additional requirements beyond being able to exchange the data
formats the service is expecting. With CORBA or WS-*, you have to install vendor-
specific client libraries as well as loads and loads of IDL or WSDL-generated stub
code. How many of you have had a problem getting CORBA or WS-* vendors to
interoperate? It has traditionally been very problematic. The WS-* set of specifi-
cations has also been a moving target over the years. So with WS-* and CORBA,
you not only have to worry about vendor interoperability, you also have to make
sure that your client and server are using the same specification version of the
protocol. With REST over HTTP, you don’t have to worry about either of these
things and can just focus on understanding the data format of the service. I like to
think that you are focusing on what is really important: application interoperabil-
ity, rather than vendor interoperability.
Scalability
Because REST constrains you to a well-defined set of methods, you have predict-
able behavior that can have incredible performance benefits. GET is the strongest
example. When surfing the Internet, have you noticed that the second time you
browse to a specific page it comes up faster? This is because your browser caches
already visited pages and images. HTTP has a fairly rich and configurable protocol
for defining caching semantics. Because GET is a read method that is both idem-
potent and safe, browsers and HTTP proxies can cache responses to servers, and
this can save a huge amount of network traffic and hits to your website. Add HTTP
caching semantics to your web services and you have an incredibly rich way of
defining caching policies for your services. We will discuss HTTP caching in detail
within Chapter 10.
It doesn’t end with caching, though. Consider both PUT and DELETE. Because
they are idempotent, neither the client nor the server has to worry about handling
duplicate message delivery. This saves a lot of bookkeeping and complex code.
RESTful Architectural Principles | 9
37.
Representation-Oriented
The third architecturalprinciple of REST is that your services should be representation-
oriented. Each service is addressable through a specific URI and representations are
exchanged between the client and service. With a GET operation, you are receiving a
representation of the current state of that resource. A PUT or POST passes a represen-
tation of the resource to the server so that the underlying resource’s state can change.
In a RESTful system, the complexity of the client-server interaction is within the rep-
resentations being passed back and forth. These representations could be XML, JSON,
YAML, or really any format you can come up with.
With HTTP, the representation is the message body of your request or response. An
HTTP message body may be in any format the server and client want to exchange.
HTTP uses the Content-Type header to tell the client or server what data format it is
receiving. The Content-Type header value string is in the Multipurpose Internet Mail
Extension (MIME) format. The MIME format is very simple:
type/subtype;name=value;name=value...
type is the main format family and subtype is a category. Optionally, the MIME type
can have a set of name/value pair properties delimited by the “;” character. Some ex-
amples are:
text/plain
text/html
application/xml
text/html; charset=iso-8859-1
One of the more interesting features of HTTP that leverages MIME types is the capa-
bility of the client and server to negotiate the message formats being exchanged between
them. While not used very much by your browser, HTTP content negotiation is a very
powerful tool when writing web services. With the Accept header, a client can list its
preferred response formats. Ajax clients can ask for JSON, Java for XML, Ruby for
YAML. Another thing this is very useful for is versioning of services. The same service
can be available through the same URI with the same methods (GET, POST, etc.), and
all that changes is the MIME type. For example, the MIME type could be application/
vnd+xml for an old service while newer services could exchange application/vnd
+xml;version=1.1 MIME types. You can read more about all these concepts in Chap-
ter 8.
All in all, because REST and HTTP have a layered approach to addressability, method
choice, and data format, you have a much more decoupled protocol that allows your
service to interact with a wide variety of different clients in a consistent way.
Communicate Statelessly
The fourth RESTful principle I will discuss is the idea of statelessness. When I talk
about statelessness, though, I don’t mean that your applications can’t have state. In
10 | Chapter 1: Introduction to REST
38.
REST, stateless meansthat there is no client session data stored on the server. The
server only records and manages the state of the resources it exposes. If there needs to
be session-specific data, it should be held and maintained by the client and transferred
to the server with each request as needed. A service layer that does not have to maintain
client sessions is a lot easier to scale, as it has to do a lot fewer expensive replications
in a clustered environment. It’s a lot easier to scale up, because all you have to do is
add machines.
A world without server-maintained session data isn’t so hard to imagine if you look
back 12–15 years ago. Back then, many distributed applications had a fat GUI client
written in Visual Basic, Power Builder, or Visual C++ talking RPCs to a middle tier that
sat in front of a database. The server was stateless and just processed data. The fat client
held all session state. The problem with this architecture was an IT operations one. It
was very hard for operations to upgrade, patch, and maintain client GUIs in large en-
vironments. Web applications solved this problem because the applications could be
delivered from a central server and rendered by the browser. We started maintaining
client sessions on the server because of the limitations of the browser. Now, circa 2008,
with the growing popularity of Ajax, Flex, and Java FX, the browsers are sophisticated
enough to maintain their own session state like their fat-client counterparts in the
mid-’90s used to do. We can now go back to that stateless scalable middle tier that we
enjoyed in the past. It’s funny how things go full circle sometimes.
HATEOAS
The final principle of REST is the idea of using Hypermedia As The Engine Of Appli-
cation State (HATEOAS). Hypermedia is a document-centric approach with the added
support for embedding links to other services and information within that document
format. I did indirectly talk about HATEOAS in “Addressability” on page 6 when I
discussed the idea of using hyperlinks within the data format received from a service.
Oneoftheusesofhypermediaandhyperlinksiscomposingcomplexsetsofinformation
from disparate sources. The information could be within a company intranet or dis-
persed across the Internet. Hyperlinks allow us to reference and aggregate additional
data without bloating our responses. The e-commerce order in “Addressabil-
ity” on page 6 is an example of this:
<order id="111">
<customer>http://customers.myintranet.com/customers/32133</customer>
<order-entries>
<order-entry>
<quantity>5</quantity>
<product>http://products.myintranet.com/products/111</product>
...
In that example, links embedded within the document allowed us to bring in additional
information as needed. Aggregation isn’t the full concept of HATEOAS, though. The
more interesting part of HATEOAS is the “engine.”
RESTful Architectural Principles | 11
39.
The engine ofapplication state
If you’re on Amazon.com buying a book, you follow a series of links and fill out one
or two forms before your credit card is charged. You transition through the ordering
process by examining and interacting with the responses returned by each link you
follow and each form you submit. The server guides you through the order process by
embedding where you should go next within the HTML data it provides your browser.
This is very different from the way traditional distributed applications work. Older
applications usually have a list of precanned services they know exist and interact with
a central directory server to locate these services on the network. HATEOAS is a bit
different because with each request returned from a server it tells you what new inter-
actions you can do next, as well as where to go to transition the state of your
applications.
For example, let’s say we wanted to get a list of products available on a web store. We
do an HTTP GET on http://example.com/webstore/products and receive back:
<products>
<product id="123">
<name>headphones</name>
<price>$16.99</price>
</product>
<product id="124">
<name>USB Cable</name>
<price>$5.99</price>
</product>
...
</products>
This could be problematic if we had thousands of products to send back to our client.
We might overload it, or the client might wait forever for the response to finish down-
loading. We could instead list only the first five products and provide a link to get the
next set:
<products>
<link rel="next" href="http://example.com/webstore/products?startIndex=5"/>
<product id="123">
<name>headphones</name>
<price>$16.99</price>
</product>
...
</products>
Whenfirstqueryingforalistofproducts,clientsdon’thavetoknowthey’reonlygetting
back a list of five products. The data format can tell them that they didn’t get a full set
and to get the next set follow a specific link. Following the next link could get them
back a new document with additional links:
12 | Chapter 1: Introduction to REST
40.
<products>
<link rel="previous" href="http://example.com/webstore/products?startIndex=1"/>
<linkrel="next" href="http://example.com/webstore/products?startIndex=5"/>
<product id="128">
<name>stuff</name>
<price>$16.99</price>
</product>
...
</products>
In this case, there is the additional state transition of previous so that clients can browse
an earlier part of the product list. The next and previous links seem a bit trivial, but
imagine if we had other transition types like payment, inventory, or sales.
This sort of approach gives the server a lot of flexibility, as it can change where and
how state transitions happen on the fly. It could provide new and interesting oppor-
tunities to surf to. In Chapter 9, we’ll dive into HATEOAS again.
Wrapping Up
REST identifies the key architectural principles of why the Web is so prevalent and
scalable. The next step in the evolution of the Web is to apply these principles to the
semantic Web and the world of web services. REST offers a simple, interoperable, and
flexible way of writing web services that can be very different than the RPC mechanisms
like CORBA and WS-* that so many of us have had training in. In the next chapter we
will apply the concepts of REST by defining a distributed RESTful interface to an ex-
isting business object model.
Wrapping Up | 13
42.
CHAPTER 2
Designing RESTfulServices
In Chapter 1, I gave you a brief overview of REST and how it relates to HTTP. Although
it is good to obtain a solid foundation in theory, nothing can take the place of seeing
theory be put into practice. So, let’s define a RESTful interface for a simple order entry
system of a hypothetical e-commerce web store. Remote distributed clients will use this
web service to purchase goods, modify existing orders in the system, and view infor-
mation about customers and products.
In this chapter, we will start off by examining the simple underlying object model of
our service. After walking through the model, we will add a distributed interface to our
system using HTTP and the architectural guidelines of REST. To satisfy the addressa-
bility requirements of REST, we will first have to define a set of URIs that represent the
entry points into our system. Since RESTful systems are representation-oriented, we
will next define the data format that we will use to exchange information between our
services and clients. Finally, we will decide which HTTP methods are allowed by each
exposedURIandwhatthosemethodsdo.Wewillmakesuretoconformtotheuniform,
constrained interface of HTTP when doing this step.
The Object Model
The object model of our order entry system is very simple. Each order in the system
represents a single transaction or purchase and is associated with a particular customer.
Orders are made up of one or more line items. Line items represent the type and number
of each product purchased.
Based on this description of our system, we can deduce that the objects in our model
are Order, Customer, LineItem, and Product. Each data object in our model has a unique
identifier, which is the integer id property. Figure 2-1 shows a UML diagram of our
object model.
We will want to browse all orders as well as each individual order in our system. We
will also want to submit new orders and update existing ones. Finally, we will want to
have the ability to cancel and delete existing orders. The OrderEntryService object
15
43.
represents the operationswe want to perform on our Order, Customer, LineItem, and
Product objects.
Model the URIs
The first thing we are going to do to create our distributed interface is define and name
each of the distributed endpoints in our system. In a RESTful system, endpoints are
usually referred to as resources and are identified using a URI. URIs satisfy the ad-
dressability requirements of a RESTful service.
In our object model, we will be interacting with Orders, Customers, and Products. These
will be our main, top-level resources. We want to be able to obtain lists of each of these
top-level items and to interact with individual items. LineItems are aggregated within
Order objects so they will not be a top-level resource. We could expose them as a sub-
resource under one particular Order, but for now, let’s assume they are hidden by the
data format. Knowing this, here is a list of URIs that will be exposed in our system:
/orders
/orders/{id}
/products
/products/{id}
/customers
/customers/{id}
The /orders URI represents all the orders in our system. To access an individual order,
we will use a pattern: /orders/{id}. The {id} string is a pattern that represents an
individual order. It can be any integer value that corresponds to the id property of our
Order object. Products and Customers interactions will also be modeled in the same way.
You’ll notice that the nouns in our object model have been represented
as URIs. URIs shouldn’t be used as mini-RPC mechanisms and should
not identify operations. Instead, you should use a combination of HTTP
methods and the data format to model unique operations in your dis-
tributed RESTful system.
Figure 2-1. Order Entry System Object Model
16 | Chapter 2: Designing RESTful Services
44.
Defining the DataFormat
One of the most important things we have to do when defining a RESTful interface is
determine how our resources will be represented over the wire to our clients. XML is
perhaps one of the most popular formats on the Web and can be processed by most
modern languages, so let’s choose that. JSON is also a popular format, as it is more
condensed and JavaScript can interpret it directly (great for Ajax applications), but let’s
stick to XML for now.
Generally, you would define an XML schema for each representation you want to send
across the wire. An XML schema defines the grammar of a data format. It defines the
rules about how a document can be put together. I do find, though, that when ex-
plaining things within an article (or a book), providing examples rather than schema
makes things much easier to read and understand.
Read and Update Format
The XML format of our representations will look a tiny bit different from when we read
or update resources from the server than when we create resources on the server. Let’s
look at our read and update format first.
Common link element
Each format for Order, Customer, and Product will have a common XML element called
link:
<link rel="self" href="http://example.com/..."/>
The link* element tells any client that obtains an XML document describing one of the
objects in our e-commerce system where on the network the client can interact with
that particular resource. The rel attribute tells the client what relationship the link has
with the resource the URI points to (contained within the href attribute). The self
value just means it is pointing to itself. While not that interesting on its own, link
becomes very useful when we aggregate or compose information into one larger XML
document.
The details
So, with the common elements described, let’s start diving into the details by first
looking at our Customer representation format:
<customer id="771">
<link rel="self" href="http://example.com/customers/771"/>
<first-name>Bill</first-name>
<last-name>Burke</last-name>
* I actually borrowed the link element from the Atom format. Atom is a syndication format that is used to
aggregate and publish blogs and news feeds. You can find out more about Atom at www3.org/2005/Atom.
Defining the Data Format | 17
45.
<street>555 Beacon St.<street>
<city>Boston</city>
<state>MA</state>
<zip>02115</zip>
</customer>
Prettystraightforward. We just take the object model of Customer from Figure 2-1 and
expand its attributes as XML elements. Product looks much the same in terms of
simplicity:
<product id="543">
<link rel="self" href="http://example.com/products/543"/>
<name>iPhone</name>
<cost>$199.99</cost>
</product>
In a real system, we would, of course, have a lot more attributes for Customer and
Product, but let’s keep our example simple so that it’s easier to illustrate these RESTful
concepts:
<order id="133">
<link rel="self" href="http://example.com/orders/133"/>
<total>$199.02</total>
<date>December 22, 2008 06:56</date>
<customer id="117">
<link rel="self" href="http://example.com/customers/117"/>
<first-name>Bill</first-name>
<last-name>Burke</last-name>
<street>555 Beacon St.<street>
<city>Boston</city>
<state>MA</state>
<zip>02115</zip>
</customer>
<line-items>
<line-item id="144">
<product id="543">
<link rel="self" href="http://example.com/products/543"/>
<name>iPhone</name>
<cost>$199.99</cost>
</product>
<quantity>1</quantity>
</line-item>
</line-items>
</order>
The Order data format has the top-level elements of total and date that specify the total
cost of the order and the date the Order was made. Order is a great example of data
composition as it includes Customer and Product information. This is where the link
element becomes particularly useful. If the client is interested in interacting with a
Customer or Product that makes up the Order, it has the URI needed to interact with one
of these resources.
18 | Chapter 2: Designing RESTful Services
46.
Create Format
When weare creating new Orders, Customers, or Products, it doesn’t make a lot of sense
to include an id attribute and link element with our XML document. The server will
generate IDs when it inserts our new object into a database. We also don’t know the
URI of a new object, because the server also generates this. So, the XML for creating a
new Product would look something like this:
<product>
<name>iPhone</name>
<cost>$199.99</cost>
</product>
Orders and Customers would follow the same pattern and leave out the id attribute
and link element.
Assigning HTTP Methods
The final thing we have to do is decide which HTTP methods will be exposed for each
of our resources and what these methods will do. It is crucial that we do not assign
functionality to an HTTP method that supersedes the specification-defined boundaries
of that method. For example, an HTTP GET on a particular resource should be read-
only. It should not change the state of the resource it is invoking on. Intermediate
services like a proxy-cache, a CDN (Akamai), or your browser rely on you to follow
the semantics of HTTP strictly so that they can perform built-in tasks like caching
effectively. If you do not follow the definition of each HTTP method strictly, clients
and administration tools cannot make assumptions about your services and your sys-
tem becomes more complex.
Let’s walk through each method of our object model to determine which URIs and
HTTP methods are used to represent them.
Browsing All Orders, Customers, or Products
The Order, Customer, and Product objects in our object model are all very similar in how
they are accessed and manipulated. One thing our remote clients will want to do is to
browse all the Orders, Customers, or Products in the system. These URIs represent these
objects as a group:
/orders
/products
/customers
To get a list of Orders, Products, or Customers, the remote client will call an HTTP GET
on the URI of the object group it is interested in. An example request would look like
the following:
GET /products HTTP/1.1
Assigning HTTP Methods | 19
47.
Our service willrespond with a data format that represents all Orders, Products, or
Customers within our system. Here’s what a response would look like:
HTTP/1.1 200 OK
Content-Type: application/xml
<products>
<product id="111">
<link rel="self" href="http://example.com/products/111"/>
<name>iPhone</name>
<cost>$199.99</cost>
</product>
<product id="222">
<link rel="self" href="http://example.com/products/222"/>
<name>Macbook</name>
<cost>$1599.99</cost>
</product>
...
</products>
One problem with this bulk operation is that we may have thousands of Orders, Cus
tomers, or Products in our system and we may overload our client and hurt our response
times. To mitigate this problem, we will allow the client to specify query parameters
on the URI to limit the size of the dataset returned:
GET /orders?startIndex=0&size=5 HTTP/1.1
GET /products?startIndex=0&size=5 HTTP/1.1
GET /customers?startIndex=0&size=5 HTTP/1.1
Here we have defined two query parameters: startIndex and size. The startIndex
parameter represents where in our large list of Orders, Products, or Customers we want
to start sending objects from. It is a numeric index into the object group being queried.
The size parameter specifies how many of those objects in the list we want to return.
These parameters will be optional. The client does not have to specify them in its URI
when crafting its request to the server.
Obtaining Individual Orders, Customers, or Products
ImentionedintheprevioussectionthatwewoulduseaURIpatterntoobtainindividual
Orders, Customers, or Products:
/orders/{id}
/products/{id}
/customers/{id}
We will use the HTTP GET method to retrieve individual objects in our system. Each
GET invocation will return a data format that represents the object being obtained:
GET /orders/232 HTTP/1.1
For this request, the client is interested in getting a representation of the Order repre-
sented by the 232 Order id. GET requests for Products and Customers would work the
same. The HTTP response message would look something like this:
20 | Chapter 2: Designing RESTful Services
48.
HTTP/1.1 200 OK
Content-Type:application/xml
<order id="232">...</order>
The response code is 200, “OK,” indicating that the request was successful. The
Content-Type header specifies the format of our message body as XML, and finally we
have the actual representation of the Order.
Creating an Order, Customer, or Product
There are two possible ways in which a client could create an Order, Customer, or
Product within our order entry system: by using either the HTTP PUT or POST method.
Let’s look at both ways.
Creating with PUT
The HTTP definition of PUT states that it can be used to create or update a resource
on the server. To create an Order, Customer, or Product with PUT, the client simply
sends a representation of the new object it is creating to the exact URI location that
represents the object:
PUT /orders/233 HTTP/1.1
PUT /customers/112 HTTP/1.1
PUT /products/664 HTTP/1.1
PUT is required by the specification to send a response code of 201, “Created” if a new
resource was created on the server as a result of the request.
The HTTP specification also states that PUT is idempotent. Our PUT is idempotent,
because no matter how many times we tell the server to “create” our Order, the same
bits are stored at the /orders/233 location. Sometimes a PUT request will fail and the
client won’t know if the request was delivered and processed at the server. Idempotency
guarantees that it’s OK for the client to retransmit the PUT operation and not worry
about any adverse side effects.
The disadvantage of using PUT to create resources is that the client has to provide the
unique ID that represents the object it is creating. While it usually possible for the client
to generate this unique ID, most application designers prefer that their servers (usually
through their databases) create this ID. In our hypothetical order entry system, we want
our server to control the generation of resource IDs. So what do we do? We can switch
to using POST instead of PUT.
Creating with POST
Creating an Order, Customer, or Product using the POST method is a little more com-
plex than using PUT. To create an Order, Customer, or Product with POST, the client
sends a representation of the new object it is creating to the parent URI of its repre-
sentation, leaving out the numeric target ID. For example:
Assigning HTTP Methods | 21
49.
POST /orders HTTP/1.1
Content-Type:application/xml
<order>
<total>$199.02</total>
<date>December 22, 2008 06:56</date>
...
</order>
The service receives the POST message, processes the XML, and creates a new order
in the database using a database-generated unique ID. While this approach works per-
fectly fine, we’ve left our client in a quandary. What if the client wants to edit, update,
or cancel the order it just posted? What is the ID of the new order? What URI can we
use to interact with the new resource? To resolve this issue, we will add a bit of addi-
tional information to the HTTP response message. The client would receive a message
something like this:
HTTP/1.1 201 Created
Content-Type: application/xml
Location: http://example.com/orders/233
<order id="233">
<link rel="self" href="http://example.com/orders/133"/>
<total>$199.02</total>
<date>December 22, 2008 06:56</date>
...
</order>
HTTP requires that if POST creates a new resource that it respond with a code of 201,
“Created” (just like PUT). The Location header in the response message provides a URI
to the client so it knows where to further interact with the Order that was created, i.e.,
if the client wanted to update the Order. It is optional whether the server sends the
representation of the newly created Order with the response. Here, we send back an
XML representation of the Order that was just created with the ID attribute set to the
one generated by our database as well as a link element.
I didn’t pull the Location header out of thin air. The beauty of this ap-
proach is that it is defined within the HTTP specification. That’s an
important part of REST—to follow the predefined behavior defined
within the specification of the protocol you are using. Because of this,
most systems are self-documenting, as the distributed interactions are
already mostly defined by the HTTP specification.
Updating an Order, Customer, or Product
We will model updating an Order, Customer, or Product using the HTTP PUT method.
The client PUTs a new representation of the object it is updating to the exact URI
location that represents the object. For example, let’s say we wanted to change the price
of a product from $199.99 to $149.99. Here’s what the request would look like:
22 | Chapter 2: Designing RESTful Services
50.
PUT /orders/232 HTTP/1.1
Content-Type:application/xml
<product id="111">
<name>iPhone</name>
<cost>$149.99</cost>
</product>
As I stated earlier in this chapter, PUT is great because it is idempotent. No matter how
many times we transmit this PUT request, the underlying Product will still have the
same final state.
When a resource is updated with PUT, the HTTP specification requires that you send
a response code of 200, “OK” and a response message body or a response code of 204,
“No Content” without any response body. In our system, we will send a status of 204
and no response message.
We could use POST to update an individual Order, but then the client
would have to assume the update was nonidempotent and we would
have to take duplicate message processing into account.
Removing an Order, Customer, or Product
We will model deleting an Order, Customer, or Product using the HTTP DELETE
method. The client simply invokes the DELETE method on the exact URI that repre-
sents the object we want to remove. Removing an object will wipe its existence from
the system.
When a resource is removed with DELETE, the HTTP specification requires that you
send a response code of 200, “OK” and a response message body or a response code
of 204, “No Content” without any response body. In our application, we will send a
status of 204 and no response message.
Cancelling an Order
So far, the operations of our object model have fit quite nicely into corresponding HTTP
methods. We’re using GET for reading, PUT for updating, POST for creating, and
DELETE for removing. We do have an operation in our object model that doesn’t fit
so nicely. In our system, Orders can be cancelled as well as removed. While removing
an object wipes it clean from our databases, cancelling only changes the state of the
Order and retains it within the system. How should we model such an operation?
Assigning HTTP Methods | 23
contribute their personalholdings to a new company which was
virtually a trust; and in this form the trusts which had been
demolished were at once reorganized. Moreover, of course any
number of stock companies can simply dissolve and merge into one
large company, or they may keep their individuality but make
important trade agreements with one another, and so indirectly fulfil
the purposes of a trust. In short, the ways of bringing assenting
industrial enterprises under one management and so of virtually
making a given industry into a monopoly, are manifold.
To promote the development of trusts, there was nothing necessary
but success at the outset. If the first trusts were successful, the
device would be imitated so long as there was any prospect of profit.
It really happened that this imitation went on finally as a sort of
mania, where no special saving of profits could be predicted; one
trust followed another, and the year 1903 saw 233 purely industrial
trusts incorporated, of which 31 had a capital of over $50,000,000
each, and of which the total capitalization was over nine billions.
At first sight it might look as if this movement would be really
sympathetic to the American people in general. The love of size
generated in the nation by the lavishness of nature must welcome
this consolidation of interest, and the strong spirit of self-initiative
claiming the right of individuals to unite and work together must
surely favour all sorts of co-operation. As a fact now an opposite
tendency operates, which after all springs from the same spirit of
self-initiative. The freely acting individual must not be prevented by
a stronger force from using the strength he has. Everything which
excludes free competition and makes the individual economically
helpless seems immoral to the American. That is old Anglo-Saxon
law.
The common law of England has at all times condemned agreements
which tend toward monopoly, and this view dominates the American
mind with a force quite surprising to the European who has become
accustomed at least to monopolies owned by the state. The laws of
almost all the separate states declare agreements tending toward a
53.
monopoly to beillegal; and federal legislation, in its anti-trust
measures of 1887 and 1890, has seconded this idea without doing
more than formulating the national idea of justice. The law of the
country forbids, for instance, all agreements looking to the
restriction of trade between different states of the country or with
foreign nations. Senator Foraker, in February, 1904, called down
public displeasure by proposing a law which permitted such
agreements restricting commerce so long as the restriction was
reasonable. It was feared at once that the courts would think
themselves justified in excusing every sort of restraint and
monopolistic hindrance. And yet there is no doubt that the
interpretation of what should constitute “restriction” to commerce
was quite as arbitrary a matter as the interpretation of what should
be “reasonable.” Indeed, the economic consolidation of competing
organizations by no means necessarily cuts off the beneficent effects
of competition. When, for instance, the Northern Securities Company
united several parallel railway lines, it asserted justly that the several
roads under their separate corps of officials would still compete for
public favour. Yet the public and the court objected to the
consolidation. The one real hindrance to the propagation of trusts
lies in this general dread of every artificial check to free competition.
Many circumstances which have favoured the formation of trusts are
obvious. In the first place, the trust can carry on business more
cheaply than the component companies individually. The general
administration is simplified by doing away with parallel positions, and
all expenses incident to business competition are saved. Then, too, it
can make larger profits since when competition stops, the fixing of
prices lies quite with itself. This is of course not true, in so far as
other countries are able to compete; but here comes in the function
of the protective tariff, which permits the trust to raise its prices until
they equal those of foreign markets plus the tariff.
The good times which America has enjoyed for some years have also
favoured the development of trusts. When the harvests are good
and the factories all busy, high prices are readily paid. The trusts can
do even better than single companies by shutting down unprofitable
54.
plants and adaptingthe various remaining plants for mutual co-
operation. Then, too, their great resources enable them to procure
the best business intelligence. In addition to all this came a series of
favourable external circumstances. First was the rapid growth of
American capital which was seeking investment. In the seventies,
the best railroad companies had to pay a rate of 7 per cent. in order
to attract investors; now they pay 3½ per cent. Capital lies idle in
great quantities and accumulates faster than it can find investment.
This has necessarily put a premium on the organization of new
trusts. Then, too, there was the well-known uniformity of the
market, so characteristic of America. The desire to imitate on the
one side, and patience and good nature on the other, give to this
tremendous region of consumption extending from the Atlantic to
the Pacific Ocean a uniformity of demand which greatly favours
manufacture on a gigantic scale. This is in sharp contrast with the
diversity of requirements in Europe.
It has been, doubtless, also important that the American feels
relatively little attached to his special business. Just as he loves his
Fatherland really as a conception, as an ideal system, but feels less
bound to the special piece of soil where he was born and will leave
his own farm if he is a farmer and go westward in search of better
land, so the American passionately loves business as a method,
without being over attached to his own particular firm. If the
opening is favourable, he gives up his business readily to embark on
another, just as he gives up an old-fashioned machine in favour of
an improved one.
Just this quality of mind is so different from the German that here
would be probably the greatest hindrance to the organization of
trusts in Germany. The German feels himself to have grown up in his
special business, which he may have inherited from his father, just
as the peasant has grown up on his farm, and he does not care to
become the mere employee of a large trust. Another contributory
mental trait has been the friendly confidence which the American
business man puts in his neighbour. The name is here appropriate;
the trusts in fact repose to a high degree on mutual trust, and trusts
55.
like the Americancould not develop wherever there should be
mutual distrust or jealousy in the business world. Finally, the laws
themselves have been favourable, in so far as they have favoured
the issue of preferred stock in a way very convenient to trusts, but
one which would not have been approved in Europe. And, moreover,
the trusts have made considerable use of the diversity existing
between the laws of different states.
There have been retarding factors, too. We have mentioned the
most important of all—the legal discountenance of all business
agreements tending to create a monopoly or to restrain trade. There
have been others, however. One purpose of the trusts is to put
prices up and so to make the necessities of life dearer. It is the
people who pay the prices—the same people who elect Congress
and determine the tariffs and the laws; so that every trust works in
the knowledge that putting up prices tends immediately to work
back on business by calling forth tariff revision and anti-trust laws.
One source of great profit to the trusts has been the possibility of
restricting output. This method promised gain where natural
products were in question, such as oil, tobacco, and sugar, of which
the quantity is limited, and further for all technical patents. Where,
however, there is no such limitation the most powerful corporation
will not be able to avoid competition, and if it tries to buy up
competing factories to stop such competition, still more are built at
once, solely with the purpose of extorting a high ransom from the
trusts; and this game is ruinous. In other departments again
consolidation of business means very little economy; Morgan’s
marine trust is said not to have succeeded for this reason. In short,
not all industries are susceptible of being organized as trusts, and
the dazzling profits of certain favoured trusts too easily misled those
who were in pursuit of fortune into forgetting the difference between
different businesses. Trusts were formed where they could not be
profitable. Perhaps the real founders themselves did not overlook the
difference; but they counted on the great hungry public to overlook
it, until at least most of the shares should have been disposed of.
56.
As a fact,however, the reluctance of the great investing public has
been a decidedly restraining factor too. The securities spoiled before
the public had absorbed them; everywhere the complaint went up of
undigested securities. The public came early to suspect that the
promoters were making their profits not out of the legitimate
economies to be saved by the trusts, but by enormously
overcapitalizing them and taking large blocks of stock for
themselves.
There was still another unfavourable influence on public opinion. The
main profits of a protected trust lie in its being able to sell more
dearly than it could if exposed to foreign competition. But now if the
consolidated industry itself proposes to sell to other countries, it
must of course step down to the prevailing level of prices. It must
therefore sell more cheaply abroad than at home. But this is soon
found out, and creates a very unfavourable impression. The
American is willing to pay high prices, as far as that goes; but when
he has to pay a price double what the same factory charges for the
same goods when delivered in Europe, he finds the thing wholly
unnatural, and will protest at the next election. Thus there have
been plenty of factors to counteract the favourable conditions, and
the history of trusts has certainly not been for their promoters a
simple tale of easy profits.
Now, if we do not ask what has favoured or hindered the trusts, nor
how they have benefited or jeopardized their founders, but rather
look about to see what their effect on the nation has been and will
be, some good features appear at once. However much money may
have been lost, or rather, however fictitious values may have been
wiped out in the market, the great enterprises are after all increasing
the productive capacity of the nation and its industrial strength in
the fight with other peoples. They give a broad scope to business,
and bring about relations and mutual adaptations which would never
have developed in the chaotic struggling of small concerns. They
produce at the same time by the concentration of control an inner
solidarity which allows one part to function for another in case there
are hindrances or disasters to any part of the great organism, and
57.
this is undoubtedlya tremendous factor for the general good. A
mischance which, under former conditions, would have been
disastrous can be survived now under this system of mutual
interdependence: thus it can hardly be doubted that the combined
action of the banks in the year 1903 prevented a panic; since, when
stocks began to fall, the banks were able to co-operate as they
would not have been able previously to their close affiliation.
Furthermore, economic wealth can now be created more
advantageously for the nation. The saving of funds which were
formerly spent in direct competition is a true economy, and the
trusts have asserted again and again that as a matter of fact they do
not put up prices, but that they make sufficient profits in saving
what had formerly been wasted in business hostilities. Certainly the
trusts make it possible to isolate useless or superannuated plants,
without causing a heavy loss to the owners, and thus the national
industry is even more freely adaptable to changing circumstances
than before; and this advantage accrues to the entire country. The
spirit of enterprise is remarkably encouraged and the highest
premiums are put on individual achievement. Almost all the men
who hold responsible positions in the mammoth works of the Steel
Trust have worked up, like Carnegie himself, from the bottom of the
ladder, and made their millions simply by working better than their
fellows.
On the other hand, the trusts have their drawbacks. One of the most
regrettable to the American mind is their moral effect. The American
distrusts such extreme concentration of power and capital; it looks
toward aristocracy, oligarchy, and tyranny. At the same time the
masses are demoralized, and in very many cases individual initiative
is strangled. There are, as it were, nothing but officials obeying
orders; no men acting wholly on their own responsibility. Work
ceases to be a pleasure, because everything goes by clock-work; the
trust supersedes the independent merchant and manufacturer just
as the machine has superseded the independent artisan.
58.
The trusts haveother demoralizing effects. Their resources are so
tremendous as in the end to do away with all opposition. The
independent man who hopes to oppose the great rival, can too
easily be put in a position in which he is made to choose between
beggary and the repudiation of all his principles. Everybody knows
the shameless history of the Standard Oil Company, which has
strangled not merely weak proprietors, but, much more, has
strangled strong consciences. Then, too, the whole system of over-
capitalization is immoral. Large trusts can hardly be formed except
by purchasing the subsidiary companies at fancy prices, and issuing
stock which in large part represents the premium paid to the
promoters. Indeed, this whole system of community of interests
which puts thousands of corporations into the hands of a few men
who everywhere play into one another’s hands, must bring it about
that these men will soon grow careless and overlook one another’s
irregularities in a way which will threaten sober business traditions.
The whole country was shocked on hearing the revelations of the
Shipbuilding Trust, and seeing with what criminal carelessness the
organization went on in a little group of friends, and how the
methods of poker-playing were applied to transactions of great
moment. The fundamental objection, however, is always that it is
immoral to kill competition by agreements which create a monopoly.
Now, what can be done to obviate these evils? Apparently the first
thing would be a revision of the tariff; and yet even their opponents
must agree that there is only an indirect relation between the
protective tariff and the trusts. It is true that the high tariffs have
helped to create those industries which have now come together in
trusts, and if the industries were to be wiped out, of course there
would be nothing left of consolidations. But it is surely not true that
the trusts are the immediate effect of the tariff, and the more a
revised tariff were to let in foreign competition so much the more
would the national industries need to form themselves into trusts for
the sake of the benefits of consolidated management. All the
business advantages and all the moral evils of trusts would still
remain, even though the dividends were to sink. And the trusts
59.
would not becarried off the field unless American industry itself
should utterly succumb to the foreign enemy.
Most of all, however, it seems clear that any policy prejudicial to the
conditions of production and distribution would first of all, and most
sadly, hit the competitors of the trusts. There is no absolute
monopoly in any American industry. Indeed, even the Sugar Refining
Company has a few outside competitors, and there is a legion of
independent producers outside of the Steel Trust who are
themselves in part organized in groups, and in many industries the
trusts do not comprise even half of the manufacturers. Now, if the
high tariff wall should be torn down so that a flood of cheap foreign
manufactures could come in, it is certain that the first sufferers
would be the small independent companies, which would be
drowned out, while the mighty trusts would swim for a long time.
Indeed, the destruction of such home competition would greatly
benefit the trusts. Some of the strongest of these would hardly be
reached at all by a reduction of the tariff—as, for instance, the
strongest of them, the Petroleum Trust, which does not enjoy any
protection. And it is also to be asked if trusts do not prosper in free-
trade England? So soon as the water is squeezed out of their stocks,
as has in good part lately happened, the trusts would still have a
great advantage after protective duties should be abolished. And at
the same time the necessary depression of wages which would
result from that movement would endanger the whole industrial
fabric. Moreover, the social and moral evils of the trusts would
persist. Therefore the Republican party, which is just now in power,
will take no part in solving the trust question by reducing the tariff.
Those Republicans who oppose the trusts are much more inclined to
proceed to federal legislation. President Roosevelt has, in a number
of speeches which are among the most significant contributions to
the whole discussion, pointed to this way again and again. The
situation is complicated and has shifted from time to time. The real
difficulty lies in the double system of legislative power which we
have already explicitly described. We have seen that all legislative
power which is not expressly conferred on the Union belongs to the
60.
several states; speciallyhas each state the right to regulate the
commercial companies to which it has given charters. But if the
company is such a one as operates between several states—as, for
instance, one which transports goods from one state to another—it
is regulated by federal law. Now, as long ago as the year 1890, in
the so-called Sherman Act, Congress passed draconic regulations
against interstate trusts. The law threatens with fine and
imprisonment any party to a contract which restricts interstate
commerce. It can be said of this law that it entirely did away with
the trusts in their original form, in which the various companies
themselves composed the trust. At the same time the federal
officials were strongly seconded by the judicial doings of the
separate states, as we have already seen. But the effect has only
been to drive industry into new forms, and forms which are not
amenable to federal regulations, but fall under the jurisdiction of the
separate states. Corporations were formed which have their home in
a certain state, but which by the tremendous capital of their
members have been able to acquire factories distributed all through
the country. Indeed, they are not real trusts any more, and the
name is kept up only because the new corporations have descended
from trusts and accomplish the same purpose.
Of course, this change would have been of no advantage for the
several companies if the stern spirit shown by Congress in this
legislation had been manifested once more by the separate states,
that is, if each separate state had forbidden what the Union had
forbidden; but so long as a single state in the whole forty-five
permitted greater freedom to business than the others, of course all
new companies would be careful to seek out that state and settle
there. And, what was more important, would there pay taxes—a fact
which tended to persuade every state to enact convenient trust
laws.
Now, it is not a question between one state and forty-four others,
but rather between the diversities of all the forty-five. Almost every
state has its peculiar provisions, and if its laws are favourable to the
trusts this is because, as each state says, if it were to stand on high
61.
moral grounds itwould only hurt itself by driving away profitable
trusts, and would not benefit the whole country, because the trusts
would simply fly away and roost in some other state. More especially
the industrially backward Western States would be always ready to
entertain the trusts and pass most hospitable laws, for the sake of
the revenue which they could thereby get for their local purposes.
And so it is quite hopeless to expect the trusts to be uprooted by the
legislation of the separate states. If all forty-five states were to pass
laws such as govern stock companies in Massachusetts, there would
be no need of further legislation; and it is also no accident, of
course, that there are very few trusts in the State of New York. All
the great trusts whose directors reside in the metropolis have their
official home across the river in the State of New Jersey, which has
made great concessions to the companies.
If these companies are to be reached by law, the surest way seems
to be by taking a radical step and removing the supervision of large
stock companies from the single states, and transferring it to the
federal government; this is the way which President Roosevelt has
repeatedly recommended. In our political section we have explicitly
shown that such a change cannot be introduced by an act of
Congress, but only by an amendment to the Constitution, which
cannot be made by Congress, since it is in itself a product of the
Constitution. Congress would be able only to take the initiative, and
two-thirds of both houses would have to support the proposition to
change the Constitution; and this change would have to be ratified
by three-fourths of the state legislatures themselves. Now, it would
be difficult to get a two-thirds majority in both houses on any
question hostile to trusts; but it is quite out of the question to induce
the three-fourths of the states to cripple their own rights in so
important a matter as the regulation of stock companies; particularly
as in economic matters local power is necessary to local optimism,
and the weaker states would never consent to give up such rights,
since they would be forced to see industrial laws framed according
to the requirements of the more highly developed states. Was the
President, then, in his speeches, like Don Quixote, tilting against the
62.
windmills; or washe proposing, as some of his opponents said, quite
impracticable solutions in order to divert attention from such a
handy solution as that of tariff reduction? And was he declaiming
loudly against the trusts before the public in order really to help on
the friends of capital?
Perhaps another point of view may be found. It may be that
President Roosevelt proposed a constitutional amendment in order
to arouse discussion along certain lines, and in order specially to
have the chance of demonstrating that federal control of those
overgrown business enterprises is necessary, and that their control
by the several states is dangerous. It looks indeed as if such
discussion would have been highly superfluous if not insincere, if it
were true that the sole way of helping the situation were the quite
impossible constitutional amendment.
But such is not the case; there is another way of reaching the same
end without meeting the difficulties involved in changing the
Constitution. Of course, the President was not free to discuss this
means, nor even to mention it. This way is, we think, for the
Supreme Court to reverse its former decision, and to modify its
definition of interstate commerce in closer accord with the latest
developments of the trusts. We have seen that there are drastic laws
relating to interstate commerce which have overthrown all the earlier
trusts; but a corporation claiming home in New Jersey, although
owning factories in different states and dependent on the co-
operation of several states for its output, is to-day treated by the
Supreme Court as a corporation pertaining to one state. If, now, the
Supreme Court were to decide that such a corporation transacts
interstate commerce, then all the severity of the existing federal laws
would apply to such corporations, and everything which could be
accomplished by an amendment to the Constitution would be
effected by that one decision. Of course, the President could not
suggest this, since the Supreme Court is co-ordinate with the
Executive; yet if public attention should be awakened by such a
discussion, even the judges of the Supreme Court might consider the
matter in a new light.
63.
To be sure,this would at the same time require the Supreme Court
somewhat to modify its previous interpretation of the Anti-Trust Law
itself, and not merely its application; since otherwise, if the trusts
come under federal jurisdiction, the law might wipe out the new
trusts, as it did the old, instead merely of regulating them. In view of
the recently published memoirs of Senator Hoar, there can be no
doubt that the Supreme Court has interpreted the law forbidding the
restraint of trade more strictly than was originally intended in the bill
which Hoar himself drew up. Congress meant to refer to agreements
in restraint of trade in a narrow, technical sense, while the court has
interpreted this law as if it were to apply to every agreement which
merely regulates production or sale in any place. But this
unnecessarily severe construction of the law by the unexpected
verdict of the court can of course be set aside by a further
Congressional measure, and therefore offers no difficulty.
The Administration might proceed in still another way. A good deal
has been said of greater publicity in public affairs, and in the last few
years energetic measures have already been taken at the instance of
the President. Many of the evils of trusts lie in their concealment of
the conditions under which they have been organized; and the new
Department of Commerce is empowered to take official testimony
concerning all such matters, and to demand this under oath.
Whether this will be an ultimate gain is doubted by many, since
those acquainted with the matter say that the secrets of modern
book-keeping make it impossible to inspect the general condition of
a large industrial concern when its promoters desire to conceal the
truth. While if one were to go back of the books and lay bare every
individual fact to the public eye, the corporations would be
considerably injured in their legitimate business. And in any case,
this new effort at publicity has so far no judicial sanction. One large
trust has already refused to give the information desired because its
counsel holds the Congressional law to be unconstitutional, and this
matter will have to be settled by the Supreme Court.
The most thoughtful minds are coming slowly to the opinion that
neither tariff provisions nor legislation is necessary, but that the
64.
matter will eventuallyregulate itself. The great collapse of market
values has opened the eyes of many people, and the fall in the price
of commodities manufactured by trusts works in much the same
direction. People see, more and more, that most of the evils are
merely such troubles as all infant organisms pass through. The
railroads of the country were also at first enormously overcapitalized,
but the trouble has cured itself in the course of time. The surpluses
have been spent on improvements, and railroad shares to-day
represent actual values. Such a change has in fact already set in
among the trusts. Paternal regulation by the government, which
prescribes how industry shall go on, is always essentially distasteful
to Americans. Exact regulative measures which shall be just cannot
be framed beforehand by any government. Even Adam Smith
believed, for instance, that the form of organization known as a
stock company was suitable for only a few kinds of business. The
American prefers to submit all such questions to the actual business
test. All experimental undertakings are sifted by natural selection,
and the undesirable and unnecessary ones fall through. It is true
that many lose their property in such experiments, but that is only a
wholesome warning against thoughtless undertakings and against
hasty belief that the methods profitable in one field must be
profitable in every other. It is true that here and there a man will
make large profits rather too easily, but Roosevelt has well said that
it is better that a few people become too rich than that none
prosper.
The development of affairs shows most of all that prices can be
inflated for a short time, but that they slowly come back to a
reasonable figure so long as there are no real monopolies. The
experience of the last ten years teaches, moreover, that the most
important factor which works against the trusts is the desire for
independence on the part of capitalists, who do not for a long time
willingly subordinate themselves to any corporation, but are always
tempted to break away and start once more an independent
concern.
65.
And comparing thesituation in 1904 with that of 1900, one sees that
in spite of the seeming growth of the trust idea, the trusts
themselves have become more solid by the squeezing out of
fictitious valuations; they are more modest, content themselves with
less profits, and they are much less dangerous because of the
competition which has grown up around them. The trusts which
originally ruled some whole industry through the country are to-day
satisfied if they control two-thirds of it. A single fundamental thought
remains firm, that the development of industry demands a
centralized control. This idea works itself out more and more, and
would remain in spite of any artificial obstruction which might be put
before it. But the opposite tendencies are too deeply rooted in
human nature, in Anglo-Saxon law, and in the American’s desire for
self-initiative, to let this centralization go to dangerous limits.
But those who will not believe that the trusts, with their enormous
capitals, can be adequately restrained in this way, may easily content
themselves with that factor which, as the last few years have shown,
speaks more energetically than could Congress itself—this is
organized labour. The question of capital in American economy is
regulated finally by the question of labour.
The Labour Question
As the negro question is the most important problem of internal
politics, so the labour question is the most important in American
economic life; and one who has watched the great strikes of recent
years, the tremendous losses due to the conflicts between capital
and labour, may well believe that, like the negro question, this is a
problem which is far from being solved. Yet this may not be the
case. With the negro pessimism is justified, because the difficulties
are not only unsolved, but seem unsolvable. The labour question,
however, has reached a point in which a real organic solution is no
longer impossible. Of course, prophecies are dangerous; and yet it
looks as if, in spite of hard words, the United States have come to a
66.
condition in whichlabourers and capitalists are pretty well satisfied,
and more so perhaps than in any other large industrial nation. It
might be more exact to say that the Americans are nearer the ideal
condition for the American capitalist and the American labourer,
since the same question in other countries may need to be solved on
wholly different lines.
In fact, the American problem cannot be looked into without
carefully scrutinizing how far the factors are peculiar to this nation.
Merely because certain general factors are common to the whole
industrial world, such as capital, machinery, land values, labour,
markets, and profits, the social politician is inclined to leave out of
account the specific form which the problem takes on in each
country. The differences are chiefly of temperament, of opinions,
and of mode of life.
It is, indeed, a psychological factor which makes the American
labour question very different from the German problem. This fact is
neglected, time after time, in the discussions of German theorists
and business men. It is, for instance, almost invariably affirmed in
Germany that the American government has done almost nothing
toward insuring the labourer against illness, accident, or old age,
and that therefore America is in this respect far inferior to Germany.
It can easily be foreseen, they say, that American manufacturers will
be considerably impeded in the world’s market as soon as the
progress of civilization forces them to yield this to the working-man.
The fact is that such an opprobrium betrays a lack of understanding
of American character. The satisfaction felt in Germany with the laws
for working-men’s insurance is fully justified; for they are doubtless
excellent under German conditions, but they might not seem so
satisfactory to the average American nor to the average American
labourer. He looks on it as an interesting economic experiment,
admirable for the ill-paid German working-man, but wholly
undesirable for the American. The accusation that the American
government fails in its duty by not providing for those who have
served the community, is the more unjust, since America expends on
67.
the average $140,000,000in pensions for invalid veterans and their
widows, and is equally generous wherever public opinion sees good
cause for generosity.
It cannot be doubted that the American labourer is a different sort of
creature from the Continental labourer; his material surroundings are
different, and his way of life, his dwelling, clothes and food, his
intellectual nourishment and his pleasures, would seem to the
European workmen like luxuries. The number of industrial labourers
in the year 1880 was 2.7 million, and they earned $947,000,000; in
1890 it was 4.2 million earning $1,891,000,000; and in 1900 there
were 5.3 million labourers earning $2,320,000,000; therefore, at the
time of the last census, the average annual wage was $437. This
average figure, however, includes men, women, and children. The
average pay of grown men alone amounts to $500. This figure gives
to the German no clear idea of the relative prosperity of the
working-man without some idea of the relation between German and
American prices.
One reads often that everything is twice as expensive in America as
in Germany, while some say that the American dollar is worth only
as much as the German mark—that is, that the American prices are
four times the German; and still others say that American prices are
not a bit higher than German. The large German-American
steamships buy all their provisions of meat in New York rather than
in Hamburg or Bremen, because the American prices are less. If one
consults, on the other hand, a doctor or lawyer in New York, or
employs a barber or any one else for his personal services, he will
find it a fact that the American price is four times as high as the
German. The same may be said of articles of luxury; for bouquets
and theatre tickets the dollar is equal to the mark. It is the same
with household service in a large town; an ordinary cook receives
five dollars per week, and the pay of better ones increases as the
square of their abilities. Thus we see at once that an actual
comparison of prices between the United States and Europe cannot
be made. A dollar buys five marks’ worth of roast beef and one
mark’s worth of roses.
68.
In general, itcan be said that the American is better off as regards
all articles which can be made in large quantities, and worse off in
articles of luxury and matters of personal service. The ready-made
suit of clothes is no dearer in America than in Germany and probably
better for the price, while the custom-made suit of a first-class tailor
costs about four times what it would cost in Germany. All in all, we
might say that an American who lives in great style and spends
$50,000 a year can get no greater material comforts than the man in
Germany who spends a third as much—that is, 70,000 marks. On
the other hand, the man who keeps house with servants, but
without luxuries, spending, say, $5,000 a year, lives about like a man
in Germany who spends 10,000 marks—that is, about half as much.
But any one who, like the average labourer, spends $500 in America,
unquestionably gets quite as much as he would get with the equal
amount of 2,100 marks in Germany.
But the more skilled artisan gets $900 on the average—that is, about
three times as much as the German skilled workman; so that,
compared with the wages of higher-paid classes, the working-men
are paid relatively much more than in Europe. The average labourer
lives on the same plane as the German master artisan; and if he is
dissatisfied with the furnishings of his home it is not because he
needs more chairs and tables, but because he has a fancy for a new
carpet or a new bath-tub. In this connection we are speaking always
of course of the real American, not the recent immigrants from
Southern and Eastern Europe, who are herded together in the worst
parts of large cities, and who sell their labour at the lowest rate. The
native American labourer and the better class of German and Irish
immigrants are well clothed and fed and read the newspapers, and
only a small part of their wages goes for liquor.
More important than the economic prosperity of the American
working-man, though not wholly independent of it, is the social self-
respect which he enjoys. The American working-man feels himself to
be quite the equal of any other citizen, and this not merely in the
legal sense. This results chiefly from the intense political life of the
country and the democratic form of government, which knows no
69.
social prerogatives. Itresults also from the absence of social caste.
There is a considerable class feeling, but no artificial lines which
hinder any man from working up into any position. The most modest
labourer knows that he may, if he is able, work up to a distinguished
position in the social structure of the nation.
And the most important thing of all is probably the high value put on
industry as such. We have spoken of this in depicting the spirit of
self-initiative. In fact, the background of national conceptions as to
the worth of labour must be the chief factor in determining the social
condition of the working-man. When a nation comes to that way of
thinking which makes intellectual activities the whole of its culture,
while economic life merely serves the function of securing the—
outward comforts of the nation as it stretches on toward its goal of
culture, then the industrial classes must content themselves with an
inferior position, and those who do bodily labour, with the least
possible amount of personal consideration. But when a nation, on
the other hand, believes in the intrinsic worth of industrial culture,
then the labour by which a man lives becomes a measure of his
moral worth, and even intellectual effort finds its immediate ethical
justification only in ministering to the complex social life; that is,
only so far as it is industry.
Such now is the conception of the American. Whether a person
makes laws, or poetry, or railway ties, or shoes, or darning-needles,
the thing which gives moral value to his life’s work is merely its
general usefulness. In spite of all intellectual and æsthetic
differences, this most important element of activity is common to all,
and the manual labourer, so far as he is industrious, is equal to
those who work with their brains. On the other hand, the social
parasite, who perhaps has inherited money and uses it only for
enjoyment, is generally felt to be on a lower plane than the factory
hand who does his duty. For the American this is not an artificial
principle, but an instinctive feeling, which may not do away with all
the thousand different shadings of social position, but nevertheless
consigns them to a secondary place. One may disapprove of such an
industrial conception of society, and like better, for example, the
70.
æsthetic conception ofthe Japanese, who teach their youth to
despise mercantile business and tastefully to arrange flowers. But it
is clear that where such an industrial conception prevails in a nation
the working-man will feel a greater self-respect and greater
independence of his surroundings, since the millionaire is also then
only a fellow-workman.
Undoubtedly just this self-respect of the American labourer makes
him the great industrial force which he is. The American
manufacturer pays higher wages than any of his competitors in the
markets of the world and is not disconcerted at this load, because he
knows that the self-respecting working-man equalizes the difference
of price by more intense and intelligent labour. It is true that the
perfection of labour-saving machinery is a tremendous advantage
here, but after all it is the personal quality of the working-man which
has brought about that in so many industries ten American workmen
do more than fifteen or, as experts often say, twenty Italian
workmen. The American manufacturer prefers to hire a hundred
heads rather than a thousand hands, even if the wages are equal,
and even the greedy capitalist prefers the labourer who is worth
thirty dollars a week to one who is worth only twenty. The more the
working-man feels himself to be a free co-operator, the more
intelligently does he address himself to the work. We hear constantly
of improvements which artisans have thought out, and this
independent initiative of theirs does not in the least impair the
discipline of industry. American discipline does not mean inferiority
and the giving up of one’s own judgment, but is a free willingness to
co-operate and, for the common end, to intrust the leadership to
some one else. This other person is exalted to the trustworthy
position of leader by the desire of those concerned, so that each
man is carrying out his own will in obeying the foreman.
Therefore, everything which in any wise savours of compassion is
entirely out of the question for him. In fact, the friendly
benevolence, however graciously expressed, intended to remind the
workman that he is after all a human creature, perhaps the friendly
provision of a house to live in or of some sort of state help for his
71.
family, must alwaysbe unwelcome to him, since it implies that he is
not able, like other fathers of a family, to be forethoughtful and
provident. He prefers to do everything which is necessary himself.
He insures himself in a life-insurance company and, like anybody
else, he looks out for his own interests—tries to improve his
conditions by securing good contracts with his employer, by
arranging organizations of his fellow-workmen, and by means of his
political rights. But whatever he accomplishes, he enjoys it because
he has worked in free competition against opposing interests. Any
material benefits which he might purchase by enduring the
patronizing attitude of capitalists or legislators would be felt to be an
actual derogation.
And thus it happens that social democracy, in the technical sense,
makes no advance among American workmen. The American
labourer does not feel that his position is inferior; he knows that he
has an equal opportunity with everybody else, and the idea of entire
equality does not attract him, and would even deprive him of what
he holds most valuable—namely, his self-initiative, which aims for
the highest social reward as a recognition of the highest individual
achievement. American society knows no unwritten law whereby the
working-man of to-day must be the same to-morrow, and this gives
to the whole labour question in America its distinction from the
labour question in European aristocratic countries. In most cases the
superiors have themselves once been labourers. Millionaires who to-
day preside over the destinies of thousands of working-men have
often themselves begun with the shovel or hod. The workman knows
that he may set his ambition as high as he likes, and to exchange his
equal opportunity for an equality of reward would mean for him to
sink back into that social condition in which industry is thought to be
only a means to something else, and not in itself a valuable activity.
Although Bellamy may already dream of the common umbrella, his
native country is probably further from social democracy than any
country in Europe, because the spirit of self-initiative is here stronger
than anywhere else, and because the general public is aware that no
class distinctions cut it off from the highest positions in the country.
72.
It knows thateverything depends on industry, energy, and
intelligence.
This does not hinder the working-men, in their fight for better
conditions of labour, from adopting many socialistic tenets. The
American calls it socialism even to demand that the government own
railways, telegraph lines, express companies, or coal-fields, or that
the city conduct tramways, or gas or electric-light works. Socialism
of this sort is undoubtedly progressing, although the more
extravagant ideas find more wordy orators to support them than
hearers to give belief. It is also very characteristic that the labour
leaders do not make such agitation their life work, but often after a
few years go over to one or another civil occupation. The relation
between working-man and capitalist, moreover, is always felt to be
temporary. A man is on one side of the line to-day and on the other
to-morrow. There is no firm boundary between groups of men, but
merely a distribution in temporary groups; and this separates the
American labour unions from even the English unions, with which
otherwise they have much in common.
Many other conditions by which the American working-man’s life is
separated from the Englishman’s are of an economic sort. It is
remembered, for instance, how successful the English unions have
been in establishing co-operative stores, while in America they have
failed in this. The department shops in the large cities have been
able to sell cheaper and better goods, and have been in every way
more popular. But enough of comparing America with the Old World
—we must discuss the actual situation in the New.
73.
The labour movementof the United States really began in the third
decade of the last century. Of course, only the North is in question;
in the South slavery excluded all alliances and independent
movements for improving the condition of the manual labourer.
There had been small strikes as early as the eighteenth century, but
the real movement began with the factories which were built during
the nineteenth.
From the very beginning the demand for shorter hours and higher
wages were the main issues. At the same time the American world
was filled more or less with fantastic notions of co-operation, and
these influenced the course of affairs. Boston and New York were
the centres of the new movement. As early as 1825 in New York
there appeared the first exclusively labour newspaper, the “Labour
Advocate”; it commenced a literature which was to increase like an
avalanche. The labourers figured independently in politics in 1830,
when they had their own candidate for governor. But all political
endeavours of the working people have been mere episodes, and
the chief labour movements of the century have taken place outside
of politics; the leading unions have generally found that their
strength lay in renouncing political agitation. Only when legal
measures for or against the interests of labourers have been in
question, has there been some mixing in with politics, but the
American workmen have never become a political party.
At the beginning of the thirties, working-men of different industries
united for the first time in a large organization, such as later became
the regular form. But at the outset of the movement there appeared
also the opposite movement from the side of the capitalists. For
instance, in 1832 merchants and shipholders in Boston met solemnly
to declare it their duty to oppose the combinations of working
people which were formed for the illegal purpose of preventing the
individual workman from making a free choice as regards his hours
of labour, and for the purpose of making trouble with their
employers, who already paid high wages.
74.
The organization ofthe working-man and that of the employer have
grown steadily, and the nation itself has virtually played the rôle of
an attentive but neutral spectator. In the case of direct conflict the
sympathy of the country has almost always been on the side of the
working-man, since in the concrete case the most impressive point
was generally not the opposition between capital and labour, but the
personal contrast of the needy day-labourer and the rich employer;
and the sentimentality of the American has always favoured the
weaker classes. The nation however, has shown an equal amount of
sympathy toward capital whenever a general matter of legislation
was in question; that is, whenever the problem has seemed more
theoretical than personal. In such cases the capitalists have always
been felt to be the pioneers of the American nation by putting their
enterprise into all sorts of new undertakings, applying their capital
and intelligence to economic life; so that they have seemed to a
greater extent in need of national protection than the workman, who
may always be easily replaced by some one else.
Considering the matter as a whole, it can be said indeed that the
nation has preserved a general neutrality, and let both parties
virtually alone. A change has very recently taken place. The new
conditions of the industrial struggle make it clearer day by day that
there are three parties to the conflict, rather than two; that is, not
only capitalist and labourer, but also the general public, which is
dependent on the industrial output, and therefore so immediately
concerned in the settlement of differences as to seem, even in
concrete cases, entitled to take active part. The turning-point came
perhaps during the coal strike in the winter of 1902–03, when the
President himself stood out to represent this third party. But we
must follow the development more minutely—must speak of the
labour organizations as they exist to-day, of the results of legislation,
of the weapons employed by the labourers and those used by the
capitalists, of their advantages and disadvantages, and of the latest
efforts to solve the problem. Three forms of working-men’s
organizations can be discriminated to-day—the Knights of Labour,
the independent trades-unions, and the federated trades-unions.
75.
The Knights ofLabour are by principle different from both of the
other groups; and their influence, although once very great, is now
waning. Their fundamental idea is a moral one, while that of their
rivals is a practical one. This is, of course, not to be taken as
meaning that the labour unions pursue immoral ends or the Knights
of Labour unpractical ones. The Knights of Labour began very
modestly in 1869 as a secret organization, somewhat like the Free
Masons, having an elaborate initiation and somewhat unusual
procedures. Their constitution began with the motto, “Labour is
noble and sacred,” and their first endeavours were for the
intellectual uplifting of the labourer and opposition to everything
which made labour mean or unworthy. The order grew steadily, but
at the same time the practical interests of different groups of
working-men necessarily came into prominence. In the middle
eighties, when they gave up their secret observances, the society
had about a million members, and its banner still proclaimed the one
sentiment that industry and virtue not wealth are the true measure
of individual and national greatness. Their members, they insisted,
ought to have a larger share of the things which they produced, so
as to have more time for their intellectual, moral, and social
development. In this moral spirit, the society worked energetically
against strikes and for the peaceful settlement of all disputes.
Its principal weakness was perhaps that, when the membership
became large, it began to take part in politics; the Knights
demanded a reform in taxation, in the currency, in the credit system,
and a number of other matters in line with state socialism. It was
also a source of weakness that, even in local meetings, working-men
of different trades came together. This was of course quite in
accordance with the ethical ideal of the society. As far as the moral
problems of the workmen are in question, the baker, tailor, mason,
plumber, electrician, and so on, have many interests which are
identical; but practically it turned out that one group had little
interest in its neighbour groups, and oftentimes even strongly
conflicting interests were discovered. Thus this mixed organization
declined in favour of labour societies which comprised members of
76.
one and onlyone trade, so that at the present time the Knights of
Labour are said to number only 200,000 and their importance is
greatly reduced. It is still undoubted that the idealistic formulation in
which they presented the interests of labour to the nation has done
much to arouse the public conscience.
At the present time the typical form of organization is the trades-
union, and between the independent and the federated trades-
unions there is no fundamental difference. There are to-day over
two million working-men united in trades-unions; the number
increases daily. And this number, which comprises only two-fifths of
all wage-earners, is kept down, not because only two-fifths of the
members of each trade can agree to unite, but because many trades
exist which are not amenable to such organization; the unions
include almost all men working in some of the most important
trades. The higher the employment and the more it demands of
preparation, the stronger is the organization of the employed.
Printers, for instance, almost all belong to their union, and in the
building and tobacco trades there are very few who are not
members. The miners’ union includes about 200,000 men, who
represent a population of about a million souls. On the other hand, it
would be useless and impossible to perfect a close organization
where new individuals can be brought in any day and put to work
without any experience or training; thus ordinary day-labourers are
not organized. The number of two million thus represents the most
important trades, and includes the most skilled workers.
The oldest trades-union in America is the International Typographical
Union, which began in 1850. It is to be noticed at once that the
distinction between national and international trades-unions is a
wholly superficial one, for in the hundreds of so-called international
unions there has been no effort to stretch out across the ocean.
“International” means only that citizens of Canada and, in a few
cases, of Mexico are admitted to membership. It has been the
experience of other countries, too, that the printing trades were the
first to organize. In America the hatmakers followed in 1854, the
iron founders in 1859, and the number of organized trades increased
77.
rapidly during thesixties and seventies. The special representation
of local interests soon demanded, on the one hand, the division of
the larger societies into local groups, and, on the other, the affiliation
of the larger societies having somewhat similar interests. Thus it has
come about that each locality has its local union, and these unions
are affiliated in state organizations for purposes of state legislation
and completely unified in national or international organizations. On
the other hand, the unions belonging to different trades are pledged
locally and nationally to mutual support. But here it is no longer a
question, as with the Knights of Labour, of the mixing up of diverse
interests, but of systematic mutual aid on practical lines.
The largest union of this sort is the American Federation of Labour,
which began its existence in Pittsburg in 1881, and has organized a
veritable labour republic. The Federation took warning at the outset
from the sad fate of previous federations, and resolved to play no
part in politics, but to devote itself exclusively to industrial questions.
It recognized the industrial autonomy and the special character of
each affiliating trades-union, but hoped to gain definite results by
co-operation. They first demanded an eight-hour day and aimed to
forbid the employment of children under fourteen years of age, to
prevent the competition of prison labour and the importation of
contract labour; they asked for a change in laws relating to the
responsibility of factory owners and for the organization of societies,
for the establishment of government bureaus for labour statistics,
and much else of a similar sort. At first the Federation had bitter
quarrels with the Knights of Labour, and perhaps even as bitter a
one with socialistic visionaries in its own ranks. But a firm and
healthy basis was soon established, and since the Federation
assisted in every way the formation of local, provincial, and state
organizations, the parts grew with the help of the whole and the
whole with the help of the parts. To-day the Federation includes 111
international trades-unions with 29 state organizations, 542 central
organizations for cities, and also 1,850 local unions which are
outside of any national or international organizations. The interests
of this Federation are represented by 250 weekly and monthly
78.
papers. The headoffice is naturally Washington, where the federal
government has its seat. Gompers is its indefatigable president.
Outside of this Federation are all the trades-unions of railway
employees and several unions of masons and stonecutters. The
railway employees have always held aloof; their union dates from
1893, and is said to comprise 200,000 men.
The trades-unions are not open to every one; each member has to
pay his initiation fees and make contributions to the local union, and
through it to the general organization. Many of the trades-unions
even require an examination for entrance; thus the conditions for
admission into the union of electrical workers are so difficult that
membership is recognized among the employers themselves as the
surest evidence of a working-man’s competence. Every member is
further pledged to attend the regular meetings of the local branch,
and in order that these local societies may not be too unwieldy, they
are generally divided into districts when the number of members
becomes too great to admit of all meeting together. The cigarmakers
of the City of New York, for example, have a trades-union of 6,000
members, which is divided into ten smaller bodies. Every single
society in the country has its own officials. If the work of the official
takes all his time, he receives a salary equal to the regular pay for
work in his trade. The small organizations send delegates to the
state and national federations; and wherever these provincial or
federal affiliations represent different trades, each of these trades
has its own representative, and all decisions are made with that
technical formality which the American masters so well. In
accordance with this parliamentary rigour, every member is
absolutely pledged to comply with the decisions of the delegates.
Any one who refuses to obey when a strike is ordered thereby loses
all his rights.
The rights enjoyed by the members of the trades-unions are in fact
considerable. Firstly, the local union is a club and an employment
agency, and especially in large cities these two functions are very
important for the American working-man. Then there are the
arrangements for insurance and aid. Thus the general union of
79.
cigarmakers of thecountry, which combines 414 local unions having
a total membership of 34,000 men, has given in the last twenty
years $838,000 for the support of strikes, $1,453,000 for aid to ill
members, $794,000 for the families of deceased members, $735,000
for travelling expenses, and $917,000 for unemployed members; and
most of the large unions could show similar figures. Yet these are
the lesser advantages. The really decisive thing is the concessions
which have been won in the economic fight, and which could never
have been gotten by the working-men individually. Nevertheless, to-
day not a few men hold off from the unions and get rid of paying
their dues, because they know that whatever organized labour can
achieve, will also help those who stay outside.
The main contention of these trades-unions refers to legislation and
wages, and no small part of their work goes in fighting for their own
existence—that is, in fighting for the recognition of the union
labourer as opposed to the non-union man—a factor which doubtless
is becoming more and more important in the industrial disputes.
Many a strike has not had wages or short hours of labour or the like
in view, but has aimed solely to force the employers officially to
recognize the trades-unions, to make contracts with the union
delegates rather than with individual men, and to exclude all non-
union labourers.
The newly introduced contention for the union label is in the same
class. The labels were first used in San Francisco, where it was
aimed to exclude the Chinese workmen from competition with
Americans. Now the labels are used all over the country. Every box
of cigars, every brick, hat, or piano made in factories which employ
union labour, bears the copyrighted device which assures the
purchasing public that the wares were made under approved social
and political conditions. The absence of the label is supposed to be a
warning; but for the population of ten millions who are connected
with labour unions, it is more than a warning; it is an invitation to
boycott, and this is undoubtedly felt as a considerable pressure by
manufacturers. The more the factories are thus compelled to
concede to the unions, and the more inducements the unions thus
80.
offer to prospectivemembers, and the faster therefore these come
in, the more power the unions acquire. So the label has become to-
day a most effective weapon of the unions.
But this is only the means to an end. We must consider these ends
themselves, and first of all labour legislation. Most striking and yet
historically necessary is the diversity in the statutes of different
states, which was formerly very great but is gradually diminishing.
The New England states, and especially Massachusetts, have gone
first, and still not so fast as public opinion has often desired. In the
thirties there were many lively fights for the legislative regulation of
the working hours in factories, and yet even the ten hours a day for
women was not established until much later; on the other hand, the
employment of children in factories was legislated on at that time,
and in this direction the movement progressed more rapidly.
A considerable step was taken in 1869, when Massachusetts
established at the expense of the state a bureau for labour statistics,
the first in the world; this was required to work up every year a
report on all phases of the labour question—economic, industrial,
social, hygienic, educational, and political. One state after another
imitated this statistical bureau, and especially it led to the
establishment of the Department of Labour at Washington, which
has already had a world-wide influence. During the seventies there
followed strict laws for the supervision of factories, for precautionary
measures, and hygienic improvements. Most of the other states
came after, but none departed widely from the example of
Massachusetts, which was also the first state to make repeated
reductions in the working-day. Here it followed the example of the
federal government. To be sure, the reduction of the working-day
among federal employees was first merely a political catering to the
labour vote, but the Federation kept to the point and the separate
states followed. Twenty-nine states now prescribe eight hours as the
day for all public employees and the federal government does the
same.
81.
The legislative changesin the judicial sphere have been also of
importance for trades-unions. According to Old English law at the
beginning of the nineteenth century, it was conspiracy for workmen
to unite for the purposes which the trades-unions to-day hold before
themselves. This doctrine of conspiracy, which to be sure from the
beginning depended largely on the arbitrary interpretation of the
judges, has been weakened from time to time through the century,
and has finally given away to legal conceptions which put no
obstacles in the way of the peaceful alliance of working-men for the
purpose of obtaining better conditions of labour. They especially
regard the strike as lawful so long as violence is not resorted to.
Nearly all states have now passed laws which so narrow the old
conception of criminal conspiracy that it no longer stands in the way
of trades-unions. Other legal provisions concern the company stores.
In some mining districts far removed from public shops, the
company store may still be found, where the company buys the
articles needed by its employees and sells these things to them at a
high price. But nearly every state has legally done away with this
system; it was, indeed, one of the earliest demands of the trades-
unions.
There have been great improvements too in legislation relating to
the responsibility of employees. The Anglo-Saxon law makes an
employer responsible for injury suffered by the workmen by reason
of his work, but not responsible if the injuries are due to the
carelessness of a fellow-workman. The penalty fell then on the one
who had neglected his duty. It was said that the workman on taking
up his duties must have known what the dangers were. But the
more complicated the conditions of labour have become, the more
the security of any individual has depended on a great many fellow-
labourers who could not be identified, so that the old law became
meaningless. Therefore, the pressure of trades-unions has in the last
half century steadily altered and improved the law in this respect.
American state law to-day virtually recognizes the responsibility of
the employer for every accident, even when due to the carelessness
of some other labourer than the one injured.
82.
Welcome to ourwebsite – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com