Docsity

Programacion con Node JS, Guías, Proyectos, Investigaciones de Informática

Vista previa parcial del texto

¡Descarga Programacion con Node JS y más Guías, Proyectos, Investigaciones en PDF de Informática solo en Docsity!

RESTful Web API Design with

Node.js

Design and implement comprehensive RESTful

solutions in Node.js

Valentin Bojinov

BIRMINGHAM - MUMBAI

Credits

Author Valentin Bojinov Reviewers Abhishek Dey Stefan Lapers Ângelo Marcos Rigo Commissioning Editor Edward Gordon Acquisition Editor Nikhil Karkal Content Development Editor Ritika Singh Technical Editors Monica John Mrunmayee Patil Rikita Poojari Copy Editor Vikrant Phadke Project Coordinator Judie Jose Proofreaders Maria Gould Ameesha Green Indexer Monica Ajmera Mehta Production Coordinator Alwin Roy Cover Work Alwin Roy

About the Author

Valentin Bojinov studied computer programming at Technological School of

Electronic Systems, a college within the Technical University of Sofia, Bulgaria. There, he got acquainted with programming and realized that his career would be in research and development. After college, he graduated from the Technical University of Sofia with a BSc in telecommunication and information engineering. It was then that his interest in data transmission grew and he ventured into B2B (business-to-business) communication. He is currently working on his MSc degree in software development. He is an expert in Java, SOAP, RESTful web services, and B2B integration. A few years after Valentin 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 this opportunity to thank my soul mate, Galya, for putting up with me and my decision to work on this title. Also, many thanks to my lovely parents: my dad, Emil, for making me develop an enthusiasm for computers 20 years ago and 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 there with. Guys, thanks for always being such good friends and experts! I know I haven't recently shown up for our regular monthly gathering, so next time, the beer is on me!

Ângelo Marcos Rigo is a developer with 15 years of experience, with significant

focus on web development. He always wants to learn better and new technologies. He has worked for the prominent companies in the fields of telecommunication, IT, education, and now, web marketing. He has also worked as a reviewer on Moodle Security , Packt Publishing , and is available for consulting at http://www.u4w.com.br. I would like to thank my wife and daughter for all their support.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.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. TM 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 Packt
  • Copy and paste, print, and bookmark content
  • On demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

[ i ]

Table of Contents

Table of Contents

  • Chapter 1: REST – What You Didn't Know Preface iii
    • A brief history of REST
      • 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
  • Chapter 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
      • Nodejitsu
      • Microsoft Azure
    • Self-test questions [ ii ]
    • Summary
  • Chapter 3: Building a Typical Web API
    • Specifying the API
    • Implementing routes
    • Testing the API
    • Content negotiation
    • Cross-origin resource sharing
    • API versioning
    • Self-test questions
    • Summary
  • Chapter 4: Using NoSQL Databases
    • Key/value store – LevelDB
    • Document store – MongoDB
    • Database modeling with Mongoose
    • Testing a NoSQL database solution
    • Content delivery network
    • Self-test questions
    • Summary
  • Chapter 5: Implementing a Full-fledged RESTful Service
    • Extensibility and versioning
    • Working with arbitrary data
    • Linking
    • Implementing paging and filtering
    • Caching
    • Discovering and exploring RESTful services
    • Self-test questions
    • Summary
  • Chapter 6: Keeping the Bad Guys Out
    • Authentication
      • Basic authentication
      • Passport
        • Passport basic authentication strategy
        • Passport's third-party authentication strategies
    • Authorization
    • Transport Layer Security
    • Self-test questions
    • Summary
  • Index

