RESTful Web API Design With Node - Js - Sample Chapter
RESTful Web API Design With Node - Js - Sample Chapter
ee
P U B L I S H I N G
pl
C o m m u n i t y
$ 29.99 US
19.99 UK
Sa
m
Valentin Bojinov
D i s t i l l e d
E x p e r i e n c e
Valentin Bojinov
[1]
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
Communicate statelessly
[2]
Chapter 1
http://www.mydatastore.com/images/vacation/2014/summer
http://www.mydatastore.com/videos/vacation/2014/winter
http://www.mydatastore.com/data/documents/balance?format=xml
http://www.mydatastore.com/data/archives/2014
Images
Videos
XML documents
GET
POST
PUT
DELETE
HEAD
OPTIONS
TRACE
CONNECT
[3]
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
Request an existing
resource
PUT
Create or update a
resource
POST
Update an existing
resource
DELETE
Delete a resource
There is an exception in the usage of the verbs, however. I just mentioned that POST
is used to create a resource. For instance, when a resource has to be created under a
specific URI, then PUT is the appropriate request:
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">
<Item>Sample item</Item>
<price currency="EUR">100</price>
</balance>
HTTP/1.1 201 Created
Content-Type: text/xml
Location: /data/documents/balance/22082014
[4]
Chapter 1
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
[6]
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 humans usually reject simple, straightforward approaches, and most of the
time, we prefer spending more time on turning complex solutions into even more
complex and sophisticated solutions.
Take classical SOAP web services for example. Their various WS-* specifications
are so many and sometimes loosely defined in order to make different solutions
from different vendors interoperable. The WS-* specifications need to be unified by
another specification, WS-BasicProfile.
This mechanism defines extra interoperability rules in order to ensure that all
WS-* specifications in SOAP-based web services transported over HTTP provide
different means of transporting binary data. This is again described in other sets of
specifications such as SOAP with Attachment References (SwaRef) and Message
Transmission Optimisation Mechanism (MTOM), mainly because the initial idea of
the web service was to execute business logic and return its response 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 place by introducing the concept of
resources and standard means to manipulate them.
Visibility
Reliability
Scalability
Performance
[7]
HTTP 400 Bad request if a unsupported content type is requested, or for any
other invalid request
HTTP 500 Internal Server error when something unexpected happens during
the request processing
For instance, let's assume that at the server side, we have balance resources stored in
an XML file. 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. It is the Accept HTTP header that
specifies the expected representation 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>
[8]
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 should 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 you restful
applications and should be avoided.
[9]
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:
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
Chapter 1
[ 11 ]
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 the history of REST, and we made a slight
comparison between RESTful services and classical SOAP Web services. We looked
at the five key principles that would turn our web application into a REST-enabled
application, 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 REST 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 full-fledged web service.
[ 12 ]
www.PacktPub.com
Stay Connected: