RESTful Web API Design with Node.js 10, Third Edition - Valentin Bojinov - E-Book

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

Valentin Bojinov

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 168

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



RESTful Web API Design with Node.js 10Third Edition

 

 

 

 

 

 

 

Learn to create robust RESTful web services with Node.js, MongoDB, and Express.js

 

 

 

 

 

 

 

 

Valentin Bojinov

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

RESTful Web API Design with Node.js 10 Third Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Reshma RamanContent Development Editor:Francis CarneiroTechnical Editor:Sachin SunilkumarCopy Editor:Shaila KusanaleProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Mariammal ChettiyarGraphics:Jason MonteiroProduction Coordinator:Shraddha Falebhai

First published: October 2016 Second edition: October 2017 Third edition: April 2018

Production reference: 1300418

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78862-332-2

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Valentin Bojinov studied computer science at the Technological School of Electronic Systems in Sofia, Bulgaria, a college within the Technical University of Sofia. He holds a B.Sc. in telecommunication and information engineering. Valentin is an expert in Java, SOAP, RESTful web services, and B2B integration. He specializes B2B Integration and Service Oriented Architecture and currently works as an Senior Integration Consultant in an UK consultancy company Estafet Limited.

I would like thank my  my dad Emil, for encouraging me to study programming almost 20 years ago, and to mummy Anka, for always being there for me! Special thanks to all my mentors from school for showing me how to learn efficiently and to never give up. I also have to mention my extraordinary schoolmates I had the chance to study with!

About the reviewers

Amit Kothari is a full-stack developer based in Melbourne, Australia. He has more than 12 years experience in designing and developing software systems and has worked on a wide range of projects across various domains including telecommunication, retails, banking and finance. Amit is also the co-author of the book - Chatbots for eCommerce: Learn how to build a virtual shopping assistant.

 

 

 

Erina has completed her master's and proactively working as an assistant professor in the computer science department of Thakur college, Mumbai. Her enthusiasm in web technologies inspires her to contribute for freelance JavaScript projects, especially on Node.js. Her research topics were SDN and IoT, which according to her create amazing solutions for various web technologies when they are used together. Nowadays, she focuses on blockchain and enjoys fiddling with its concepts in JavaScript.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

RESTful Web API Design with Node.js 10 Third Edition

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

REST – What You Did Not Know

REST fundamentals

Principle 1 – Everything is a resource

Principle 2 – Each resource is identifiable by a unique identifier

Principle 3 – Manipulate resources via standard HTTP methods

Principle 4 – Resources can have multiple representations

Principle 5 – Communicate with resources in a stateless manner

The REST goals

Separation of the representation and the resource

Visibility

Reliability

Scalability and performance

Working with WADL

Documenting RESTful APIs with Swagger

Taking advantage of the existing infrastructure

Summary

Getting Started with Node.js

Installing Node.js

Npm

Installing the Express framework and other modules

Setting up a development environment

Handling HTTP requests

Modularizing code

Testing Node.js

Working with mock objects

Deploying an application

Nodejitsu

Microsoft Azure

Heroku

Self-test questions

Summary

Building a Typical Web API

Specifying the API

Implementing routes

Querying the API using test data

Content negotiation

API versioning

Self-test questions

Summary

Using NoSQL Databases

MongoDB – a document store database

Database modeling with Mongoose

Testing a Mongoose model with Mocha

Creating a user-defined model around a Mongoose model

Wiring up a NoSQL database module to Express

Self-test questions

Summary

Restful API Design Guidelines

Endpoint URLs and HTTP status codes best practices

Extensibility and versioning

Linked data

Summary

Implementing a Full Fledged RESTful Service

Working with arbitrary data

Linking

Implementing paging and filtering

Caching

Supplying the Cache-Control header in Express applications

Discovering and exploring RESTful services

Summary

Preparing a RESTful API for Production

Documenting RESTful APIs

Testing RESTful APIs with Mocha

The microservices revolution

Summary

Consuming a RESTful API

Consuming RESTful services with jQuery

Troubleshooting and identifying problems on the wire

Cross Origin Resource Sharing

Content Delivery Networks

Handling HTTP status codes on the client side

Summary

Securing the Application

Authentication

Basic authentication

Passport

Passport's basic authentication strategy

Passport's OAuth Strategy

Passport's third-party authentication strategies

Authorization

Transport layer security

Self-test questions

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

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. Thus, 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 this book, you will have learned how to implement a real-life RESTful service, taking advantage of the modern NoSQL database to serve 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 the robust RESTful APIs that serve content to your applications.

Who this book is for

This book targets developers who want to enrich their development skills by learning how to develop scalable, server-side, RESTful applications based on the Node.js platform. You also need to be aware of HTTP communication concepts and should have a working knowledge of the JavaScript language. Keep in mind that this is not a book that will teach you how to program in JavaScript. Knowledge of REST will be an added advantage but is definitely not a necessity.

What this book covers

Chapter 1, REST – What You Did Not Know, gives you a brief introduction to the history of REST and how it couples with the HTTP protocol.

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. You'll also develop your first HTTP server application and write automated unit tests for HTTP handler using mock request objects.

Chapter 3, Building a Typical Web API, takes you through structuring your application using human-readable URL and URI parameters. You will get to develop a read-only RESTful service application, using the filesystem for storage.

 Chapter 4, Using NoSQL Databases, showcases how to use the MongoDB NoSQL database, and explains the foundation of document data stores.

Chapter 5, Restful API Design Guidelines, explains that there are a number of prerequisites that a RESTful API should meet.

Chapter 6, Implementing a Full-Fledged RESTful Service, focuses on implementing a production-ready RESTful service that uses NoSQL to store its data. You will get to learn how to handle binary data and how to version an API while it evolves.

Chapter 7, Preparing a RESTful API for Production, explains that feature complete and full-fledged implementations aren't necessarily production-ready.

Chapter 8, Consuming a RESTful API, showcases a sample frontend client that serves as a consumption reference implementation.

Chapter 9, Securing the Application, covers restricting access to your data by choosing an appropriate authentication approach. You'll then be able to protect data leakage with transport layer security.

To get the most out of this book

Inform the reader of the things that they need to know before they start, and spell out what knowledge you are assuming

Any additional installation instructions and information they need for getting set up

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/RESTful-Web-API-Design-with-Node.js-10-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

 

Conventions used

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database tale names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "This tells npm that our package depends on the URL and express modules."

A block of code is set as follows:

router.get('/v1/item/:itemId', function(request, response, next) { console.log(request.url + ' : querying for ' + request.params.itemId); catalogV1.findItemById(request.params.itemId, response);});router.get('/v1/:categoryId', function(request, response, next) { console.log(request.url + ' : querying for ' + request.params.categoryId); catalogV1.findItemsByCategory(request.params.categoryId, response);});

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

router.get('/v1/:categoryId', function(request, response, next) {

console.log(request.url + ' : querying for ' + request.params.categoryId); catalogV1.findItemsByCategory(request.params.categoryId, response);});

Any command-line input or output is written as follows:

$ npm install -g express

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example:

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

REST – What You Did Not Know

Over the last few years, we have started taking for granted that data sources feeding for content, mobile device service feeds, or cloud computing are all driven by modern technologies, such as RESTful web services. Everybody has been talking about how their stateless model allows applications to scale easily and how it emphasizes on clear decoupling between data provisioning and data consumption. Nowadays, architects have started introducing the concept of microservices, aiming to reduce the complexity in systems by splitting their core components into small independent pieces that simply do a single task. So, enterprise-grade software is about to become a composite of such microservices. This makes it easy to maintain, and allows better life cycle management when new parts need to be introduced. Unsurprisingly, most of the microservices are serviced by RESTful frameworks. This fact may leave the impression that REST was invented sometime in the last decade, but that is far from the truth. In fact, REST has been around since the last decade of the previous century!

This chapter will walk you through the foundation of Representational State Transfer (REST) and will explain how REST couples with the HTTP protocol. You will look into five key principles that have to be considered while turning any HTTP application into a RESTful service-enabled application. You will also look at the differences between describing RESTful and classic Simple Object Access Protocol (SOAP)-based web services. Finally, you will learn how to utilize already-existing infrastructure for your benefit.

In this chapter, we will cover the following topics:

REST fundamentals

REST with HTTP

Essential differences in the description, discovery, and documentation of RESTful services compared to classical SOAP-based services

Taking advantage of existing infrastructure

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 https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf in the fifth chapter, 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_arch_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

)

Resources are manipulated via standard HTTP methods

Resources can have multiple representations

Communicate with resources in a stateless manner

Principle 1 – Everything is a resource

To understand this principle, one must conceive of the idea of representing data by a specific format and not by a physical file containing a bunch of bytes. Each piece of data available on the internet has a format that describes it, known as the content type; for example, JPEG images, MPEG videos, HTML, XML, text documents, and binary data are all resources with the following content types: image/jpeg, video/mpeg, text/html, text/xml, and application/octet-stream.

Principle 2 – Each resource is identifiable by a unique identifier

Since the internet contains so many different resources, they all should be accessible via URIs and should be identified uniquely. Furthermore, the URIs can be in a human-readable format, despite the fact that their consumers are more likely to be software programs rather than ordinary humans.

Human-readable URIs keep data self-descriptive and ease further development against it. This helps you to keep the risk of logical errors in your programs to a minimum.

Here are a few sample examples of such URIs representing different resources in a catalog application:

http://www.mycatalog.com/categories/watches

http://www.mycatalog.com/categories/watches?collection=2018

http://www.mycatalog.com/categories/watches/model-xyz/image

http://www.mycatalog.com/categories/watches/model-xyz/video

http://www.mycatalog.com/archives/2017/categories/watches.zip

These human-readable URIs expose different types of resources in a straightforward manner. In the preceding example URIs, it is quite clear the data is items in a catalog, which are categorized watches. The first link shows all the items in the category. The second shows only the ones that are part of the 2018 collection. Next is a link pointing to the image of the item, followed by a link to a sample video. The last link points to a resource containing items from the previous collection in a ZIP archive. The media types served per each URI are rather easy to identify, with the assumption that the data format of an item is either JSON or XML, so we can easily map the media type of a self-described URL to one of the following:

JSON or XML documents describing the items

Images

Videos

Binary archive documents

Principle 3 – Manipulate resources via standard HTTP methods

The native HTTP protocol (RFC 2616) defines eight actions, also known as HTTP verbs:

GET

POST

PUT

DELETE

HEAD

OPTIONS

TRACE

CONNECT

The first four of them just feel natural in the context of resources, especially when defining actions for data manipulation. Let's make a parallel with relative SQL databases where the native language for data manipulation isCRUD(short forCreate, Read, Update, and Delete), originating from the different types of SQL statements, INSERT,SELECT,UPDATE, andDELETE