RESTful Web API Design With Node - Js - Second Edition - Sample Chapter
RESTful Web API Design With Node - Js - Second Edition - Sample Chapter
Second Edition
$ 29.99 US
19.99 UK
P U B L I S H I N G
Valentin Bojinov
Second Edition
ee
Sa
m
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Valentin Bojinov
Preface
RESTful services have become the de facto standard data feed providers for social services,
news feeds, and mobile devices. They deliver a large amount of data to millions of users;
therefore, they need to address high-availability requirements such as reliability and
scalability. This book will show you how to utilize the Node.js platform to implement a
robust and performant data service. By the end of the book you will have learned how to
implement a real-life RESTful service, taking advantage of the modern NoSQL database for
serving both JSON and binary content. Important topics such as correct URI structuring and
security features are also covered with detailed examples, showing you everything you
need to know to start implementing robust RESTful APIs serving content for your
applications!
Chapter 2, Getting Started with Node.js, teaches you how to install Node.js and how to
work with its package manager to install modules, develop your first HTTP server
application, and write automated unit tests for the HTTP handler by using mock request
objects.
Chapter 3, Building a Typical Web API, teaches you how to structure your application using
human-readable URL and URI parameters and develop a read-only RESTful service
application using the filesystem as storage.
Chapter 4, Using NoSQL Databases, explains how to use LevelDB and MongoDB NoSQL
databases, understand the difference between key/value and document data stores, and
write automated tests for NoSQL user defined modules.
Chapter 5, Implementing a Full-Fledged RESTful Service, implements a production-ready
RESTful service that uses NoSQL to store its data. You will also learn how to handle binary
data and how to version an API while it evolves.
Chapter 6 , Keeping the Bad Guys Out, explains how to restrict access to your data by
choosing an appropriate authentication approach, protect data leakage with transport layer
security.
REST fundamentals
It actually happened back in 1999, when a request for comments was submitted to the
Internet Engineering Task Force (IETF: http://www.ietf.org/) via RFC 2616:
Hypertext Transfer Protocol-HTTP/1.1. One of its authors, Roy Fielding, later defined a
set of principles built around the HTTP and URI standards. This gave birth to REST as we
know it today.
These definitions were given in Chapter 5, Representational State Transfer
(REST), of Fielding's dissertation called Architectural Styles and the Design of
Network-based Software Architectures. The dissertation is still available at
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_a
rch_style.htm.
Let's look at the key principles around the HTTP and URI standards, sticking to which will
make your HTTP application a RESTful-service-enabled application:
Everything is a resource
Each resource is identifiable by a unique identifier (URI)
Use the standard HTTP methods
Resources can have multiple representations
Communicate statelessly
[8]
Chapter 1
[9]
TRACE
CONNECT
The first four of them feel just natural in the context of resources, especially when defining
actions for resource data manipulation. Let's make a parallel with relative SQL databases
where the native language for data manipulation is CRUD (short for Create, Read, Update,
and Delete) originating from the different types of SQL statements: INSERT, SELECT,
UPDATE, and DELETE, respectively. In the same manner, if you apply the REST principles
correctly, the HTTP verbs should be used as shown here:
HTTP
verb
Action
GET
Requests an existing
resource
PUT
Updates a resource or
creates it as an identifier
provided from the client
POST
DELETE
Deletes a resource
Note that a resource can be created by either of POST or PUT HTTP verbs. When a resource
has to be created under a specific URI with an identifier provided by the client, then PUT is
the appropriate action:
PUT /data/documents/balance/22082014 HTTP/1.1
Content-Type: text/xml
Host: www.mydatastore.com
<?xml version="1.0" encoding="utf-8"?>
<balance date="22082014">
[ 10 ]
Chapter 1
<Item>Sample item</Item>
<price currency="EUR">100</price>
</balance>
HTTP/1.1 201 Created
Content-Type: text/xml
Location: /data/documents/balance/22082014
However, in your application, you may want to leave it up to the server REST application to
decide where to place the newly created resource, and thus create it under an appropriate
but still unknown or non-existing location.
For instance, in our example, we might want the server to create the date part of the URI
based on the current date. In such cases, it is perfectly fine to use the POST verb to the main
resource URI and let the server respond with the location of the newly created resource:
POST /data/documents/balance HTTP/1.1
Content-Type: text/xml
Host: www.mydatastore.com
<?xml version="1.0" encoding="utf-8"?>
<balance date="22082014">
<Item>Sample item</Item>
<price currency="EUR">100</price>
</balance>
HTTP/1.1 201 Created
Content-Type: text/xml
Location: /data/documents/balance
[ 11 ]
[ 12 ]
Chapter 1
Now that you know that REST is around 15 years old, a sensible question would be, why
has it become so popular just quite recently? My answer to the question is that we as
developers usually reject simple, straightforward approaches, and most of the time, prefer
spending more time on turning already complex solutions into even more complex and
sophisticated ones.
Take classical SOAP web services for example. Their various WS-* specifications are so
many and sometimes so loosely defined, that in order to make different solutions from
different vendors interoperable, a separate specification WS-Basic Profile has been
introduced.It defines extra interoperability rules in order to ensure that all WS-*
specifications in SOAP-based web services can work together.
When it comes to transporting binary data with classical web services over HTTP, things
get even more complexas SOAP-based web services provide different ways of
transporting binary data. Each way is defined in other sets of specifications such as SOAP
with Attachment References (SwaRef) and Message Transmission Optimization
Mechanism (MTOM). All this complexity was caused mainly because the initial idea of the
web service was to execute business logic remotely, not to transport large amounts of data.
Well, I personally think that when it comes to data transfer, things should not be that
complex. This is where REST comes into play, by introducing the concept of resources and a
standard means for manipulating them.
[ 13 ]
For instance, let's assume that at server side, we have balance resources stored in an XML
format. We can have an API that allows a consumer to request the resource in various
formats, such as application/json, application/zip, application/octet-stream,
and so on.
It would be up to the API itself to load the requested resource, transform it into the
requested type (for example, JSON or XML), and either use ZIP to compress it or directly
flush it to the HTTP response output.
The caller can make use of the Accept HTTP header to specify the expected media type of
the response data. So, if we want to request our balance data inserted in the previous
section in XML format, the following request should be executed:
GET /data/balance/22082014 HTTP/1.1
Host: my-computer-hostname
Accept: text/xml
HTTP/1.1 200 OK
Content-Type: text/xml
Content-Length: 140
<?xml version="1.0" encoding="utf-8"?>
<balance date="22082014">
<Item>Sample item</Item>
<price currency="EUR">100</price>
</balance>
[ 14 ]
Chapter 1
To request the same balance in JSON format, the Accept header needs to be set to
application/json:
GET /data/balance/22082014 HTTP/1.1
Host: my-computer-hostname
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 120
{
"balance": {
"date": "22082014",
"Item": "Sample item",
"price": {
"-currency": "EUR",
"#text": "100"
}
}
}
Visibility
REST is designed to be visible and simple. Visibility of the service means that every aspect
of it should self-descriptive and follow the natural HTTP language according to principles
3, 4, and 5.
Visibility in the context of the outer world would mean that monitoring applications would
be interested only in the HTTP communication between the REST service and the caller.
Since the requests and responses are stateless and atomic, nothing more is needed to flow
the behavior of the application and to understand whether anything has gone wrong.
Remember that caching reduces the visibility of your restful applications
and in general should be avoided, unless needed for serving resources
subject to large amounts of callers. In such cases, caching may be an
option, after carefully evaluating the possible consequences of serving
obsolete data.
[ 15 ]
Reliability
Before talking about reliability, we need to define which HTTP methods are safe and which
are idempotent in the REST context. So, let's first define what safe and idempotent methods
are:
An HTTP method is considered to be safe provided that when requested, it does
not modify or cause any side effects on the state of the resource
An HTTP method is considered to be idempotent if its response is always the
same, no matter how many times it is requested
The following table lists shows you which HTTP method is safe and which is idempotent:
HTTP Method Safe Idempotent
GET
Yes
Yes
POST
No
No
PUT
No
Yes
DELETE
No
Yes
[ 16 ]
Chapter 1
[ 17 ]
</resource>
</resources>
</application>
This extract of a WADL file shows how application-exposing resources are described.
Basically, each resource must be a part of an application. The resource provides the URI
where it is located with the base attribute, and describes each of its supported HTTP
methods in a method. Additionally, an optional doc element can be used at resource and
application to provide additional documentation about the service and its operations.
Though WADL is optional, it significantly reduces the efforts of discovering RESTful
services.
Summary
In this chapter, you learned about foundation of a REST, looking at the five key principles
that turn a web application into a REST-enabled application. We made a slight comparison
between RESTful services and classical SOAP web services, and finally took a look at how
RESTful services are described and how we can simplify the discovery of the services we
develop.
Now that you know the basics, we are ready to dive into the Node.js way of implementing
RESTful services. In the next chapter, you will learn about the essentials of Node.js and the
accompanying tools that are necessary to use and understand in order to build a real-life
fully-fledged web service.
[ 18 ]
Get more information RESTful Web API Design with Node.js Second Edition
www.PacktPub.com
Stay Connected: