Book Image

RESTful Web API Design with Node.js 10 - Third Edition

By : Valentin Bojinov
Book Image

RESTful Web API Design with Node.js 10 - Third Edition

By: Valentin Bojinov

Overview of this book

When building RESTful services, it is really important to choose the right framework. Node.js, with its asynchronous, event-driven architecture, is exactly the right choice for building RESTful APIs. This third edition of RESTful Web API Design with Node.js 10 will teach you to create scalable and rich RESTful applications based on the Node.js platform. You will be introduced to the latest NPM package handler and understand how to use it to customize your RESTful development process. You will begin by understanding the key principle that makes an HTTP application a RESTful-enabled application. After writing a simple HTTP request handler, you will create and test Node.js modules using automated tests and mock objects; explore using the NoSQL database, MongoDB, to store data; and get to grips with using self-descriptive URLs. You’ll learn to set accurate HTTP status codes along with understanding how to keep your applications backward-compatible. Also, while implementing a full-fledged RESTful service, you will use Swagger to document the API and implement automation tests for a REST-enabled endpoint with Mocha. Lastly, you will explore some authentication techniques to secure your application.
Table of Contents (16 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

The REST goals


Now that we've covered the main REST principles, it is time to dive deeper into what can be achieved when they are followed:

  • Separation of the representation and the resource
  • Visibility
  • Reliability
  • Scalability
  • Performance

Separation of the representation and the resource

A resource is just a set of information, and as defined by principle 4, it can have multiple representations; however, its state is atomic. It is up to the caller to specify the desired media type with the Accept header in the HTTP request, and then it is up to the server application to handle the representation accordingly, returning the appropriate content type of the resource together with a relevant HTTP status code:

  • HTTP 200 OK in the case of success
  • HTTP 400 Bad Request if an unsupported format is given or for any other invalid request information
  • HTTP 406 Not Acceptable if an unsupported media type is requested
  • HTTP 500 Internal Server Error when something unexpected happens during the request processing

Let's assume that, at server side, we have items resources stored in an XML format. We can have an API that allows a consumer to request the item resources in various formats, such as application/xml, 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 would make use of the Accept HTTP header to specify the media type of the response they expect. So, if we want to request our item data inserted in the previous section in XML format, the following request should be executed:

GET /category/watches/watch-abc HTTP/1.1 
Host: my-computer-hostname 
Accept: text/xml 
 
HTTP/1.1 200 OK 
Content-Type: text/xml 
<?xml version="1.0" encoding="utf-8"?>
<Item category="watch">
    <Brand>...</Brand>
    </Price></Price>
</Item>

To request the same item in JSON format, the Accept header needs to be set to application/json:

GET /categoery/watches/watch-abc HTTP/1.1 
Host: my-computer-hostname 
Accept: application/json 
 
HTTP/1.1 200 OK 
Content-Type: application/json 
{
  "watch": {
    "id": ""watch-abc"",
    "brand": "...",
    "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.

Note

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.

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 stays the same, regardless of the number of times it is requested, am idempotent request always gives back the same request, if repeated identically.

The following table lists which HTTP methods are safe and which are idempotent:

HTTP method

Safe

Idempotent

GET

Yes

Yes

POST

No

No

PUT

No

Yes

DELETE

No

Yes

 

Consumers should consider operation's safety and the idempotence features in order to be served reliably.

Scalability and performance

So far, we stressed the importance of having stateless behavior for a RESTful web application. The World Wide Web (WWW) is an enormous universe, containing huge amount of data and a lot of users, eager to get that data. The evolution of the WWW has brought the requirement that applications should scale easily as their load increases. Scaling applications that have a state is difficult to achieve, especially when zero or close-to-zero operational downtime is expected.

That's why staying stateless is crucial for any application that needs to scale. In the best-case scenario, scaling your application would require you to put another piece of hardware for a load balancer, or bring another instance in your cloud environment. There would be no need for the different nodes to sync between each other, as they should not care about the state at all. Scalability is all about serving all your clients in an acceptable amount of time. Its main idea is to keep your application running and to prevent Denial of Service (DoS) caused by a huge amount of incoming requests.

Scalability should not be confused with the performance of an application. Performance is measured by the time needed for a single request to be processed, not by the total number of requests that the application can handle. The asynchronous non-blocking architecture and event-driven design of Node.js make it a logical choice for implementing an application that scales and performs well.