Preface

This book is focused on designing and developing Representational State Transfer (REST) platforms in Rails. REST is the architectural style of the Web, consisting of a set of constraints that, applied to components, connectors, and data elements, constitute the wider distributed hypermedia system that we know today: the World Wide Web.

There are a few good reasons why it makes more sense to build platforms instead of just products or applications. Platforms are like ecosystems interconnecting different applications, services, users, developers, and partners. Platforms foster innovation through the inputs of their direct collaborators. By providing application programming interfaces (APIs) and software development kits (SDKs), platforms are more customer driven. Another reason for building platforms instead of just applications is that the Web is slowly but surely changing from a model in which a human reader would browse some content on web pages, to a model in which services and clients (not necessarily humans) exchange information. This was certainly, although only partially, what Tim Berners Lee envisioned in 2001 in his famous Scientific American article, “The Semantic Web.” The Web is becoming more semantic. In the past, a software agent would not have been able to “understand” an HTML document. It could parse some parts of it, but it would not process whether that document was referring to a blog post or something else, like the London bus schedule.

We used to think of the Web as hypertext documents linked to one another; nowadays web documents are instead becoming more like data objects linked to other objects, or hyperdata. Applications can either display hyperdata in a human-readable form or parse it so that other services or applications can consume that information. The Semantic Web can be easily explained by considering it as a normal evolution of hypertext. When hyperdata objects are explored through an API, different communication protocols are implemented to allow several technologies to access them independently. To enable this exchange of information among heterogeneous systems, the API implements a language-neutral message format to communicate. This might be XML or JSON, used as a container for the exchanged messages. If we think about it, a “hypermedia API” is one that is designed to be accessed and explored by any device or application. Its architecture is hence similar to the architecture of the Web and we apply the same reasoning when serving and consuming the API as when surfing a web page.

There are also reasons for choosing Rails over other web development frameworks. The first of them is having to develop in Ruby rather than another language. Ruby is easy to use, especially from a web developer’s perspective. It is totally object oriented and open source and has a vibrant community working on a variety of diverse and interesting projects and language libraries, making development easier. Ruby on Rails is a pragmatic framework, cleanly and perfectly implementing Model-View-Controller (MVC) patterns, which makes it easy to model real-world scenarios. Rails makes it easier to bootstrap an application, avoiding repetitive coding and speeding up feature development. Rails also follows agile methodology, promoting flexibility, evolutionary development, and iterative delivery.

This book wants to encourage developers to organically design platforms instead of products and to develop them quickly, in the hope that the new services added to the Web of tomorrow will be more easily discovered and eventually integrated, fostering open information exchange and stimulating partnerships between organizations. At the end of every chapter, the reader will have learned something new regarding how to build and organically extend a multiservice platform spanning different devices. Hopefully, at the end of this book you will have a better idea of how to build an architecture composed of different services accessing shared resources through a set of collaborating APIs and applications.

Why Rails and Not Node.js

Many articles have been written about Rails versus Node.js in the last few years. Although both can be used to build web applications, there are some fundamental differences between Node.js and Rails.

First of all, Rails is a complete and highly opinionated web framework, while Node.js is a (nonopinionated) framework based on Chrome’s JavaScript runtime for building network applications. In short, Node.js is a server-side JavaScript implementation.

Interaction within the MVC architecture in Rails is clean, concise, and efficient. In Node.js you will need to work with plug-ins and helpers to achieve the same level of integration that in Rails you get out of the box. Also, programming both the backend and frontend in JavaScript doesn’t necessarily mean you will be able to develop your product faster. While this is probably true for fast prototyping, you should really consider whether Node.js is a technology that will allow you to scale your product down the line. Keep in mind that developing a full application in Rails is as fast as, if not faster than, developing the same app with Node.js. We will see how quickly and easily you can build a REST API in Rails.

The Rails community is quite mature at this point, while still being fresh. There are still a lot of new things happening in the Rails world, both in terms of exciting projects being created and modules being written. If you start programming in Rails, you will also learn Ruby. The Ruby developer community is vibrant, and a good number of new products are written in Ruby. These include technologies like Logstash, Chef, Puppet, Homebrew, and many others. Also, Ruby programmers are still experiencing a growth in demand. In conclusion, while Node.js is an interesting technology to use and to play and prototype with, Rails is both more mature and more suitable for long-term stable projects.

Why (I Think) You Should Read This Book

There are certainly many reasons to read a particular book, and many more to write one. When I started writing RESTful Rails Development, I imagined a world of micro-communicating applications, feeding and sourcing from the so-called Web of Data.

I thought of RESTful principles, and I imagined device-independent services that would just consume, process, and create streams of data. Before writing this book, I had several discussions with friends and colleagues about the future of the Internet and how hypermedia could be considered the true Semantic Web. The same discussions can be found online in blog posts, forums, and social-network threads. Programmers, architects, marketers, and normal people seem to have a spectrum of diverging and colliding opinions on the matter. Some people complain about possible business adoption, others about poor design and lazy development practices. Some others are thoroughly excited about unleashing the full potential of RESTful services.

