RESTful Web API Design with Node.js - Second Edition - Valentin Bojinov - E-Book

RESTful Web API Design with Node.js - Second Edition E-Book

Valentin Bojinov

0,0
26,39 €

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

Mehr erfahren.
Beschreibung

Design and implement efficient RESTful solutions with this practical hands-on guide

About This Book

  • Create a fully featured RESTful API solution from scratch.
  • Learn how to leverage Node.JS, Express, MongoDB and NoSQL datastores to give an extra edge to your REST API design.
  • Use this practical guide to integrate MongoDB in your Node.js application.

Who This Book Is For

The ideal target audience for this book is web developers who have some experience with RESTful services. Familiarity with basic JavaScript programming techniques is required. No prior experience with Node.JS or Express.js is required.

What You Will Learn

  • Install, develop, and test your own Node.js user modules
  • Comprehend the differences between an HTTP and a RESTful application
  • Optimize RESTful service URI routing with best practices
  • Eliminate third-party dependencies in your tests with mocking
  • Learn about NoSQL data stores and integrate MongoDB in your Node.js application with Mongoose
  • Secure your services with NoSQL database integration within Node.js applications
  • Enrich your development skills to create scalable, server-side, RESTful applications based on the Node.js platform

In Detail

In this era of cloud computing, every data provisioning solution is built in a scalable and fail-safe way. Thus, when building RESTful services, the right choice for the underlying platform is vital. Node.js, with its asynchronous, event-driven architecture, is exactly the right choice to build RESTful APIs.

This book will help you enrich your development skills to create scalable, server-side, RESTful applications based on the Node.js platform.

Starting with the fundamentals of REST, you will understand why RESTful web services are better data provisioning solution than other technologies. You will start setting up a development environment by installing Node.js, Express.js, and other modules. Next, you will write a simple HTTP request handler and create and test Node.js modules using automated tests and mock objects. You will then have to choose the most appropriate data storage type, having options between a key/value or document data store, and also you will implement automated tests for it. This module will evolve chapter by chapter until it turns into a full-fledged and secure Restful service.

Style and approach

Create state of the art RESTful API solutions leveraging Node.JS 4.x.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 151

Veröffentlichungsjahr: 2016

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.



Table of Contents

RESTful Web API Design with Node.js - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. 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 - use the standard HTTP methods
Principle 4 - resources can have multiple representations
Principle 5 - communicate statelessly
The REST goals
Separation of the representation and the resource
Visibility
Reliability
Scalability and performance
Working with WADL
Taking advantage of the existing infrastructure
Summary
2. Getting Started with Node.js
Installing Node.js
Node Package Manager
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
Microsoft Azure
Nodejitsu
Self-test questions
Summary
3. Building a Typical Web API
Specifying the API
Implementing routes
Querying the API
Content negotiation
Cross-origin resource sharing
API versioning
Self-test questions
Summary
4. Using NoSQL Databases
Key/value store - LevelDB
Document store - MongoDB
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
Content delivery network
Self-test questions
Summary
5. Implementing a Fully-Fledged RESTful Service
Extensibility and versioning
Working with arbitrary data
Linking
Implementing paging and filtering
Caching
Supplying the Cache-Control header in Express applications
Discovering and exploring RESTful services
Self-test questions
Summary
6. Keeping the Bad Guys Out
Authentication
Basic authentication
Passport
Passport's basic authentication strategy
Passport's third-party authentication strategies
Authorization
Transport Layer Security
Self-test questions
Summary

RESTful Web API Design with Node.js - Second Edition

RESTful Web API Design with Node.js - Second Edition

Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: March 2015

Second edition: May 2016

Production reference: 1200516

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B32PB, UK.

ISBN 978-1-78646-913-7

www.packtpub.com

Credits

Author

Valentin Bojinov

Copy Editor

Charlotte Carneiro

Reviewer

Huseyin BABAL

Project Coordinator

Sanchita Mandal

Commissioning Editor

Amarabha Banerjee

Proofreader

Safis Editing

Acquisition Editor

Reshma Raman

Indexer

Hemangini Bari

Content Development Editor

 Shali Deeraj

Production Coordinator

Melwyn D'sa

Technical Editor

Prajakta Mhatre

Cover Work

Melwyn D'sa

About the Author

Valentin Bojinov studied computer programming at the Technological School of Electronic Systems in Sofia, Bulgaria, a college within the Technical University of Sofia. He was introduced to programming there and realized that his career would be in research and development. He holds a BSc in telecommunication and information engineering. Then, his interest in data transmission grew, and he ventured into B2B (business-to-business) communication. He is currently pursuing his MSc in software development. Valentin is an expert in Java, SOAP, RESTful web services, and B2B integration.

A few years after he started his career as a .NET developer, he realized that B2B and SOA were his passion. He then moved to SAP, where he contributed to the development of the web services stack of the SAP JEE platform. He currently works as a senior Java developer for the Bulgarian branch of Seeburger AG, a leader in the B2B and MFT solutions market. There, he develops and maintains several B2B communication adapters, including web services and SAP adapters.

I would like to take the opportunity to thank my soulmate Galya for putting up with me and with my decision to work on this title. Also, many thanks to my lovely parents, my dad Emil for encouraging me to study computers 20 years ago, and to mummy Anka for always being there for me! Special thanks to all my mentors from TUES for showing me how to learn efficiently and to never give up, the credit here goes mainly to Lubomir Chorbadjiev. I also have to mention my extraordinary colleagues I had the chance to study with! Guys, thanks for always being such good friends and experts! I know I haven’t recently shown on our regular monthly gathering, so next time beer is on me!

About the Reviewer

Huseyin BABAL is an enthusiast full stack developer since 2007 who mainly develops web applications by using Java, Node.js and PHP on the backend; AngularJS and Twitter Bootstrap on the frontend; and Elasticsearch and MongoDB for some research projects. He is the author of Node.js in Action on Udemy with 1500+ students. He is also interested in DevOps engineering and applies continuous delivery principles to his projects. He writes tutorials about full stack development on Tuts+ and Java Code Geeks and shares his experiences at public conferences.

Besides the computer world, he lives in Istanbul with his wonderful wife and two cockatiels. He likes to spend his spare time with his wife by walking at least 1 hour per day, visiting different places, watching cartoons, and going on summer holidays.

www.PacktPub.com

eBooks, discount offers, and more

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.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

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!

What this book covers

Chapter 1, REST – What You Did Not Know, gives you a brief introduction into 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, 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.

What you need for this book

The following software is required to test the code present in this book:

Node.jsEnide developer studio or the Nodeclipse plugin for the Eclipse IDESoapUIOpenSSL

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. Knowledge of REST would be an added advantage but is definitely not a necessity.

Conventions

In this book, you will find a number of text styles 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 table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "All Node.js modules contain a package.json descriptor file."

A block of code is set as follows:

"dependencies": {     "url": "0.1.x",     "express": "4.7.x" }

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

nodeunit test-math.js

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Let's start by creating a workspace in Enide Studio. Navigate to File | New | Node.js Project and enter the name of your first project."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

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

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged into your Packt account. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-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-Second-Edition/tree/master. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. REST – What You Did Not Know

Nowadays, topics such as cloud computing and mobile device service feeds, as well as other data sources driven by cutting-edge, scalable, stateless, and modern technologies such as RESTful web services, leave the impression that REST was invented recently. Well, to be honest, it definitely was not! In fact, REST has been here since the end of the 20th century.

This chapter will walk you through REST's fundamental principles, and it will explain how REST couples with the HTTP protocol. You will look into the five key principles that need to be considered while turning an HTTP application into a RESTful-service-enabled application. You will also look at the differences in describing RESTful and classic 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 fundamentalsREST with HTTPEssential differences in the description and discovery of RESTful services compared to classical SOAP-based servicesTaking 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.

Note

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_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 resourceEach resource is identifiable by a unique identifier (URI)Use the standard HTTP methodsResources can have multiple representationsCommunicate statelessly

Principle 1 - everything is a resource

To understand this principle, one must conceive the idea of representing data by a specific format and not by a physical file. Each piece of data available on the Internet has a format that could be described by a content type. For example, JPEG images; MPEG videos; HTML, XML, and 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 reduce the risk of logical errors in your programs to a minimum.

Here are a few sample examples of such URIs:

http://www.mydatastore.com/images/vacation/2014/summerhttp://www.mydatastore.com/videos/vacation/2014/winterhttp://www.mydatastore.com/data/documents/balance?format=xmlhttp://www.mydatastore.com/data/archives/2014

These human-readable URIs expose different types of resources in a straightforward manner. In the example, it is quite clear that the media types of these resources are as follows:

ImagesVideosXML documentsSome kinds of binary archive documents

Principle 3 - use the standard HTTP methods

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

GETPOSTPUTDELETEHEADOPTIONSTRACECONNECT

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

Response status code

GET

Requests an existing resource

"200 OK" if the resource exists, "404 Not Found" if it does not exist, and "500 Internal Server Error" for other errors

PUT