Caio Ribeiro Pereira

Building APIs with Node.js

Caio Ribeiro Pereira

São Vicente - SP, São Paulo, Brazil

Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ .

ISBN 978-1-4842-2441-0

e-ISBN 978-1-4842-2442-7

DOI 10.1007/978-1-4842-2442-7

Library of Congress Control Number: 2016961314

© Caio Ribeiro Pereira 2016

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

I dedicate this book to my family who always supports me and has motivated me since the beginning of my life.

Introduction

We live in a time in which the majority of users use different types of devices to connect to the Internet. The most popular devices are smartphones, tablets, and notebooks. Developing systems for different types of devices requires the work of building web services, also known by the name of application program interfaces (APIs).

Basically, the APIs are back-end systems that are designed to work only with data in a centralized manner, allowing client-side applications to be developed separately, to have a unique interface to the final user. These client-side applications are typically mobile apps, desktop applications, or web apps.

Since 2010 Node.js has increasingly proven to be an excellent platform to solve many problems, especially for building REST APIs. The single-thread architecture that performs nonblocking I/O running on top of JavaScript, which is a ubiquitous language in all current browsers, showed good performance in the processing of many kinds of applications. Some large companies, such as LinkedIn and PayPal, have significantly reduced expenses with servers migrating some of their projects to Node.js.

In addition, another advantage of using Node.js, which captivated many developers, is the short learning curve. After all, anyone who has worked with web development already has at least a basic understanding of the JavaScript language.

Who Is This Book For?

This book is intended for developers who have at least a basic knowledge of JavaScript and, especially, those who understand object-oriented programming (OOP), a little bit of client-server architecture, and those with an understanding of the main characteristics of REST APIs.

Mastering these concepts, or at minimum a basic knowledge of them, is essential to fully understand this book.

All the code in this book is written using the latest JavaScript implementation, the ECMAScript 2015 (also called ECMAScript 6, or ES6).

How Should I Use This Book?

Throughout the book, many concepts and codes are going to be presented for you to learn through practice all the theoretical parts of this book. It will guide you in a didactic way in the development of two projects (an API and a web client application), which in the end are both integrated to work as a single project.

It is highly recommended that you follow the book’s instructions step by step, so in the end you can complete the project correctly.

Acknowledgments

Special thanks go to Mrs. Charlotte Bento de Carvalho, my cousin Cláudio Souza, my friends Leandro Alvares da Costa and Bruno Alvares da Costa, Paulo Silveira, and Adriano Almeida. They have had an important role in my life, influencing me to be who I am today, and consequently, to write this book.