This book is about:

  • How to develop RESTful applications
  • How to design RESTful architectures
  • How to deploy RESTful services

Therefore, you should read this book if:

  • You want to dive into RESTful development.
  • You want to learn about how to design a small application ecosystem.
  • You just want to design an API to connect to some external services.

You could be a developer with some years of experience, or you could be a student eager to get started with an exciting new project. You could be an engineer exploring different possibilities to create ambitious applications or wanting to convince your manager of the possibilities of RESTful services and hypermedia. You could be a project manager with some technical background looking to understand the logic behind RESTful services, or you could work in marketing but be willing to learn how to open up your platform to services on the World Wide Web.

You should read this book if you are passionate about the future of the Web, if you feel strongly about keeping it open, if you envision the Semantic Web as a mesh of communicating services, or if you want to start writing software that just implements these paradigms. If you have read about API design and hypermedia paradigms, if you are just enthusiastic about the Web of Data, or if you have wondered how you could quickly prototype a new service or apply hypermedia models to a commercial project, then this book is also for you. I hope this book will help you in your present and future projects; I also hope it will be your guide to building amazingly disruptive applications, creating services that will make the Web more open and accessible to a wide range of devices, and providing beautifully designed hypermedia APIs that will make data easier to explore and process. This book is for you—and I hope you thoroughly enjoy it.

What You Will Find in This Book

This is not a book that you have to read from beginning to end, although you certainly can if you want. Every chapter can be considered a standalone unit that will present an aspect of RESTful architecture and Rails development:

Chapter 1, From Hypertext to Hyperdata
This chapter introduces the shift that has been occurring in the way the Web is accessed and consumed, from hypertext documents that were intended to be human readable, to web applications that can either display information for their human users or provide endpoints for software agents that are designed to consume data.
Chapter 2, Getting Started with Ruby on Rails
This chapter introduces Ruby on Rails. It guides you through setting up your development environment, and then introduces some RVM and rbenv basics and outlines some simple concepts in Rails application architecture. We will then set up our first application. This will be a “Hello Rails” app with a twist, since it will not strictly be an app but an API instead.
Chapter 3, First Adventures in API Design
This chapter leads you through some API design considerations by creating a simple API using a Wikipedia categories and category links database dump. The result will be an API with two endpoints. Given a keyword, the API will return the category information or the category graph from Wikipedia in JSON.
Chapter 4, The REST of the World

This chapter covers the basics of REST versus CRUD (Create, Read, Update, Delete) design, introducing architectural constraints, resource and representation concepts, and HTTP protocol semantics. Our categories API will be extended and used to illustrate the concepts.

This chapter also covers how Rails plays with REST logic, since it was designed with CRUD in mind.

Chapter 5, Designing APIs in RoR

This chapter extends what has been introduced thus far regarding REST architectures with hypermedia paradigms.

Practical examples will be implemented over our categories API model. The API introduced in Chapter 3 and extended in Chapter 4 will be further developed to illustrate API architecture and design concepts in Rails. Category links will be used to extend the API in order to make it explorable.

Chapter 6, Asynchronous REST
This chapter explores aspects of REST architecture that concern asynchronous operations. Asynchronous operations on resources are usually applied when your app has to perform some actions that need some time to complete. We will see what the best practices are in these cases.
Chapter 7, Testing RESTful Services
This chapter is about testing, and specifically testing RESTful services in Rails. What are doubles? What are stubs, and what are mocks? These are the questions that will be answered in this chapter. You will also learn about integration testing and best practices in testing.
Chapter 8, Microservices and Microapplications

This chapter is focused on the basics of service-oriented architecture (SOA) and distributed systems design. It takes the approach of envisioning fine-grained collaborating microservices, or better microapplications. A set of applications and APIs accessing shared resources will be used as an example.

In our example, an API will return geographical points of interest within cities. These will be mapped to categories of preference returned from our first API, then data will be correlated to obtain possible thematic city walks.