Preface [ iv ] Chapter 5 , Implementing a Full-fledged RESTful Service , takes you through implementing a production-ready RESTful service that uses NoSQL to store its data. You get to learn how to handle binary data and how to version an API while it evolves. Chapter 6 , Keeping the Bad Guys Out , covers restricting access to your data by choosing an appropriate authentication approach. Now you can protect data leakage with transport layer security. What you need for this book The following pieces of software are used throughout the book:

  • Node.js (http://www.nodejs.org/)
  • Enide developer studio or the Nodeclipse plugin for the Eclipse IDE (http://www.nodeclipse.org/enide/studio/)
  • SoapUI (http://www.soapui.org)
  • OpenSSL (http://www.openssl.org)
  • The Nodeclipse plugin (http://www.nodeclipse.org)
  • The NPM package manager (https://www.npmjs.org/) Who this book is for If you are a Java developer wanting to enrich your development skills to create scalable, server-side RESTful applications based on the Node.js platform, this book is for you. You also need to be aware of the concepts of HTTP communication, and you should have working knowledge of JavaScript. Knowledge of REST will be an added advantage but is definitely not a necessity. Conventions 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 table 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."

Preface [ v ] A block of code is set as follows: app.get('/contacts/:number', cors(), function(request, response) { response.setHeader('content-type', 'application/json'); response.end (JSON.stringify(contacts.query(request.params.number))); }); New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Select File | New | Node.js Project and enter the name of your first project" Warnings or important notes appear in a box like this. 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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to [email protected], and mention the book title via 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 on 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.

[ 1 ]

REST – What You

Didn't Know

Nowadays, topics such as cloud computing and mobile device service feeds, and other data sources being powered by cutting-edge, scalable, stateless, and modern technologies such as RESTful web services, leave the impression that REST has been invented recently. Well, to be honest, it is definitely not! In fact, REST was defined at the end of the 20th century. This chapter will walk you through REST's history and will teach you how REST couples with the HTTP protocol. You will look at 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 between RESTful and SOAP-based services. Finally, you will learn how to utilize already existing infrastructure for your benefit. In this chapter, we will cover the following topics:

  • A brief history of REST
  • REST with HTTP
  • RESTful versus SOAP-based services
  • Taking advantage of existing infrastructure

REST – What You Didn't Know [ 2 ] A brief history of REST Let's look at a time when the madness around REST made everybody talk restlessly about it! This 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 Chapter 5 , Implementing a Full-fldged RESTful Service , 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)
  • Use the standard HTTP methods
  • Resources can have multiple representations
  • Communicate 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.

REST – What You Didn't Know [ 4 ] 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 Request 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 Create or update a resource " 201 CREATED " if a new resource is created, " 200 OK " if updated, and " 500 Internal Server Error " for other errors POST Update an existing resource " 200 OK " if the resource has been updated successfully, " 404 Not Found " if the resource to be updated does not exist, and " 500 Internal Server Error " for other errors DELETE Delete a resource " 200 OK " if the resource has been deleted successfully, " 404 Not Found " if the resource to be deleted does not exist, and " 500 Internal Server Error " for other errors There is an exception in the usage of the verbs, however. I just mentioned that POST is used to create a resource. For instance, when a resource has to be created under a specific URI, then PUT is the appropriate request: PUT /data/documents/balance/22082014 HTTP/1. Content-Type: text/xml Host: www.mydatastore.com

Sample item 100 HTTP/1.1 201 Created Content-Type: text/xml Location: /data/documents/balance/

Chapter 1 [ 5 ] However, in your application you may want to leave it up to the server REST application to decide where to place the newly created resource, and thus create it under an appropriate but still unknown or non-existing location. For instance, in our example, we might want the server to create the date part of the URI based on the current date. In such cases, it is perfectly fine to use the POST verb to the main resource URI and let the server respond with the location of the newly created resource: POST /data/documents/balance HTTP/1. Content-Type: text/xml Host: www.mydatastore.com

Sample item 100 HTTP/1.1 201 Created Content-Type: text/xml Location: /data/documents/balance **Principle 4 – resources can have multiple representations** A key feature of a resource is that they may be represented in a different form than the one it is stored. Thus, it can be requested or posted in different representations. As long as the specified format is supported, the REST-enabled endpoint should use it. In the preceding example, we posted an xml representation of a balance, but if the server supported the JSON format, the following request would have been valid as well: POST /data/documents/balance HTTP/1. Content-Type: application/json Host: www.mydatastore.com { "balance": { "date": ""22082014"", "Item": "Sample item", "price": {