Thanks to all the readers from Underground WebDev ( https://udgwebdev.com ); after all, the essence of this book is based on many posts from this blog.

Finally, thank you, dear reader, for purchasing this book.

Contents

  1. Chapter 1:​ Introduction to Node.​js
    1. What Is Node.​js?​
    2. Main Features
      1. Single-Thread Architecture
      2. Event-Loop
    3. Why Do I Need to Learn Node.​js?​
    4. Conclusion
  2. Chapter 2:​ Setting Up the Environment
    1. Node.​js Standard Installation
      1. About io.​js and Node.​js Merge
    2. Node.​js Installation Via NVM
      1. Set Up NVM
      2. Top NVM Commands
      3. Installing Node.​js Via NVM
    3. Conclusion
  3. Chapter 3:​ Managing Modules with NPM
    1. What Does NPM Do?​
    2. Top NPM Commands
    3. Understanding the package.​json File
    4. NPM Task Automation
    5. Conclusion
  4. Chapter 4:​ Building an API
    1. Introduction to Express
    2. Getting Started on the Pilot Project
      1. Pilot Project Source Code
    3. Implementing a Simple and Static Resource
    4. Arranging the Loading of Modules
    5. Conclusion
  5. Chapter 5:​ Working with SQL Databases
    1. Setting Up Sequelize
    2. Creating Models
      1. Model:​ Tasks
      2. Model:​ Users
    3. Conclusion
  6. Chapter 6:​ CRUDify API Resources
    1. Organizing Task Routes
    2. Listing Tasks Via GET
      1. About HTTP Status
    3. Creating Tasks Via POST
    4. Finding a Task Via GET
    5. Updating a Task Via PUT
    6. Deleting a Task Via DELETE
    7. Refactoring Some Middlewares
    8. Creating Users’ Endpoints
    9. Testing Endpoint Access Using Postman
    10. Conclusion
  7. Chapter 7:​ Authenticating Users
    1. Introduction to Passport.​js and JWT
      1. About Passport.​js
      2. About JWT
    2. Installing Passport and JWT
    3. Implementing JWT Authentication
    4. Generating Tokens for Authenticated Users
    5. Conclusion
  8. Chapter 8:​ Testing the Application:​ Part 1
    1. Setting Up the Test Environment
    2. Writing the First Test
    3. Testing the Authentication Endpoint
    4. Conclusion
  9. Chapter 9:​ Testing the Application:​ Part 2
    1. Testing a Task’s Endpoints
    2. Testing a User’s Endpoints
    3. Conclusion
  10. Chapter 10:​ Documenting the API
    1. Introduction to ApiDoc.​js
    2. Documenting Token Generation
    3. Documenting User Resource
    4. Documenting Tasks Resource
    5. Conclusion
  11. Chapter 11:​ Preparing the Production Environment
    1. Enabling CORS in the API
      1. A Bit More About CORS
    2. Generating Logs
    3. Configuring Parallel Processing Using Cluster Module
      1. Developing Clusters
    4. Compacting Requests Using GZIP Middleware
    5. Installing SSL Support to Use HTTPS
    6. Armoring the API with Helmet
    7. Conclusion
  12. Chapter 12:​ Building the Client-Side App:​ Part 1
    1. Setting Up the App Environment
    2. Creating Sign-in and Signup Views
    3. Writing Sign-in and Signup Components
    4. Conclusion
  13. Chapter 13:​ Building the Client-Side App:​ Part 2
    1. Views and Components for Task’s CRUD
    2. Views and Components for Logged Users
    3. Creating the Main Menu
    4. Treating All Screen Events
    5. Conclusion
  14. Index

About the Author and About the Technical Reviewer

About the Author

A435096_1_En_BookFrontmatter_Figb_HTML.jpg

Caio Ribeiro Pereira is a software engineer from Brazil who love works with Node.js, JavaScript, Meteor, Ruby On Rails, DevOps, and front-end stuffs. He has a bacharelor’s degree in Information Systems, author of the blog https://udgwebdev.com , creator of the DevFreeBooks ( https://devfreebooks.github.io ) and DevFreeCasts ( https://devfreecasts.github.io ), and is actively engaged in many local meet-ups including NodeBr, DevInSantos, Meteor Brazil and JavaScript Brazil.

About the Technical Reviewer

A435096_1_En_BookFrontmatter_Figc_HTML.jpg

Massimo Nardone has more than 22 years of experience in security, Web/ and mobile development, and cloud and IT architecture. His true IT passions are security and Android.

He has been programming and teaching how to program with Android, Perl, PHP, Java, VB, Python, C/C++, and MySQL for more than 20 years. He holds a master’s of science degree in Computing Science from the University of Salerno, Italy.

He has worked as a project manager, software engineer, research engineer, chief security architect, information security manager, PCI/SCADA auditor, and senior lead IT security/cloud/SCADA architect for many years.

His technical skills include: security, Android, cloud, Java, MySQL, Drupal, Cobol, Perl, Web and mobile development, MongoDB, D3, Joomla, Couchbase, C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll, Scratch, and more.

He currently works as Chief Information Security Officer for Cargotec Oyj.

He worked as visiting lecturer and supervisor for exercises at the Networking Laboratory of the Helsinki University of Technology (Aalto University). He holds four international patents (PKI, SIP, SAML, and Proxy areas).

Massimo has reviewed more than 40 IT books for different publishing companies and he is the coauthor of Pro Android Games (Apress, 2015).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset