Building Killer RESTful APIs with NodeJs

35
This deck on GitHub @djidja8

description

What makes a RESTful API - RESTful?

Transcript of Building Killer RESTful APIs with NodeJs

Page 2: Building Killer RESTful APIs with NodeJs

Plan:

1. Node.js Overview

2. Express.js Overview

3. About RESTful APIs

4. Show me the code

Page 3: Building Killer RESTful APIs with NodeJs

What is Node.js?

Core module Fs

Core module Http

NPM

NPM: Installing and Importing Modules

Page 4: Building Killer RESTful APIs with NodeJs

Node.js is a cross-platform runtime environment and a library for applications written in JavaScript outside the browser* and is built as a wrapper around Google's V8 JavaScript runtime* and evented IO library 'libuv'

Page 5: Building Killer RESTful APIs with NodeJs

V8 JavaScript runtime:V8 is Google's open source JavaScript engine written in C++ and used in Google's open source browser Chrome

libuv:A cross-platform library that abstracts OS host platform system API for asynchronous (non-blocking) IO that provides an event loop with callback based notifications for I/O and other activities. libuv offers core utilities like timers, non-blocking networking support, asynchronous file system access, child processes and more.

Non-blocking standard libraries:After an IO request, Node.js will continue executing the code that comes after it, then jump back when the result is available: this is highly concurrent, and it works well for IO-bound workloads (but it is not parallelism).

Page 6: Building Killer RESTful APIs with NodeJs

Most APIs speak Streams:The built-in stream module is used by the core libraries and can also be used by user-space modules, while providing a backpressure mechanism to throttle writes for slow consumers

Extensible via C/C++ add-ons:Node.js is extensible and modules can include add-ons written in native code

Provides a package manager and module system:NPM package manager:an online repository of reusable components, with easy installation and version and dependency management

Global scope:Browser JavaScript lifts everything into its global scope, Node.js was designed to have everything being local by default. Exporting is done explicitly, and in case we need to access globals, there is a global object.

Page 7: Building Killer RESTful APIs with NodeJs

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily embeddable in other programs. The REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out...

Page 8: Building Killer RESTful APIs with NodeJs

I/O is provided by simple wrappers around standard POSIX functions. All the methods have asynchronous and synchronous forms, but async is default. With the asynchronous methods there is no guaranteed ordering. So the following code is prone to error:

The correct way to do this is to chain the callbacks:

Page 9: Building Killer RESTful APIs with NodeJs

Node.js installations come with the file system module, fs. For the most part, fs simply provides a wrapper for the standard file operations. The following example uses the fs module to read (async but not streamed) contents of a file into memory

Page 10: Building Killer RESTful APIs with NodeJs

The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. http module never buffers entire requests or responses - async and streaming

Page 11: Building Killer RESTful APIs with NodeJs

NPM is the official package manager for Node.js and is written entirely in JavaScript. It is bundled and installed automatically with the environment and runs through the command line and manages library (modules) dependencies for an application. It also allows full application installations

Page 12: Building Killer RESTful APIs with NodeJs

– NPM:

NPM install and uninstall commands

Page 13: Building Killer RESTful APIs with NodeJs

What is Express.js?

Application

Request and Response

Router

Middleware

Page 14: Building Killer RESTful APIs with NodeJs

is a minimal and flexible node.js web application framework, providing a robust set of features for building single, multi-page and hybrid web applications and pure web APIs.

Page 15: Building Killer RESTful APIs with NodeJs

envEnvironment mode: defaults to NODE_ENV environment variable or "development"

trust proxyset to signify that Express is behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed.

SONP callback nameBy default the JSONP callback name is simply callback, however you may alter this with this setting

JSON replacerJSON replacer callback, null by default

case sensitive | strict routingEnable case sensitivity, disabled by default, treating "/Foo" and "/foo" as the sameEnable strict routing, by default "/foo" and "/foo/" are treated the same by the router

view cacheEnables view template compilation caching, enabled in production by default

view engineThe default engine extension to use when omitted

ViewsThe view directory path, defaulting to "process.cwd() + '/views'"

Page 16: Building Killer RESTful APIs with NodeJs

The Request object is created internally by a HTTP server and passed as the first argument to a 'request' listener

Request object is an EventEmitter with the following events:

'data‘Emitted when a piece of the message body is received

'end‘Emitted exactly once for each request. After that, no more 'data' events will be emitted on the request

'close‘Indicates that the underlaying connection was terminated before response.end() was called or able to flush

Page 17: Building Killer RESTful APIs with NodeJs

Response object is created internally by a HTTP server and is passed as the second parameter to the 'request' event. It is a Writable Stream.

Page 18: Building Killer RESTful APIs with NodeJs

A router is an isolated instance of middleware and routes. Routers can be thought of as "mini" applications only capable of performing middleware and routing, every express application has a builtin app router. Apply the express.Router() to a section of the site using .use() api.

Use route middleware to process requests

Use route middleware to validate parameters using .param()

Use app.route() as a shortcut to the Router to define multiple requests on a route

Page 19: Building Killer RESTful APIs with NodeJs

Middleware is the core concept behind Express.js request processing and routing and is composed from any number of functions that are invoked by the Express.js routing layer before final application request handler is invoked.

*As of 4.x, Express no longer depends on Connect. All of Express' previously included middleware are now in separate repositories. The only included middleware is now express.static(), used to server static files.

Middleware function signature is simple:

Page 20: Building Killer RESTful APIs with NodeJs

Express.js has great built in capabilities to serve static content. The module is able to also gzip compress and/or cache served files, too

Page 21: Building Killer RESTful APIs with NodeJs

Error-handling middleware are defined just like regular middleware, however must be defined with an arity of 4 signature: (error, request, response, next)

Page 22: Building Killer RESTful APIs with NodeJs

error-handling middleware are typically defined very last, below any other app.use() calls...

Page 23: Building Killer RESTful APIs with NodeJs

All of Express' previously (before v4.0) included middleware are now in separate repos. Here are some example libraries:

body-parser - previously bodyParser, json, and urlencoded

compression - previously compress

connect-timeout - previously timeout

csurf - previousy csrf

errorhandler - previously error-handler

method-override - previously method-override

morgan - previously logger

response-time - previously response-time

serve-favicon - previously favicon

Page 24: Building Killer RESTful APIs with NodeJs

Uniform Interface

Stateless

Cacheable

Client-Server

Layered System

Code on Demand (optional)

Example

Page 25: Building Killer RESTful APIs with NodeJs

The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture and enables each part to evolve independently. The four guiding principles of the uniform interface are:

Resource-BasedIndividual resources are identified in requests using URIs as resource identifiers. The resources themselves are conceptually separate from the representations that are returned to the client

Manipulation of Resources Through RepresentationsWhen a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource on the server, provided it has permission to do so

Self-descriptive MessagesEach message includes enough information to describe how to process the message. For example, which parser to invoke may be specified by an Internet media type (previously known as a MIME type)

Hypermedia as the Engine of Application State (HATEOAS)HATEOS is the key constrain that makes web browsing possible. Applicable to APIs but not widely used. It is simple to understand: each response message includes the links to next possible request message.

Page 26: Building Killer RESTful APIs with NodeJs

HAL is designed for building APIs in which clients navigate around the resources by following links. Links are identified by link relations, the lifeblood of a hypermedia API: they are how you tell client developers about what resources are available and how they can be interacted with, and they are how the code they write will select which link to traverse

HAL - Specification

Page 27: Building Killer RESTful APIs with NodeJs

As REST is an acronym for REpresentational State Transfer, statelessness is key. Essentially, what this means is that the necessary state to handle the request is contained within the request itself, whether as part of the URI, query-string parameters, body, or headers

Page 28: Building Killer RESTful APIs with NodeJs

The goal of caching is never having to generate the same response twice. The benefit of doing this is that we gain speed and reduce server load.

Expiration Expires header Cache-Control header

Validation Last-Modified header Etag header

Page 29: Building Killer RESTful APIs with NodeJs

The client-server constraint is based on a principle known as the separation of concerns. It simply requires the existence of a client component that sends requests and a server component that receives requests

Servers and clients may also be replaced and developed independently, as long as the interface is not altered

Page 30: Building Killer RESTful APIs with NodeJs

REST architecture is concived as hierarchical layers of components, limited to communication with their immediate neighbors. A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way.Intermediary servers improve system scalability by enabling load-balancing and by providing shared caches. Layers may also enforce security policies

Page 31: Building Killer RESTful APIs with NodeJs

The optional code-on-demand constraint allows clients to request and execute code from servers. This, in turn, allows the server to deploy new features to clients. The result is improved extensibility and configurability for servers, and improved performance and efficiency for clients

Page 32: Building Killer RESTful APIs with NodeJs
Page 33: Building Killer RESTful APIs with NodeJs
Page 34: Building Killer RESTful APIs with NodeJs

This presentation on GitHub: Building Killer RESTful APIsOriginal Deck/CodeMirror plugin by Irene Ros: deck.js-codemirror

Node.Js Mixu Online book Why Asynchronous? Mastering Node

Express Express Home Page JUnderstanding Express.js A short guide to Connect Middleware

REST APIs REST API Tutorial Restful Exploration HAL - Hypertext Application Language