Chapter 9, Mapping Data Streams onto an Application UI
In this chapter, we consume the APIs built in the previous installments through an application built in RoR plus Ember.js. The chapter is particularly focused on mapping different resources onto an application UI. Our Walks application resources will be mapped to a user interface.
Chapter 10, Deploying an API
This chapter is centered on deploying and building middleware for external customers to connect to the APIs. It will answer questions like “How is an API deployed?” and introduce concepts like the reverse proxy. It will configure a reverse proxy on Heroku and use it to connect the APIs built in Chapter 5 with the applications consuming them.
Chapter 11, Managing an App Ecosystem
This chapter introduces API management solutions. It will help you to make the choice between developing in house or relying on external services. It will also introduce concepts like key provisioning and role management, traffic monitoring, and the API and application lifecycle.
Chapter 12, Consuming Data Streams: Integrating External APIs in Your Application
This chapter explains how to integrate external services and APIs and display them in your application, by using open data or simply importing the Wikipedia, YouTube, or Twitter APIs, thus making the imported resources available to a distributed platform without having to repeatedly call them.
Chapter 13, Device-Independent Development
This chapter expands our case study to different devices: mobile platforms and the Internet of Things. How can we include devices like mobile phones, Arduinos, or Raspberry Pi’s in our web apps and organically integrate the generated data? We will build a simple weather app to access, consume, and generate data.
Chapter 14, Data Analytics
This chapter focuses on maintaining control over data flows and analytics. What tools can we develop or integrate to keep control over our platform’s data flows?
Chapter 15, Scaling Gracefully
This chapter is about scaling gracefully. It focuses on scaling by design. This chapter is of particular interest with regard to Rails development, because scalability in Rails is a big issue.
Chapter 16, Privacy and Security
This chapter is particularly concerned with security and privacy. How do we secure our platforms, and how do we make sure user data is safe?

What You Will Not Find in This Book (And Where You Can Go for Answers)

This is neither a Ruby nor a Rails book, specifically. This book is about Rails development, but if you want to learn core concepts of the Ruby programming language or the Rails platform, you should also read a book focused on Ruby on Rails or Ruby.

This is not a book about JavaScript or Ember.js, or any other framework, although we will use some JavaScript and we will set up an Ember environment.

This is not specifically a book about Nginx, or Redis or Lua, although we might use or mention some of these technologies when going through API management, scaling, and analytics-related issues.

This book isn’t about privacy or security either, though an entire chapter is focused on these topics (and it is important to keep in mind that “with big data comes big responsibilities”). I will redirect you to more authoritative resources in the last chapter, should you want to start learning about these topics.

Note

Additional resources where you can find information regarding topics that are outside the scope of this book will be provided in notes like this one.

Resources

All code used in this book will be made available on GitHub and released under the GPLv3 license. I will also redirect to authoritative resources on specific topics throughout the book: at the end of each chapter you will find some links that you can follow to start diving into specific sets of technologies relevant to that chapter.

Coding Style

There aren’t many coding style guides for Ruby or Ruby on Rails, like you could probably find for other languages—or maybe there are too many, meaning everyone follows their own.

Throughout this book I will use some simple conventions that I hope will make the code more readable and self-explanatory.

These are:

  • UTF-8 as the source file encoding.
  • Two spaces per indentation level (aka soft tabs); no hard tabs.
  • Unix-style line endings.
  • One expression per line.
  • Single-line format for class definitions with no body.
  • Avoid single-line methods.
  • Use spaces around operators; after commas, colons, and semicolons, around { and before }.
  • Never use unless with else.
  • Keep the controllers skinny.
  • Logic resides in the models.

I would also like to underline the simple concept that this won’t be a book merely about coding. While it is certainly a book centered on development, coding should also be seen as the medium to explain concepts and design choices. I am also sure most of the readers will be able to find better ways to rewrite the code examples presented. Therefore, I completely encourage you to fork the repositories and get creative creating new apps and products.

RuboCop

RuboCop is a Ruby static code analyzer that enforces many of the guidelines outlined in the community Ruby Style Guide out of the box.

You can find out more about RuboCop at its GitHub repository.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, file extensions, keywords, and variable names.

Constant width

Used for code examples, programming snippets, and function statements.

<italic>

Shows text that should be replaced with user-supplied values or by values determined by context.

Bold

Shows commands or other text that should be typed literally by the user.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

This element indicates a warning or caution.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at http://hiromipaw.github.io/RESTful-Rails-Development/.

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “RESTful Rails Development by Silvia Puglisi (O’Reilly). Copyright 2016 Silvia Puglisi, 978-1-491-91085-6.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

All the code and simple apps provided with this book are released under the GNU General Public License version 3. GPLv3 is a free, copyleft license for software and other kinds of works. The GPLv3 license is intended to guarantee your freedom to share and change all versions of a program to make sure it remains free software for all its users.

I encourage you to visit the license document at http://www.gnu.org/copyleft/gpl.html.

I also encourage every reader of this book to fork, rewrite, and use the code examples provided to create new and amazing projects.

Rails is released under the MIT license and Ruby under the Ruby license.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

We have a web page where we list errata and corrections; you can access this page at: http://bit.ly/RESTful_rails_development.

We also have a GitHub page where all the coding examples and applications used in this book can be accessed: http://hiromipaw.github.io/RESTful-Rails-Development/.

Acknowledgments

Thanks to everyone who has made this book possible.

Thanks to the editors that have guided me through this, I’d say, adventure. To all the reviewers who took the time to send me feedback. To all my friends that supported me. To my family and partner, who bore with me while I was always writing and rewriting.

I hope it will be a guide to many who are starting their adventures in the REST and Rails worlds.