0% found this document useful (0 votes)
21 views75 pages

Building Rest Apis With Flask: Create Python Web Services With Mysql Kunal Relan Install Download

The document is a promotional material for the book 'Building REST APIs with Flask' by Kunal Relan, which provides guidance on creating Python web services with MySQL. It includes links to other related books and resources, as well as a detailed table of contents outlining various chapters covering Flask fundamentals, database modeling, CRUD applications, testing, deployment, and monitoring. The author, Kunal Relan, is an experienced developer and security researcher with contributions to the Python community.

Uploaded by

jouzasjetvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views75 pages

Building Rest Apis With Flask: Create Python Web Services With Mysql Kunal Relan Install Download

The document is a promotional material for the book 'Building REST APIs with Flask' by Kunal Relan, which provides guidance on creating Python web services with MySQL. It includes links to other related books and resources, as well as a detailed table of contents outlining various chapters covering Flask fundamentals, database modeling, CRUD applications, testing, deployment, and monitoring. The author, Kunal Relan, is an experienced developer and security researcher with contributions to the Python community.

Uploaded by

jouzasjetvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Building REST APIs with Flask: Create Python Web

Services with MySQL Kunal Relan install download

https://ebookmeta.com/product/building-rest-apis-with-flask-
create-python-web-services-with-mysql-kunal-relan/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Building Versatile Mobile Apps with Python and REST:


RESTful Web Services with Django and React 1st Edition
Art Yudin

https://ebookmeta.com/product/building-versatile-mobile-apps-
with-python-and-rest-restful-web-services-with-django-and-
react-1st-edition-art-yudin/

Building RESTful Web Services with Go Learn how to


build powerful RESTful APIs with Golang that scale
gracefully 1st Edition Naren Yellavula

https://ebookmeta.com/product/building-restful-web-services-with-
go-learn-how-to-build-powerful-restful-apis-with-golang-that-
scale-gracefully-1st-edition-naren-yellavula/

Building Web APIs with ASP.NET Core (MEAP Version 11)


Valerio De Sanctis

https://ebookmeta.com/product/building-web-apis-with-asp-net-
core-meap-version-11-valerio-de-sanctis/

Love Practically Van Nichole

https://ebookmeta.com/product/love-practically-van-nichole/
Product Maturity 1 : Theoretical Principles and
Industrial Applications 1st Edition Franck Bayle

https://ebookmeta.com/product/product-maturity-1-theoretical-
principles-and-industrial-applications-1st-edition-franck-bayle/

An Insider s Guide to the UN 4th Edition Linda Fasulo

https://ebookmeta.com/product/an-insider-s-guide-to-the-un-4th-
edition-linda-fasulo-2/

Fast Circuit Boards Energy Management Ralph Morrison

https://ebookmeta.com/product/fast-circuit-boards-energy-
management-ralph-morrison/

The Anxiety Worry Workbook 2nd ed The Cognitive


Behavioral Solution 2nd Edition David A. Clark

https://ebookmeta.com/product/the-anxiety-worry-workbook-2nd-ed-
the-cognitive-behavioral-solution-2nd-edition-david-a-clark/

Crime Violence and Security in the Caribbean 1st


Edition M. Raymond Izarali

https://ebookmeta.com/product/crime-violence-and-security-in-the-
caribbean-1st-edition-m-raymond-izarali/
Temporary Palaces The Great House in European
Prehistory 1st Edition Richard Bradley

https://ebookmeta.com/product/temporary-palaces-the-great-house-
in-european-prehistory-1st-edition-richard-bradley/
Building REST
APIs with Flask
Create Python Web Services
with MySQL

Kunal Relan

www.allitebooks.com
Building REST APIs
with Flask
Create Python Web Services
with MySQL

Kunal Relan

www.allitebooks.com
Building REST APIs with Flask: Create Python Web Services with MySQL
Kunal Relan
New Delhi, Delhi, India

ISBN-13 (pbk): 978-1-4842-5021-1 ISBN-13 (electronic): 978-1-4842-5022-8


https://doi.org/10.1007/978-1-4842-5022-8

Copyright © 2019 by Kunal Relan


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.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Nikhil Karkal
Development Editor: Laura Berendson
Coordinating Editor: Divya Modi
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
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 orders-ny@springer-sbm.com, or visit www.springeronline.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.
For information on translations, please e-mail rights@apress.com, or visit http://www.apress.
com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book’s product page, located at www.apress.com/9781484250211.
For more detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper

www.allitebooks.com
Dedicated to caffeine and sugar, my companions
through many long night of writing, and
extra credits to my mom.

www.allitebooks.com
Table of Contents
About the Author���������������������������������������������������������������������������������ix
About the Technical Reviewer�������������������������������������������������������������xi
Acknowledgments�����������������������������������������������������������������������������xiii
Introduction����������������������������������������������������������������������������������������xv

Chapter 1: Beginning with Flask����������������������������������������������������������1


Introduction to Flask���������������������������������������������������������������������������������������������1
Starting Flask��������������������������������������������������������������������������������������������������2
Flask Components Covered in This Book���������������������������������������������������������3
Introduction to RESTful Services��������������������������������������������������������������������������4
Uniform Interface���������������������������������������������������������������������������������������������7
Representations����������������������������������������������������������������������������������������������8
Messages��������������������������������������������������������������������������������������������������������9
Links Between Resources�����������������������������������������������������������������������������12
Caching����������������������������������������������������������������������������������������������������������13
Stateless��������������������������������������������������������������������������������������������������������13
Planning REST API�����������������������������������������������������������������������������������������14
API Design�����������������������������������������������������������������������������������������������������15
Setting Up Development Environment����������������������������������������������������������������16
Working with PIP�������������������������������������������������������������������������������������������17
Choosing the IDE�������������������������������������������������������������������������������������������18
Understanding Python Virtual Environments�������������������������������������������������19

www.allitebooks.com
Table of Contents

Setting Up Flask��������������������������������������������������������������������������������������������������24
Installing Flask����������������������������������������������������������������������������������������������25
Conclusion����������������������������������������������������������������������������������������������������������26

Chapter 2: Database Modeling in Flask����������������������������������������������27


Introduction���������������������������������������������������������������������������������������������������������27
SQL Databases����������������������������������������������������������������������������������������������28
NoSQL Databases������������������������������������������������������������������������������������������28
Key Differences: MySQL vs. MongoDB����������������������������������������������������������29
Creating a Flask Application with SQLAlchemy��������������������������������������������������30
Creating an Author Database�������������������������������������������������������������������������33
Sample Flask MongoEngine Application�������������������������������������������������������������46
Conclusion����������������������������������������������������������������������������������������������������������58

Chapter 3: CRUD Application with Flask (Part 1)��������������������������������59


User Authentication���������������������������������������������������������������������������������������������88
Conclusion����������������������������������������������������������������������������������������������������������96

Chapter 4: CRUD Application with Flask (Part 2)��������������������������������97


Introduction���������������������������������������������������������������������������������������������������������97
Email Verification������������������������������������������������������������������������������������������������98
File Upload��������������������������������������������������������������������������������������������������������109
API Documentation��������������������������������������������������������������������������������������������114
Building Blocks of API Documentation��������������������������������������������������������115
OpenAPI Specification���������������������������������������������������������������������������������116
Conclusion��������������������������������������������������������������������������������������������������������134

vi
Table of Contents

Chapter 5: Testing in Flask���������������������������������������������������������������135


Introduction�������������������������������������������������������������������������������������������������������135
Setting Up Unit Tests�����������������������������������������������������������������������������������136
Unit Testing User Endpoints�������������������������������������������������������������������������139
Test Coverage���������������������������������������������������������������������������������������������������155
Conclusion��������������������������������������������������������������������������������������������������������157

Chapter 6: Deploying Flask Applications������������������������������������������159


Deploying Flask with uWSGI and Nginx on Alibaba Cloud ECS�������������������������160
Deploying Flask on Gunicorn with Apache on Alibaba Cloud ECS���������������������167
Deploying Flask on AWS Elastic Beanstalk�������������������������������������������������������172
Deploying Flask App on Heroku������������������������������������������������������������������������176
Adding a Procfile�����������������������������������������������������������������������������������������177
Deploying Flask App on Google App Engine������������������������������������������������������180
Conclusion��������������������������������������������������������������������������������������������������������182

Chapter 7: Monitoring Flask Applications����������������������������������������183


Application Monitoring��������������������������������������������������������������������������������������183
Sentry����������������������������������������������������������������������������������������������������������185
Flask Monitoring Dashboard������������������������������������������������������������������������187
New Relic����������������������������������������������������������������������������������������������������189
Bonus Services��������������������������������������������������������������������������������������������192
Conclusion��������������������������������������������������������������������������������������������������������194

Index�������������������������������������������������������������������������������������������������195

vii
About the Author
Kunal Relan is an iOS security researcher
and a full stack developer with more than
four years of experience in various fields
of technology, including network security,
DevOps, cloud infrastructure, and application
development, working as a consultant with
start-ups around the globe. He is an Alibaba
Cloud MVP and author of iOS Penetration
Testing (Apress) and a variety of white papers.
Kunal is a technology enthusiast and an active
speaker. He regularly contributes to open source communities and writes
articles for Digital Ocean and Alibaba Techshare.

ix
About the Technical Reviewer
Saurabh Badhwar is a software engineer
with a passion to build scalable distributed
systems. He is mostly working to solve
challenges related to performance of software
at a large scale and has been involved in
building solutions that help other developers
quickly analyze and compare performance
of their systems when running at scale.
He is also passionate about working with
open source communities and has been
actively participating as a contributor in various domains, which involve
development, testing, and community engagement. Saurabh has also been
an active speaker at various conferences where he has been talking about
performance of large-scale systems.

xi
Acknowledgments
I would like to thank Apress for providing me this platform, without which
this would have been a lot harder. I would also like to thank Mr. Nikhil
Karkal for his help and Miss Divya Modi for her perseverance, without
whom this would have been a farsighted project.
I’d like to mention about the strong Python community which helped
me understand the core concepts in my early years of programming, which
inspired me to contribute back to the community with this book.
Last but certainly not the least, I would like to acknowledge all the
people who constantly reminded me about the deadlines and helped me
write this book, especially my family and Aparna Abhijit for helping me out
with editing.

xiii
Introduction
Flask is a lightweight microframework for web applications built on top
of Python, which provides an efficient framework for building web-based
applications using the flexibility of Python and strong community support
with the capability of scaling to serve millions of users.
Flask has excellent community support, documentation, and
supporting libraries; it was developed to provide a barebone framework for
developers, giving them the freedom to build their applications using their
preferred set of libraries and tools.
This book takes you through different stages of a REST API–based
application development process using flask which explains the basics of
the Flask framework assuming the readers understand Python. We’ll cover
database integration, understanding REST services, REST APIs performing
CRUD operations, user authentication, third-party library integrations,
testing, deployment, and application monitoring.
At the end of this book, you’ll have a fair understanding of Flask
framework, REST, testing, deploying, and managing Flask applications,
which will open doors to understanding REST API development.

xv
CHAPTER 1

Beginning with Flask


Flask is a BSD licensed, Python microframework based on Werkzeug and
Jinja2. Being a microframework doesn’t make it any less functional; Flask
is a very simple yet highly extensible framework. This gives developers
the power to choose the configuration they want, thereby making writing
applications or plugins easy. Flask was originally created by Pocoo, a
team of open source developers in 2010, and it is now developed and
maintained by The Pallets Project who power all the components behind
Flask. Flask is supported by an active and helpful developer community
including an active IRC channel and a mailing list.

I ntroduction to Flask
Flask has two major components, Werkzeug and Jinja2. While Werkzeug
is responsible for providing routing, debugging, and Web Server Gateway
Interface (WSGI), Flask leverages Jinja2 as template engine. Natively,
Flask doesn’t support database access, user authentication, or any other
high-level utility, but it does provide support for extensions integration to
add all such functionalities, making Flask a micro- yet production-ready
framework for developing web applications and services. A simple Flask
application can fit into a single Python file or it can be modularized to
create a production-ready application. The idea behind Flask is to build a
good foundation for all applications leaving everything else on extensions.

© Kunal Relan 2019 1


K. Relan, Building REST APIs with Flask, https://doi.org/10.1007/978-1-4842-5022-8_1
Chapter 1 Beginning with Flask

Flask community is quite big and active with hundreds of open source
extensions. The Flask core team continuously reviews extensions and
ensures approved extensions are compatible with the future releases. Flask
being a microframework provides flexibility to the developers to choose
the design decisions appropriate to their project. It maintains a registry of
extensions which is regularly updated and continuously maintained.

Starting Flask
Flask, just like all other Python libraries, is installable from the Python
Package Index (PPI) and is really easy to setup and start developing with,
and it only takes a few minutes to getting started with Flask. To be able to
follow this book, you should be familiar with Python, command line (or at
least PIP), and MySQL.
As promised, Flask is really easy to start with, and just five lines of code
lets you get started with a minimal Flask application.

Listing 1-1. Basic Flask Application

from flask import Flask


app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, From Flask!'

if __name__== '__main__':
      app.run()

The preceding code imports the Flask library, initiates the application
by creating an instance of the Flask class, declares the route, and then
defines the function to execute when the route is called. This code is
enough to start your first Flask application.

2
Chapter 1 Beginning with Flask

The following code launches a very simple built-in server, which


is good enough for testing but probably not when you want to go in
production, but we will cover that in the later chapters.
When this application starts, the index route upon request shall return
“Hello From Flask!” as shown in Figure 1-1.

Figure 1-1. Flask minimal application

Flask Components Covered in This Book


Now that you have been introduced to Flask, we will discuss the
components that we’ll cover in Flask REST API development in this book.
This book will serve as a practical guide to REST API development
using Flask, and we’ll be using MySQL as the backend database. As already
discussed, Flask doesn’t come with native database access support, and
to bridge that gap, we’ll use a Flask extension called Flask-SQLAlchemy
which adds support for SQLAlchemy in Flask. SQLAlchemy is essentially

3
Chapter 1 Beginning with Flask

a Python SQL toolkit and Object Relational Mapper which provides the
developers the full power and flexibility of SQL.
SQLAlchemy provides full support for enterprise-level design patterns
and is designed for high-performing database access while maintaining
efficiency and ease of use. We’ll build a user authentication module, CRUD
(Create, Read, Update, and Delete) REST APIs for object creation, retrieval,
manipulation, and deletion. We’ll also integrate a documentation utility
called Swagger for creating API documentation, write unit and integration
tests, learn application debugging, and, finally, check out different
methods of deploying and monitoring our REST APIs on cloud platforms
for production use.
For unit tests, we’ll use pytest which is a full-featured Python testing
tool—pytest is easy to write tests with and yet is scalable to support
complex use cases. We’ll also use Postman which is a complete REST API
Platform—Postman provides integration tools for every stage of the API
lifecycle, making API development easier and more reliable.
API deployment and monitoring are critical parts of REST API
development; development paradigm changes drastically when it comes
to scaling the APIs for production use cases, and for the sake of this book,
we’ll deploy our REST APIs using uWSGI and Nginx on a cloud Ubuntu
server. We’ll also deploy our REST APIs on Heroku which is a cloud
platform that facilitates Flask app deployment and scaling out of the box.
Last but not least, we’ll discuss debugging common Flask errors and
warnings and debugging Nginx requests and check out Flask application
monitoring ensuring least amount on the downtime for production use.

Introduction to RESTful Services


Representational State Transfer (REST) is a software architectural style
for web services that provides a standard for data communication
between different kinds of systems. Web services are open standard

4
Chapter 1 Beginning with Flask

web applications that interact with other applications with a motive of


exchanging data making it an essential part of client server architecture in
modern web and mobile applications. In simple terms, REST is a standard
for exchanging data over the Web for the sake of interoperability between
computer systems. Web services which conform to the REST architectural
style are called RESTful web services which allow requesting systems to
access and manipulate the data using a uniform and predefined set of
stateless operations.
Since its inception in 2000 by Roy Feilding, RESTful architecture has
grown a lot and has been implemented in millions of systems since then.
REST has now become one of the most important technologies for web-­
based applications and is likely to grow even more with its integration
in mobile and IoT-based applications as well. Every major development
language has frameworks for building REST web services. REST principles
are what makes it popular and heavily used. REST is stateless, making it
straightforward for any kind of system to use and also making it possible
for each request to be served by a different system.
REST enables us to distinguish between the client and the server,
letting us implement the client and the server independently. The most
important feature of REST is its statelessness, which simply means that
neither the client nor the server has to know the state of each other to
be able to communicate. In this way, both the client and the server can
understand any message received without seeing the previous message.
Since we are talking about RESTful web services, let’s take a dive into web
services and compare other web service standards.
Web services in a simple definition is a service offered by one
electronic device to another, enabling the communication via the World
Wide Web. In practice, web services provide resource-oriented, web-­
based interface to a database server and so on utilized by another web
client. Web services provide a platform for different kinds of systems to
communicate to each other, using a solution for programs to be able to
communicate with each other in a language they understand (Figure 1-2).

5
Chapter 1 Beginning with Flask

Figure 1-2. REST architecture diagram

SOAP (Simple Object Access Protocol) is another web service


communication protocol which has been overtaken by REST in the
recent years. REST services now dominate the industry representing
more than 70% of public APIs according to Stormpath. They operate by
exposing consistent interface to access named resources. SOAP, however,
exposes components of application logic as services rather than data.
SOAP is now a legacy protocol originally created by Microsoft and has a
lot of other constraints when compared to REST. SOAP only exchanges
data over XML, and REST provides the ability to exchange data over a
variety of data formats. RESTful services are comparatively faster and less
resource intensive. However, SOAP still has its own use cases in which it’s a
preferred protocol over REST.
SOAP is preferred when robust security is essential as it provides
support for Web Services Security (WS-Security), which is a specification
defining how security measures are implemented in web services to
protect them from external attacks. Another advantage of SOAP over REST
is its built-in retry logic to compensate for failed requests unlike REST in
which the client has to handle failed requests by retrying. SOAP is highly
extensible with other technologies and protocols like WS-Security,
WS-­addressing, WS-coordination, and so on which provides it an edge
over other web service protocols.

6
Chapter 1 Beginning with Flask

Now, when we have briefly discussed web services—REST and SOAP—


let’s discuss features of REST protocol. In general, REST services are
defined and implemented using the following features:

1. Uniform interface
2. Representations

3. Messages

4. Links between resources

5. Caching

6. Stateless

U
 niform Interface
RESTful services should have a uniform interface to access resources, and
as the name suggests, APIs’ interface for the system should be uniform
across the system. A logical URI system with uniform ways to fetch and
manipulate data is what makes REST easy to work with. HTTP/1.1 provides
a set of methods to work on noun-based resources; the methods are
generally called verbs for this purpose.
In REST architecture, there is a concept of safe and idempotent
methods. Safe methods are the ones that do not modify resources like a GET
or a HEAD method. An idempotent method is a method which produces
the same result no matter how many times it is executed. Table 1-­1 provides
a list of commonly used HTTP verbs in RESTful services.

7
Chapter 1 Beginning with Flask

Table 1-1. Commonly used HTTP verbs useful in RESTful services


Verb CRUD Operation Safe Idempotent

GET Read Fetch a single or multiple resource Yes Yes


POST Created Insert a new resource No No
PUT Update/ Insert a new resource or update No Yes
Create existing
DELETE Delete Delete a single or multiple resource No Yes
OPTIONS READ List allowed operations on a resource Yes Yes
HEAD READ Return only response headers and no Yes Yes
body
PATCH Update/ Only update the provided changes to No No
Modify the resource

Representations
RESTful services focus on resources and providing access to the resources.
A resource can be easily thought of as an object in OOP. The first thing to
do while designing RESTful services is identifying different resources and
determining the relation between them. A representation is a machine-­
readable explanation defining the current state of a resource.
Once the resources are identified, representations are the next course
of action. REST provides us the ability to use any format for representing
the resources in the system. Unlike SOAP which restricts us to use XML to
represent the data, we can either use JSON or XML. Usually, JSON is the
preferred method for representing the resources to be called by mobile or
web clients, but XML can be used to represent more complex resources.
Here is a small example of representing resources in both formats.

8
Chapter 1 Beginning with Flask

Listing 1-2. XML Representation of a Book Resource

<?xml version="1.0" encoding="UTF-8"?>


<Book>
  <ID> 1 </ID>
  <Name> Building REST APIs with Flask </Name>
  <Author> Kunal Relan </Author>
  <Publisher > Apress </ Publisher >
</Book>

Listing 1-3. JSON Representation of a Book resource

{
      "ID": "1",
      "Name": "Building REST APIs wiith Flask",
      "Author": "Kunal Relan",
      "Publisher": "Apress"
}

In REST Systems, you can use either of the methods or both the
methods depending on the requesting client to represent the data.

M
 essages
In REST architecture, which essentially established client–server style
way of data communication, messages are an important key. The client
and the server talk to each other via messages in which the client sends
a message to the server which is often called as a request and the server
sends a response. Apart from the actual data exchanged between the
client and the server in the form of request and response body, there is
some metadata exchanged by the client and the server both in the form
of request and response headers. HTTP 1.1 defines request and response
headers formats in the following way in order to achieve a uniform way of
data communication across different kinds of systems (Figure 1-3).

9
Chapter 1 Beginning with Flask

Figure 1-3. HTTP sample request

In Figure 1-4, GET is the request method, “/comments” is the path in


the server, “postId=1” is a request parameter, “HTTP/1.1” is the protocol
version that the client is requesting, “jsonplaceholder.typicode.com” is the
server host, and content type is a part of the request headers. All of these
combined is what makes a HTTP request that the server understands.
In return, the HTTP server sends the response for the requested
resources.

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "Eliseo@gardner.biz",
    "body": "laudantium enim quasi est quidem magnam voluptate
ipsam eos\ntempora quo necessitatibus\ndolor quam
autem quasi\nreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "Jayne_Kuhic@sydney.com",

10
Chapter 1 Beginning with Flask

    "body": "est natus enim nihil est dolore omnis voluptatem


numquam\net omnis occaecati quod ullam at\nvoluptatem
error expedita pariatur\nnihil sint nostrum voluptatem
reiciendis et"
  },
  {
    "postId": 1,
    "id": 3,
    "name": "odio adipisci rerum aut animi",
    "email": "Nikita@garfield.biz",
    "body": "quia molestiae reprehenderit quasi aspernatur\naut
expedita occaecati aliquam eveniet laudantium\nomnis
quibusdam delectus saepe quia accusamus maiores nam
est\ncum et ducimus et vero voluptates excepturi
deleniti ratione"
  },
  {
    "postId": 1,
    "id": 4,
    "name": "alias odio sit",
    "email": "Lew@alysha.tv",
    "body": "non et atque\noccaecati deserunt quas accusantium
unde odit nobis qui voluptatem\nquia voluptas
consequuntur itaque dolor\net qui rerum deleniti ut
occaecati"
  },
  {
    "postId": 1,
    "id": 5,
    "name": "vero eaque aliquid doloribus et culpa",
    "email": "Hayden@althea.biz",

11
Chapter 1 Beginning with Flask

    "body": "harum non quasi et ratione\ntempore iure ex


voluptates in ratione\nharum architecto fugit
inventore cupiditate\nvoluptates magni quo et"
  }]

Figure 1-4. HTTP sample response

In the preceding figure, “HTTP/2” is the response HTTP version and


“200” is the response code. The part below that till “cf-ray” is the response
headers, and the array of post comments below “cf-ray” is the response
body of the request.

Links Between Resources


A resource is the fundamental concept in the world of REST architecture.
A resource is an object with a type, associated data, and relationships to
other resources alongside a set of methods that can be executed on it.
The resource in a REST API can contain link to other resources which
should drive the process flow. Such as in the case of a HTML web page in

12
Chapter 1 Beginning with Flask

which the links in the homepage drive the user flow, resources in REST API
should be able to drive the flow without the user knowing the process map.

Listing 1-4. A Book with Link to Buy

{
      "ID": "1",
      "Name": "Building REST APIs wiith Flask",
      "Author": "Kunal Relan",
      "Publisher": "Apress",
       "URI" : "https://apress.com/us/book/123456789"
}

Caching
Caching is a technique that stores a copy of a given resource and serves it
back when requested, saving extra DB calls and processing time. It can be
done at different levels like the client, the server, or a middleware proxy
server. Caching is an important tool for increasing the API performance
and scaling the application; however, if not managed properly, it results
in the client being served old results. Caching in REST APIs is controlled
using HTTP headers. Cache headers have been an essential part of HTTP
header specifications and have been an important part of scaling web
services with efficiency. In REST specification, when a safe method is used
on a resource URL, usually the reverse proxy caches the results to use the
cached data when the same resource is requested the next time.

Stateless
Each request from client to server must contain all of the
information necessary to understand the request, and can-
not take advantage of any stored context on the server.
Session state is therefore kept entirely on the client
—Roy Fielding
13
Chapter 1 Beginning with Flask

Statelessness here means that every HTTP response is a complete entity


in itself and enough to serve the purpose of providing information to
be executed without any need of another HTTP request. The point of
statelessness is to defeat the purpose of accord with the server allowing
intended flexibility in the infrastructure. To facilitate the same, REST
servers provide enough information in the HTTP response that the client
may need. Statelessness is an essential part of being able to scale the
infrastructure enabling us to deploy multiple servers to serve millions
of concurrent users given the fact that there is no server session state
dependency. It also enables the caching feature of REST infrastructure as
it lets the caching server to decide whether to cache the request or not, just
by looking at the particular request irrespective of any previous requests.

Planning REST API


Here is a list of things we need to check while planning to create REST APIs:

1. Understanding the use case. It is really important


to know why you are building the API and what
services will the API provide.

2. Listing down API features to understand what all


actions your APIs are going to do. This also includes
listing down actions and grouping them together to
tackle redundant endpoints.

3. Identify different platforms that’ll use the API and


provide support accordingly.

4. Plan long term on supporting growth and scaling


the infrastructure.
5. Plan API versioning strategy ensuring continuous
support is maintained over different versions of the APIs.

14
Chapter 1 Beginning with Flask

6. Plan API access strategy, that is, authentication,


ACL, and throttling.

7. Plan API documentation and testing.

8. Understand how to use hypermedia with your APIs.

So, these are the eight important things to ensure while planning your
API and are really crucial for developing a stable, production-focused API
system.

API Design
Now let’s look into API design. Here we’ll cover the standards of designing
REST APIs keeping in mind the list of things we just talked about.

Long-Term Implementation
Long-term implementation helps you analyze the flaws in design before
actual implementation. This helps the developers to choose the right kind
of platforms and tools to build upon making sure the same system can be
scaled for more users later.

Spec-Driven Development
Spec-driven development enforces API design using definition and not just
the code, which ensures that the changes are made to the codebase while
the API design is intact. It is good practice to use a tool like API Designer
to understand the API design before development which also lets you
foresee the flaws. Tools like swagger or RAML let you keep the API design
standardized and enable you to port the API to different platforms if needed.

15
Chapter 1 Beginning with Flask

Prototyping
Once the API specs are put in place, prototyping helps you visualize the
API before actual development by letting the developers create MOCK API
to help them understand every potential aspect of the API.

Authentication and Authorization


Authentication involves the verification process to know who the person
is, but it just doesn’t involve giving access to all the resources yet, and
that’s where authorization comes in, which involves authorizing an
authenticated person to keep a check on resources allowed to access using
an Access Control List (ACL).
We have different ways of authenticating and authorizing users
like basic authentication, HMAC, and OAuth. OAuth 2.0 is however
a preferred method for the same and is a standard protocol used
by enterprises as well as small companies for authentication and
authorization in their REST APIs.
So, these are the key features of the REST infrastructure, and we’ll
discuss more about how REST works and enables better communication in
later chapters.
Now, we’ll start with setting up our development environment and
understand some key factors of developing applications with Python.

Setting Up Development Environment


In this part, we’ll discuss setting up Python development environment
for a Flask application. We’ll use virtual environments for a separate
isolated environment for our dependencies. We’ll use PIP for installing and
managing our dependencies and a couple of other helpful utilities in the
process of setting up our development environment. For the sake of this
book, we’ll be doing everything on macOS Mojave and Python 2.7, but you

16
Chapter 1 Beginning with Flask

can feel free to use any operating system as per your convenience. So if you
don’t have the right version of Python installed in your operating system,
you can go ahead with installing Python on your choice of operating
system using this link: www.python.org/downloads/ (Figure 1-5).

Figure 1-5. Python download

W
 orking with PIP
PIP is a PyPi recommended tool for project dependency management. PIP
comes preinstalled with Python if you are using Python downloaded from
www.python.org.
However, if you don’t have PIP installed in your system, follow the
guide here to install PIP.
In order to install PIP, download get-pip.py by using the following
command in your terminal (or command line in Windows).

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

17
Chapter 1 Beginning with Flask

Once you have the get-pip.py file, install and run the next command:

$ python get-pip.py

The previous command will install PIP, setuptools (required for


installing source distributions), and wheel.
If you already have PIP, you can upgrade to the latest version of pip
using the following command:

$ pip install -U pip

To test your installation, you should run the following command


(Figure 1-6) in your terminal (or command line in Windows):

$ python -V
$ pip -V

Figure 1-6. Checking Python and PIP installation

C
 hoosing the IDE
Before we start writing the code, we’ll need something to write with.
Throughout this book, we’ll use Visual Studio Code which is an open
source and free IDE available on all major operating systems. Visual Studio
Code is available to download from www.code.visualstudio.com, and it
provides good support for developing Python applications with plenty of
handy plugins to facilitate development. You can choose to use your own
preferred text editor or IDE to follow this book (Figure 1-7).

18
Chapter 1 Beginning with Flask

Figure 1-7. Visual Studio Code

Once we have the IDE setup, we can move to installing and setting up
the virtual environment.

Understanding Python Virtual Environments


Python, just like other modern programming languages, provides a huge
amount of third-party libraries and SDKs. Different applications might need
various specific versions of third-party modules, and it won’t be possible for
one Python installation to meet such requirements of every application. So,
in the world of Python, the solution for this problem is virtual environment,
which creates a separate self-contained directory tree containing a Python
installation of the required version alongside the required packages.
At its core, the main purpose of a virtual environment is to create an
isolated environment to contain an installation of Python and required
packages for the application. There is no limit to the number of virtual
environments you can create, and it’s super easy to create them.

19
Chapter 1 Beginning with Flask

Using Virtual Environments


In Python 2.7 we need a module called virtualenv which is installed using
PIP to get started with Python virtual environments.

Note In Python 3 the venv module comes preshipped as a part of


the standard library.

To install virtualenv, type the following command in your terminal


(or command line in case of Windows).

$ pip install virtualenv

Once we have the virtualenv module installed in our system, next we’ll
create a new directory and create a virtual environment in it.
Now, type the following command to create a new directory and open
it in your terminal.

$ mkdir pyenv && cd pyenv

The preceding command will create a directory and open it in your


terminal, and then we’ll use the virtualenv module to create a new virtual
environment inside the directory.

$ virtualenv venv

The previous command will use the virtualenv module and create a
virtual environment called venv. You can name your virtual environment
anything, but for this book, we’ll just use venv for the sake of uniformity.
Once this command stops executing, you’ll see a directory called venv.
This directory will now hold your virtual environment.
The directory structure of the venv folder should be similar to the one
in Figure 1-8.

20
Chapter 1 Beginning with Flask

Figure 1-8. Virtual environment directory structure

Here is what each folder in the structure contains:

1. bin: Files to interact with the virtual environment.

2. include: C headers to compile the Python packages.

3. lib: This folder contains a copy of the Python version


and all the other third-party modules.

Next, there are copies of, or symlinks to, different Python tools to
ensure all the Python code and commands are executed within the current
environment. The important part here is the activation scripts in bin
folder, which sets the shell to use the virtual environment’s Python and site
packages. In order to do so, you need to activate the virtual environment by
typing the following command in your terminal.

$ source venv/bin/activate

Once this command is executed, your shell prompt will be prefixed


with the name of the virtual environment, just as in Figure 1-9.

21
Chapter 1 Beginning with Flask

Figure 1-9. Activating virtual environment

Now, let’s install Flask in our virtual environment using the following
command:

$ pip install flask

The preceding command should install Flask in our virtual


environment. We’ll use the same code we did in our sample Flask
application.

$ nano app.py

And type the following code in the nano text editor:

from flask import Flask


app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, From Flask!'

Now,  try running your app.py using python app.py command.

$ FLASK_APP=app.py flask run

With the preceding command, you should be able to run the simple
Flask application, and you should see similar output in your terminal
(Figure 1-10).

22
Chapter 1 Beginning with Flask

Figure 1-10. Running Flask application in virtual environment

Now, to deactivate the virtual environment, you need to execute the


following command:

$ deactivate

After this command executes, (venv) prefix from the shell will go
away, and if you try running the application again, it will throw an error
(Figure 1-11).

Figure 1-11. Running Flask application without virtual


environment

So now you understand the concept of virtual environments, we can


dig a little deeper and understand what’s happening inside the virtual
environment.
Understanding how virtual environments work can really help you
debug the application and understand the execution environment. To
start with, let’s check out the Python executable with virtual environment
activated and deactivated, in order to understand the basic difference.
Let’s execute the following command with virtual environment
activated (Figure 1-12):

$ which python

23
Chapter 1 Beginning with Flask

Figure 1-12. Checking Python executable with virtual environment

As you see in the following figure, the shell is using virtual


environment’s Python executable, and if you deactivate the environment
and re-run the Python command, you’ll notice the shell is now using the
system’s Python (Figure 1-13).

Figure 1-13. Checking Python executable without virtual


environment

So once you activate the virtual environment, the $path environment


variable is modified to point at our virtual environment, and thus the
Python in our virtual environment is used rather than the system one.
However, an important thing to notice here is that it is basically a copy of,
or a symlink to, the system’s Python executable.

S
 etting Up Flask
We have already installed Flask in the earlier module, but let’s start over
and setup the Flask microframework.

24
Chapter 1 Beginning with Flask

I nstalling Flask
With virtual environment activated, execute the following command to
install the latest version of Flask.

$pip install flask

The preceding command will install Flask in your virtual environment.


However, if you wish to work with the latest Flask before release,
install/update the Flask module using the master branch of its repository
by executing the following command:

$pip install -U https://github.com/pallets/flask/archive/


master.tar.gz

When you install Flask, the following distributions are installed with
the main framework:

1. Werkzeug (http://werkzeug.pocoo.org/):
Werkzeug implements WSGI, the standard Python
interface between the application and the server.

2. Jinja (http://jinja.pocoo.org/): Jinja is the


templating engine in Flask which renders the pages
for the application.

3. MarkupSafe (https://pypi.org/project/
MarkupSafe/): Markupsafe comes preshipped with
Jinja, which helps escape an untrusted user input to
escalate injection attacks.

4. ItsDangerous(https://pythonhosted.org/
itsdangerous/): ItsDangerous is responsible for
securely signing data to ensure data integrity and is
used to protect Flask session cookies.

25
Chapter 1 Beginning with Flask

5. Click (http://click.pocoo.org/): Click is a


framework to write CLI applications. It provides the
“Flask” CLI command.

C
 onclusion
Once you have Flask installed in your virtual environment, you are ready
to go to the next step of the development phase. Before we do that, we’ll
discuss about MySQL and Flask-SQLAlchemy which is the ORM that
we’ll use in our Flask application. Database is an essential part of a REST
application, and in the next chapter, we’ll discuss the MySQL database
and Flask-SQLAchemy ORM and also learn how to connect our Flask
application with Flask-SQLAlchemy.

26
CHAPTER 2

Database Modeling
in Flask
This chapter covers one of the most important aspects of REST application
development, that is, connecting and interacting with database systems.
In this chapter, we’ll discuss about NoSQL and SQL databases, connecting
and interacting with them.
In this chapter we’ll cover the following topics:

1. NoSQL vs. SQL databases

2. Connecting with Flask-SQLAlchemy

3. Interacting with MySQL DB using Flask-­


SQLAlchemy

4. Connecting with Flask-MongoEngine

5. Interacting with MongoDB using Flask-­


MongoEngine

I ntroduction
Flask being a microframework provides flexibility of the data source for
applications and also provides library support for interacting with different
kinds of data sources. There are libraries to connect to SQL- and ­NoSQL-­

© Kunal Relan 2019 27


K. Relan, Building REST APIs with Flask, https://doi.org/10.1007/978-1-4842-5022-8_2
Chapter 2 Database Modeling in Flask

based databases in Flask. It also provides the flexibility to interact with


databases using raw DB libraries or using ORM (Object Relational Mapper)
/ODM (Object Document Mapper). In this chapter, we’ll briefly discuss
NoSQL- and SQL-based databases and learn using ORM layer for our Flask
application using Flask-SQLAlchemy, after which we’ll use ODM layer
using Flask-MongoEngine.
Most applications do need databases at some point, and MySQL and
MongoDB are just two of the many tools for doing it. Choosing the right
one for your application will entirely depend on the data you are going to
store. If your datasets in tables are related to each other, SQL databases is
the way to go or NoSQL databases can serve the purpose too.
Now, let’s have a brief look over SQL vs. NoSQL databases.

SQL Databases
SQL databases use Structured Query Language (SQL) for data
manipulation and definition. SQL is a versatile, widely used and accepted
option which makes it a great choice for data storing. SQL systems
work great when the data in use needs to be relational and the schema
is predefined. However, a predefined schema also serves as a con, as it
requires the whole dataset to follow the same structure which might turn
out to be tough in some situations. SQL databases store data in forms of
tables made up of rows and columns and are vertically scalable.

NoSQL Databases
NoSQL databases have a dynamic schema for unstructured data and store
data in different ways ranging from column-based (Apache Cassandra),
document-based (MongoDB), and graph-based (Neo4J) or as a key-­
value store (Redis). This provides the flexibility to store data without a
predefined structure and versatility to add fields to the data structure
on the go. Being schemaless is the key distinction of NoSQL databases,

28
Chapter 2 Database Modeling in Flask

and it also makes them better suited for distributed systems. Unlike SQL
databases, NoSQL databases are horizontally scalable.
Now that we have briefly explained SQL and NoSQL databases, we’ll
jump to functional differences between MySQL and MongoDB since these
are the two database engines we’ll be looking at in this chapter.

Key Differences: MySQL vs. MongoDB


So as discussed earlier, MySQL is a SQL-based database which stores
data in tables with columns and rows and only works on structured
data. MongoDB, on the other hand, can handle unstructured data and
stores JSON-like documents rather than tables and uses MongoDB query
language to communicate with the DB. MySQL is an extremely established
database with a huge community and great stability, and MongoDB is
a fairly new technology with growing community and is developed by
MongoDB Inc. MySQL is vertically scalable in which the load on the single
server can be increased by upgrading the RAM, SSD, or CPU, while in
the case of MongoDB, which is horizontally scalable, it needs to share
and add more servers in order to increase server load. MongoDB is the
preferred choice for high write loads and big datasets, and MySQL is a
perfect fit for applications that depends highly on multi-row transactions
like accounting systems. MongoDB is a great choice for applications with
dynamic structure and high data load such as that of a real-time analytics
application or a content management system.
Flask provides support for interacting with both MySQL and
MongoDB. There are various native drivers as well as ORM/ODM for
communication with the database. Flask-MySQL is a Flask extension that
allows native connection to MySQL; Flask-PyMongo is a native extension
for working with MongoDB in Flask and is recommended by MongoDB as
well. Flask-MongoEngine is a Flask extension, ODM for Flask to work with
MongoDB. Flask-SQLAlchemy is an ORM layer for Flask applications to
connect with MySQL.

29
Chapter 2 Database Modeling in Flask

Next, we’ll discuss about Flask-SQLAlchemy and Flask- MongoEngine


and create Flask CRUD applications using them.

 reating a Flask Application


C
with SQLAlchemy
Flask-SQLAlchemy is an extension for flask which adds support for
SQLAlchemy to the application. SQLAlchemy is a Python toolkit and
Object Relational Mapper that provides access to the SQL database using
Python. SQLAlchemy comes with enterprise-level persistence patterns
and efficient and high performing database access. Flask-SQLAlchemy
provides support for the following SQL-based database engines given the
appropriate DBAPI driver is installed:

• PostgreSQL

• MySQL

• Oracle

• SQLite

• Microsoft SQL Server

• Firebird SyBase

We’ll be using MySQL as the database engine in our application, so let’s


get started with installing SQLAlchemy and start setting up our application.
Let’s create a new directory called flask-MySQL, create a virtual
environment, and then install flask-sqlalchemy.

$ mkdir flask-mysql && cd flask-mysql

Now, create a virtual environment inside the directory using the


following command:

$ virtualenv venv

30
Chapter 2 Database Modeling in Flask

As discussed earlier, we can activate the virtual environment using the


following command:

$ source venv/bin/activate

Once the virtual environment is activated, let’s install flask-sqlalchemy.


Flask and Flask-SQLAlchemy can be installed using PIP with the
following command.

(venv)$ pip install flask flask-sqlalchemy

Other than SQLite, all other database engines need separate libraries
to be installed alongside Flask-SQLAlchemy for it to work. SQLAlchemy
uses MySQL-Python as the default DBAPI for connecting with MySQL.
Now, let’s install PyMySQL to enable MySQL connection with Flask-­
SQLAlchemy.

(venv) $ pip install pymysql

Now, we should have everything we need to create our sample flask-­


MySQL application with.
Let’s start by creating app.py which will contain the code for our
application. After creating the file, we’ll initiate the Flask application.

from flask import Flask


from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =
'mysql+pymysql://<mysql_username>:<mysql_password>@<mysql_
host>:<mysql_port>/<mysql_db>'
db = SQLAlchemy(app)

if __name__ == "__main__":
    app.run(debug=True)

31
Chapter 2 Database Modeling in Flask

Here, we import the Flask framework and Flask-SQLAlchemy and


then initiate an instance of Flask. After that, we configure the SQLAlchemy
database URI to use our MySQL DB URI, and then we create an object of
SQLAlchemy named as db, which will handle our ORM-related activities.
Now, if you are using MySQL, make sure you supply connection strings
of a running MySQL server and that the database name supplied does exist.

Note Use environment variables for supplying database connection


strings in your applications.

Make sure that you have a running MySQL server to follow this
application. However, you can also use SQLite in its place by supplying the
SQLite config details in the SQLAlchemy database URI which should look
like this:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/
<db_name>.db'

In order to run the application, you need to execute the following code
in your terminal:

(venv) $ python app.py

And if there are no errors, you should see a similar output in your
terminal:

(venv) $ python app.py


* Serving Flask app "app" (lazy loading)
* Environment: production
   WARNING: Do not use the development server in a production
environment.
   Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

32
Chapter 2 Database Modeling in Flask

* Restarting with stat


* Debugger is active!
* Debugger PIN: 779-301-240

Creating an Author Database


We’ll now create an author database application which will provide
RESTful CRUD APIs. All the authors will be stored in a table titled “authors”.
After the declared db object, add the following lines of code to declare
a class as Authors which will hold the schema for the author table:

class Author (db.Model):


    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20))
    specialisation = db.Column(db.String(50))

    def __init__(self, name, specialisation):


        self.name = name
        self.specialisation = specialisation
    def __repr__(self):
      return '<Product %d>' % self.id
db.create_all()

With this code, we have created a model titled “Authors” which has three
fields—ID, name, and specialisation. Name and specialisation are strings,
but ID is a self-generated and auto-incremented integer which will serve
as a primary key. Notice the last line “db.create_all()” which instructs the
application to create all the tables and database specified in the application.
In order to serve JSON response from our API using the data returned by
SQLAlchemy, we need another library called marshmallow which is an add-
on to SQLAlchemy to serialize SQLAlchemy-returned data objects to JSON.

(venv)$ pip install flask-marshmallow

33
Chapter 2 Database Modeling in Flask

The following command will install the Flask version of marshmallow


in our application, and we’ll define our output schema from the Authors
model using marshmallow.
Add the following lines on the top, below the other imports in your
application file to import marshmallow.

from marshmallow_sqlalchemy import ModelSchema


from marshmallow import fields

After the db.create_all(), define your output schema using the


following code:

class AuthorSchema(ModelSchema):
    class Meta(ModelSchema.Meta):
        model = Authors
        sqla_session = db.session

    id = fields.Number(dump_only=True)
    name = fields.String(required=True)
    specialisation = fields.String(required=True)

The preceding code maps the variable attribute to field objects, and in
Meta, we define the model to relate to our schema. So this should help us
return JSON from SQLAlchemy.
After setting up our model and return schema, we can jump to creating
our endpoints. Let’s create our first GET /authors endpoint to return all
the registered authors. This endpoint will query for all the objects in the
Authors model and return them in JSON to the user. But before we write
the endpoint, edit the first import line to the following to import jsonify,
make_response, and request from Flask.

from flask import Flask, request, jsonify, make_response

And after the AuthorSchema, write your first endpoint /authors with
the following code:

34
Exploring the Variety of Random
Documents with Different Content
CHAPTER V.
ANALYSIS OF THE CHAPTER.

This chapter introduces the disclosure of future events. It is done


in a manner eminently fitted to impress the mind with a sense of the
importance of the revelations about to be made. The proper state of
mind for appreciating this chapter is that when we look on the
future, and are sensible that important events are about to occur;
when we feel that that future is wholly impenetrable to us; and
when the efforts of the highest created minds fail to lift the
mysterious veil which hides those events from our view; it is in
accordance with our nature that the mind should be impressed with
solemn awe under such circumstances; it is not a violation of the
laws of our nature that one who had an earnest desire to penetrate
that future, and who saw the volume before him which contained
the mysterious revelation, and who yet felt that there was no one in
heaven or earth who could break the seals, and disclose what was to
come, should weep. Comp. ver. 4. The design of the whole chapter
is evidently to honour the Lamb of God, by showing that the power
was intrusted to him which was confided to no one else in heaven or
earth, of disclosing what is to come. Nothing else would better
illustrate this than the fact that he alone could break the mysterious
seals which barred out the knowledge of the future from all created
eyes; and nothing would be better adapted to impress this on the
mind than the representation in this chapter—the exhibition of a
mysterious book in the hand of God; the proclamation of the angel,
calling on any who could do it to open the book; the fact that no one
in heaven or earth could do it; the tears shed by John when it was
found that no one could do it; the assurance of one of the elders
that the Lion of the tribe of Judah had power to do it; and the
profound adoration of all in heaven, and in earth, and under the
earth in view of the power intrusted to him of breaking these
mysterious seals.

The main points in the chapter are these: (1) Having in ch. iv.
described God as sitting on a throne, John here (ver. 1) represents
himself as seeing in his right hand a mysterious volume; written all
over on the inside and the outside, yet sealed with seven seals; a
volume manifestly referring to the future, and containing important
disclosures respecting coming events. (2) A mighty angel is
introduced making a proclamation, and asking who is worthy to
open that book, and to break those seals; evidently implying that
none unless of exalted rank could do it, ver. 2. (3) There is a pause:
no one in heaven, or in earth, or under the earth, approaches to do
it, or claims the right to do it, ver. 3. (4) John, giving way to the
expressions of natural emotion—indicative of the longing and intense
desire in the human soul to be made acquainted with the secrets of
the future—pours forth a flood of tears because no one is found who
is worthy to open the seals of this mysterious book, or to read what
was recorded there, ver. 4. (5) In his state of suspense and of grief,
one of the elders—the representatives of that church for whose
benefit these revelations of the future were to be made (Note on
ch. iv. 4)—approaches him and says that there is one who is able to
open the book; one who has the power to loose its seals, ver. 5. This
is the Messiah—the Lion of the tribe of Judah, the Root of David—
coming now to make the disclosure for which the whole book was
given, ch. i. 1. (6) Immediately the attention of John is attracted by
the Messiah, appearing as a Lamb in the midst of the throne; with
horns, the symbols of strength; and eyes, the symbols of all-
pervading intelligence. He approaches and takes the book from the
hand of Him that sits on the throne; symbolical of the fact that it is
the province of the Messiah to make known to the church and the
world the events which are to occur, ver. 6, 7. He appears here in a
different form from that in which he manifested himself in ch. i., for
the purpose is different. There he appears clothed in majesty, to
impress the mind with a sense of his essential glory. Here he
appears in a form that recalls the memory of his sacrifice; to denote,
perhaps, that it is in virtue of his atonement that the future is to be
disclosed; and that therefore there is a special propriety that he
should appear and do what no other one in heaven or earth could
do. (7) The approach of the Messiah to unfold the mysteries in the
book, the fact that he had “prevailed” to accomplish what there was
so strong a desire should be accomplished, furnishes an occasion for
exalted thanksgiving and praise, ver. 8‒10. (8) This ascription of
praise in heaven is instantly responded to, and echoed back, from all
parts of the universe—all joining in acknowledging the Lamb as
worthy of the exalted office to which he was raised, ver. 11‒13. The
angels around the throne—amounting to thousands of myriads—
unite with the living creatures and the elders; and to these are
joined the voices of every creature in heaven, on the earth, under
the earth, and in the sea, ascribing to Him that sits upon the throne
and the Lamb universal praise. (9) To this loud ascription of praise
from far-distant worlds the living creatures respond a hearty Amen,
and the elders fall down and worship him that lives for ever and
ever, ver. 14. The universe is held in wondering expectation of the
disclosures which are to be made, and from all parts of the universe
there is an acknowledgment that the Lamb of God alone has the
right to break the mysterious seals. The importance of the
developments justifies the magnificence of this representation; and
it would not be possible to imagine a more sublime introduction to
these great events.

CHAPTER V.

A ND I saw in the right hand of him that sat


on the throne a 194book written within
195
and on the back side, sealed with seven
seals.
1. And I saw in the right hand of him that sat on the throne. Of
God, ch. iv. 3, 4. His form is not described there, nor is there any
intimation of it here except the mention of his “right hand.” The
book or roll seems to have been so held in his hand that John could
see its shape, and see distinctly how it was written and sealed.
¶ A book—βιβλίον. This word is properly a diminutive of the word
commonly rendered book (βίβλος), and would strictly mean a small
book, or a book of diminutive size—a tablet, or a letter (Liddell and
Scott, Lex.). It is used, however, to denote a book of any size—a roll,
scroll, or volume; and is thus used (a) to denote the Pentateuch, or
the Mosaic law, He. ix. 19; x. 7; (b) the book of life, Re. xvii. 8;
xx. 12; xxi. 27; (c) epistles which were also rolled up, Re. i. 11;
(d) documents, as a bill of divorce, Mat. xix. 7; Mar. x. 4. When it is
the express design to speak of a small book, another word is used
(βιβλαρίδιον), Re. x. 2, 8, 9, 10. The book or roll referred to here
was that which contained the revelation in the subsequent chapters,
to the end of the description of the opening of the seventh seal—for
the communication that was to be made was all included in the
seven seals; and to conceive of the size of the book, therefore, we
are only to reflect on the amount of parchment that would naturally
be written over by the communications here made. The form of the
book was undoubtedly that of a scroll or roll; for that was the usual
form of books among the ancients, and such a volume could be
more easily sealed with a number of seals, in the manner here
described, than a volume in the form in which books are made now.
On the ancient form of books, see Notes on Lu. iv. 17. The engraving
in Job, ch. xix., will furnish an additional illustration of their form.
¶ Written within and on the back side. Gr., “within and behind.” It
was customary to write only on one side of the paper or vellum, for
the sake of convenience in reading the volume as it was unrolled. If,
as sometimes was the case, the book was in the same form as
books are now—of leaves bound together—then it was usual to write
on both sides of the leaf, as both sides of a page are printed now.
But in the other form it was a very uncommon thing to write on both
sides of the parchment, and was never done unless there was a
scarcity of writing material; or unless there was an amount of matter
beyond what was anticipated; or unless something had been
omitted. It is not necessary to suppose that John saw both sides of
the parchment as it was held in the hand of him that sat on the
throne. That it was written on the back side he would naturally see,
and, as the book was sealed, he would infer that it was written in
the usual manner on the inside. ¶ Sealed with seven seals. On the
ancient manner of sealing, see Notes on Mat. xxvii. 66; comp. Notes
on Job xxxviii. 14. The fact that there were seven seals—an unusual
number in fastening a volume—would naturally attract the attention
of John, though it might not occur to him at once that there was
anything significant in the number. It is not stated in what manner
the seals were attached to the volume, but it is clear that they were
so attached that each seal closed one part of the volume, and that
when one was broken and the portion which that was designed to
fasten was unrolled, a second would be come to, which it would be
necessary to break in order to read the next portion. The outer seal
would indeed bind the whole; but when that was broken it would not
give access to the whole volume unless each successive seal were
broken. May it not have been intended by this arrangement to
suggest the idea that the whole future is unknown to us, and that
the disclosure of any one portion, though necessary if the whole
would be known, does not disclose all, but leaves seal after seal still
unbroken, and that they are all to be broken one after another if we
would know all? How these were arranged, John does not say. All
that is necessary to be supposed is, that the seven seals were put
successively upon the margin of the volume as it was rolled up, so
that each opening would extend only as far as the next seal, when
the unrolling would be arrested. Anyone, by rolling up a sheet of
paper, could so fasten it with pins, or with a succession of seals, as
to represent this with sufficient accuracy.
2 And I saw a strong angel proclaiming with
a loud voice, Who is worthy to open the book,
and to loose the seals thereof?
2. And I saw a strong angel. An angel endowed with great
strength, as if such strength was necessary to enable him to give
utterance to the loud voice of the inquiry. “Homer represents his
heralds as powerful, robust men, in order consistently to attribute to
them deep-toned and powerful voices” (Prof. Stuart). The inquiry to
be made was one of vast importance; it was to be made of all in
heaven, all on the earth, and all under the earth, and hence an
angel is introduced so mighty that his voice could be heard in all
those distant worlds. ¶ Proclaiming with a loud voice. That is, as a
herald or crier. He is rather introduced here as appointed to this
office than as self-moved. The design undoubtedly is to impress the
mind with a sense of the importance of the disclosures about to be
made, and at the same time with a sense of the impossibility of
penetrating the future by any created power. That one of the highest
angels should make such a proclamation would sufficiently show its
importance; that such an one, by the mere act of making such a
proclamation, should practically confess his own inability, and
consequently the inability of all of similar rank, to make the
disclosures, would show that the revelations of the future were
beyond mere created power. ¶ Who is worthy to open the book, &c.
That is, who is “worthy” in the sense of having a rank so exalted,
and attributes so comprehensive, as to authorize and enable him to
do it. In other words, who has the requisite endowments of all kinds
to enable him to do it? It would require moral qualities of an exalted
character to justify him in approaching the seat of the holy God, to
take the book from his hands; it would require an ability beyond that
of any created being to penetrate the future, and disclose the
meaning of the symbols which were employed. The fact that the
book was held in the hand of him that was on the throne, and
sealed in this manner, was in itself a sufficient proof that it was not
his purpose to make the disclosure directly, and the natural inquiry
arose whether there was anyone in the wide universe who, by rank,
or character, or office, would be empowered to open the mysterious
volume.

3 And no man in heaven, nor in earth,


neither under the earth, was able to open the
book, neither to look thereon.
3. And no man in heaven. No one—οὐδεὶς. There is no limitation
in the original to man. The idea is, that there was no one in heaven
—evidently alluding to the created beings there—who could open the
volume. Is it not taught here that angels cannot penetrate the
future, and disclose what is to come? Are not their faculties limited
in this respect like those of man? ¶ Nor in earth. Among all classes
of men—sages, divines, prophets, philosophers—who among those
have ever been able to penetrate the future, and disclose what is to
come? ¶ Neither under the earth. These divisions compose, in
common language, the universe: what is in heaven above; what is
on the earth; and whatever there is under the earth—the abodes of
the dead. May there not be an allusion here to the supposed science
of necromancy, and an assertion that even the dead cannot
penetrate the future, and disclose what is to come? Comp. Notes on
Is. viii. 19. In all these great realms no one advanced who was
qualified to undertake the office of making a disclosure of what the
mysterious scroll might contain. ¶ Was able to open the book. Had
ability—ἠδύνατο—to do it. It was a task beyond their power. Even if
anyone had been found who had a rank and a moral character which
might have seemed to justify the effort, there was no one who had
the power of reading what was recorded respecting coming events.
¶ Neither to look thereon. That is, so to open the seals as to have a
view of what was written therein. That it was not beyond their
power merely to see the book is apparent from the fact that John
himself saw it in the hand of him that sat on the throne; and it is
evident also (ver. 5) that in that sense the elders saw it. But no one
could prevail to inspect the contents, or so have access to the
interior of the volume as to be able to see what was written there. It
could be seen, indeed (ver. 1), that it was written on both sides of
the parchment, but what the writing was no one could know.

4 And I wept much, because no man was


found worthy to open and to read the book,
neither to look thereon.
4. And I wept much, because no man was found worthy, &c. Gr.,
as in ver. 3, no one. It would seem as if there was a pause to see if
there were any response to the proclamation of the angel. There
being none, John gave way to his deep emotions in a flood of tears.
The tears of the apostle here may be regarded as an illustration of
two things which are occurring constantly in the minds of men:
(1) The strong desire to penetrate the future; to lift the mysterious
veil which shrouds that which is to come; to find some way to pierce
the dark wall which seems to stand up before us, and which shuts
from our view that which is to be hereafter. There have been no
more earnest efforts made by men than those which have been
made to read the sealed volume which contains the record of what
is yet to come. By dreams, and omens, and auguries, and astrology,
and the flight of birds, and necromancy, men have sought anxiously
to ascertain what is to be hereafter. Compare, for an expression of
that intense desire, Foster’s Life and Correspondence, vol. i. p. 111,
and vol. ii. pp. 237, 238. (2) The weeping of the apostle may be
regarded as an instance of the deep grief which men often
experience when all efforts to penetrate the future fail, and they feel
that after all they are left completely in the dark. Often is the soul
overpowered with grief, and often are the eyes filled with sadness at
the reflection that there is an absolute limit to the human powers;
that all that man can arrive at by his own efforts is uncertain
conjecture, and that there is no way possible by which he can make
nature speak out and disclose what is to come. Nowhere does man
find himself more fettered and limited in his powers than here;
nowhere does he feel that there is such an intense disproportion
between his desires and his attainments. In nothing do we feel that
we are more absolutely in need of divine help than in our attempts
to unveil the future; and were it not for revelation man might weep
in despair.

5 And one of the elders saith unto me, Weep


not: behold, the 196Lion of the tribe of Judah,
the 197Root of David, hath prevailed to open the
book, and to loose the seven seals thereof.
5. And one of the elders saith unto me. See Notes on ch. iv. 4. No
particular reason is assigned why this message was delivered by one
of the elders rather than by an angel. If the elders were, however
(see Notes on ch. iv. 4), the representatives of the church, there was
a propriety that they should address John in his trouble. Though
they were in heaven, they were deeply interested in all that
pertained to the welfare of the church, and they had been permitted
to understand what as yet was unknown to him, that the power of
opening the mysterious volume which contained the revelation of
the future was intrusted particularly to the Messiah. Having this
knowledge, they were prepared to comfort him with the hope that
what was so mysterious would be made known. ¶ Weep not. That is,
there is no occasion for tears. The object which you so much desire
can be obtained. There is one who can break those seals, and who
can unroll that volume and read what is recorded there. ¶ Behold
the Lion of the tribe of Judah. This undoubtedly refers to the Lord
Jesus; and the points needful to be explained are, why he is called a
Lion, and why he is spoken of as the Lion of the tribe of Judah.
(a) As to the first: This appellation is not elsewhere given to the
Messiah, but it is not difficult to see its propriety as used in this
place. The lion is the king of beasts, the monarch of the forest, and
thus becomes an emblem of one of kingly authority and of power
(see Notes on ch. iv. 7), and as such the appellation is used in this
place. It is because Christ has power to open the seals—as if he
ruled over the universe, and all events were under his control, as the
lion rules in the forest—that the name is here given to him. (b) As to
the other point: He is called the “Lion of the tribe of Judah,”
doubtless, with reference to the prophecy in Ge. xlix. 9—“Judah is a
lion’s whelp: from the prey, my son, thou art gone up: he stooped
down, he couched as a lion, and as an old lion;” and from the fact
that the Messiah was of the tribe of Judah. Comp. Ge. xlix. 10. This
use of the term would connect him in the apprehension of John with
the prophecy, and would suggest to him the idea of his being a ruler,
or having dominion. As such, therefore, it would be appropriate that
the power of breaking these seals should be committed to him.
¶ The Root of David. Not the Root of David in the sense that David
sprung from him as a tree does from a root, but in the sense that he
himself was a “root-shoot” or sprout from David, and had sprung
from him as a shoot or sprout springs up from a decayed and fallen
tree. See Notes on Is. xi. 1. This expression would connect him
directly with David, the great and glorious monarch of Israel, and as
having a right to occupy his throne. As one thus ruling over the
people of God, there was a propriety that to him should be intrusted
the task of opening these seals. ¶ Hath prevailed. That is, he has
acquired this power as the result of a conflict or struggle. The word
used here—ἐνίκησεν—refers to such a conflict or struggle, properly
meaning to come off victor, to overcome, to conquer, to subdue; and
the idea here is, that his power to do this, or the reason why he
does this, is the result of a conflict in which he was a victor. As the
series of events to be disclosed, resulting in the final triumph of
religion, was the effect of his conflicts with the powers of evil, there
was a special propriety that the disclosure should be made by him.
The truths taught in this verse are, (1) that the power of making
disclosures, in regard to the future, is intrusted to the Messiah; and
(2) that this, so far as he is concerned, is the result of a conflict or
struggle on his part.
6 And I beheld, and, lo, in the midst of the
throne and of the four beasts, and in the midst
of the elders, stood a 198Lamb, as it had been
slain, having seven horns and seven199eyes,
which are the seven Spirits of God sent forth
into all the earth.
6. And I beheld, and, lo, in the midst of the throne. We are not to
suppose that he was in the centre of the throne itself, but he was a
conspicuous object when the throne and the elders and the living
beings were seen. He was so placed as to seem to be in the midst of
the group made up of the throne, the living beings, and the elders.
¶ And of the four beasts. See Notes, ch. iv. 6. ¶ Stood a Lamb. An
appellation often given to the Messiah, for two reasons: (1) because
the lamb was an emblem of innocence; and (2) because a lamb was
offered commonly in sacrifice. Comp. Notes on Jn. i. 29. ¶ As it had
been slain. That is, in some way having the appearance of having
been slain; having some marks or indications about it that it had
been slain. What those were the writer does not specify. If it were
covered with blood, or there were marks of mortal wounds, it would
be all that the representation demands. The great work which the
Redeemer performed—that of making an atonement for sin—was
thus represented to John in such a way that he at once recognized
him, and saw the reason why the office of breaking the seals was
intrusted to him. It should be remarked that this representation is
merely symbolic, and we are not to suppose that the Redeemer
really assumed this form, or that he appears in this form in heaven.
We should no more suppose that the Redeemer appears literally as a
lamb in heaven with numerous eyes and horns, than that there is a
literal throne and a sea of glass there; that there are “seats” there,
and “elders,” and “crowns of gold.” ¶ Having seven horns. Emblems
of authority and power—for the horn is a symbol of power and
dominion. Comp. De. xxxiii. 17; 1 Ki. xxii. 11; Je. xlviii. 25; Zec.
i. 18; Da. vii. 24. The propriety of this symbol is laid in the fact that
the strength of an animal is in the horn, and that it is by this that he
obtains a victory over other animals. The number seven here seems
to be designed, as in other places, to denote completeness. See
Notes on ch. i. 4. The meaning is, that he had so large a number as
to denote complete dominion. ¶ And seven eyes. Symbols of
intelligence. The number seven here also denotes completeness;
and the idea is, that he is able to survey all things. John does not
say anything as to the relative arrangement of the horns and eyes
on the “Lamb,” and it is vain to attempt to conjecture how it was.
The whole representation is symbolical, and we may understand the
meaning of the symbol without being able to form an exact
conception of the figure as it appeared to him, ¶ Which are the
seven Spirits of God sent forth into all the earth. See Notes on
ch. i. 4. That is, which represent the seven Spirits of God; or the
manifold operations of the one Divine Spirit. As the eye is the
symbol of intelligence—outward objects being made visible to us by
that—so it may well represent an all-pervading spirit that surveys
and sees all things. The eye, in this view, among the Egyptians was
an emblem of the Deity. By the “seven Spirits” here the same thing
is doubtless intended as in ch. i. 4; and if, as there supposed, the
reference is to the Holy Spirit considered with respect to his manifold
operations, the meaning here is, that the operations of that Spirit
are to be regarded as connected with the work of the Redeemer.
Thus, all the operations of the Spirit are connected with, and are a
part of, the work of redemption. The expression “sent forth into all
the earth,” refers to the fact that that Spirit prevades all things. The
Spirit of God is often represented as sent or poured out; and the
meaning here is, that his operations are as if he was sent out to
survey all things and to operate everywhere. Comp. 1 Co. xii. 6‒11.

7 And he came and took the book out of the


right hand of him that sat upon the throne.
7. And he came and took the book out of the right hand, &c. As if
it pertained to him by virtue of rank or office. There is a difficulty
here, arising from the incongruity of what is said of a lamb, which it
is not easy to solve. The difficulty is in conceiving how a lamb could
take the book from the hand of Him who held it. To meet this
several solutions have been proposed. (1) Vitringa supposes that the
Messiah appeared as a lamb only in some such sense as the four
living beings (ch. iv. 7) resembled a lion, a calf, and an eagle; that is,
that they bore this resemblance only in respect to the head, while
the body was that of a man. He thus supposes, that though in
respect to the upper part the Saviour resembled a lamb, yet that to
the front part of the body hands were attached by which he could
take the book. But there are great difficulties in this supposition.
Besides that nothing of this kind is intimated by John, it is contrary
to every appearance of probability that the Redeemer would be
represented as a monster. In his being represented as a lamb there
is nothing that strikes the mind as inappropriate or unpleasant, for
he is often spoken of in this manner, and the image is one that is
agreeable to the mind. But all this beauty and fitness of
representation is destroyed, if we think of him as having human
hands proceeding from his breast or sides, or as blending the form
of a man and an animal together. The representation of having an
unusual number of horns and eyes does not strike us as being
incongruous in the same sense; for though the number is increased,
they are such as pertain properly to the animal to which they are
attached. (2) Another supposition is that suggested by Professor
Stuart, that the form was changed, and a human form resumed
when the Saviour advanced to take the book and open it. This would
relieve the whole difficulty, and the only objection to it is, that John
has not given any express notice of such a change in the form; and
the only question can be whether it is right to suppose it in order to
meet the difficulty in the case. In support of this it is said that all is
symbol; that the Saviour is represented in the book in various forms;
that as his appearing as a lamb was designed to represent in a
striking manner the fact that he was slain, and that all that he did
was based on the atonement, so there would be no impropriety in
supposing that when an action was attributed to him he assumed
the form in which that act would be naturally or is usually done. And
as in taking a book from the hand of another it is wholly incongruous
to think of its being done by a lamb, is it not most natural to
suppose that the usual form in which the Saviour is represented as
appearing would be resumed, and that he would appear again as a
man?—But is it absolutely certain that he appeared in the form of a
lamb at all? May not all that is meant be, that John saw him near the
throne, and among the elders, and was struck at once with his
appearance of meekness and innocence, and with the marks of his
having been slain as a sacrifice, and spoke of him in strong figurative
language as a lamb? And where his “seven horns” and “seven eyes”
are spoken of, is it necessary to suppose that there was any real
assumption of such horns and eyes? May not all that is meant be
that John was struck with that in the appearance of the Redeemer of
which these would be the appropriate symbols, and described him
as if these had been visible? When John the Baptist saw the Lord
Jesus on the banks of the Jordan, and said, “Behold the Lamb of
God which taketh away the sin of the world” (Jn. i. 29), is it
necessary to suppose that he actually appeared in the form of a
lamb? Do not all at once understand him as referring to traits in his
character, and to the work which he was to accomplish, which made
it proper to speak of him as a lamb? And why, therefore, may we not
suppose that John in the Apocalypse designed to use language in
the same way, and that he did not intend to present so incongruous
a description as that of a lamb approaching a throne and taking a
book from the hand of Him that sat on it, and a lamb, too, with
many horns and eyes? If this supposition is correct, then all that is
meant in this passage would be expressed in some such language as
the following: “And I looked, and lo there was one in the midst of
the space occupied by the throne, by the living creatures, and by the
elders, who, in aspect, and in the emblems that represented his
work on the earth, was spotless, meek, and innocent as a lamb; one
with marks on his person which brought to remembrance the fact
that he had been slain for the sins of the world, and yet one who
had most striking symbols of power and intelligence, and who was
therefore worthy to approach and take the book from the hand of
Him that sat on the throne.” It may do something to confirm this
view to recollect that when we use the term “Lamb of God” now, as
is often done in preaching and in prayer, it never suggests to the
mind the idea of a lamb. We think of the Redeemer as resembling a
lamb in his moral attributes and in his sacrifice, but never as to form.
This supposition relieves the passage of all that is incongruous and
unpleasant, and may be all that John meant.

8 And when he had taken the book, the


200
four beasts and four and twenty elders fell
down before the Lamb, having every one of
them 201harps, and golden vials full of
202
odours, which are the 203prayers of saints.
8. And when he had taken the book, the four beasts, &c. The acts
of adoration here described as rendered by the four living creatures
and the elders are, according to the explanation given in ch. iv. 4‒7,
emblematic of the honour done to the Redeemer by the church, and
by the course of providential events in the government of the world.
¶ Fell down before the Lamb. The usual posture of profound
worship. Usually in such worship there was entire prostration on the
earth. See Notes on Mat. ii. 2; 1 Co. xiv. 25. ¶ Having every one of
them harps. That is, as the construction, and the propriety of the
case would seem to demand, the elders had each of them harps.
The whole prostrated themselves with profound reverence; the
elders had harps and censers, and broke out into a song of praise
for redemption. This construction is demanded, because (a) the
Greek word—ἔχοντες—more properly agrees with the word elders—
πρεσβύτεροι—and not with the word beasts—ζῶα; (b) there is an
incongruity in the representation that the living creatures, in the
form of a lion, a calf, an eagle, should have harps and censers; and
(c) the song of praise that is sung (ver. 9) is one that properly
applies to the elders as the representatives of the church, and not to
the living creatures—“Thou hast redeemed us to God by thy blood.”
The harp was a well-known instrument used in the service of God.
Josephus describes it as having ten strings, and as struck with a key
(Ant. vii. 12, 3). See Notes on Is. v. 12. ¶ And golden vials. The word
vial with us, denoting a small slender bottle with a narrow neck,
evidently does not express the idea here. The article here referred to
was used for offering incense, and must have been a vessel with a
large open mouth. The word bowl or goblet would better express the
idea, and it is so explained by Professor Robinson, Lex., and by
Professor Stuart, in loco. The Greek word—φιάλη—occurs in the New
Testament only in Revelation (v. 8; xv. 7; xvi. 1‒4, 8, 10, 12, 17;
xvii. 1; xxi. 9), and is uniformly rendered vial and vials, though the
idea is always that of a bowl or goblet. ¶ Full of odours. Or rather, as
in the margin, full of incense—θυμιαμάτων. See Notes on Lu. i. 9.
¶ Which are the prayers of saints. Which represent or denote the
prayers of saints. Comp. Ps. cxli. 2, “Let my prayer be set forth
before thee as incense.” The meaning is, that incense was a proper
emblem of prayer. This seems to have been in two respects: (a) as
being acceptable to God—as incense produced an agreeable
fragrance; and (b) in its being wafted towards heaven—ascending
towards the eternal throne. In ch. viii. 3, an angel is represented as
having a golden censer: “And there was given unto him much
incense, that he should offer it with the prayers of all saints upon
the golden altar which was before the throne.” The representation
there undoubtedly is, that the angel is employed in presenting the
prayers of the saints which were offered on earth before the throne.
See Notes on that passage. It is most natural to interpret the
passage before us in the same way. The allusion is clearly to the
temple service, and to the fact that incense was offered by the priest
in the temple itself at the time that prayer was offered by the people
in the courts of the temple. See Lu. i. 9, 10. The idea here is,
therefore, that the representatives of the church in heaven—the
elders—spoken of as “priests” (ver. 10), are described as officiating
in the temple above in behalf of the church still below, and as
offering incense while the church is engaged in prayer. It is not said
that they offer the prayers themselves, but that they offer incense as
representing the prayers of the saints. If this be the correct
interpretation, as it seems to be the obvious one, then the passage
lays no foundation for the opinion expressed by Professor Stuart, as
derived from this passage (in loco), that prayer is offered by the
redeemed in heaven. Whatever may be the truth on that point—on
which the Bible seems to be silent—it will find no support from the
passage before us. Adoration, praise, thanksgiving, are represented
as the employment of the saints in heaven: the only representation
respecting prayer as pertaining to that world is, that there are
emblems there which symbolize its ascent before the throne, and
which show that it is acceptable to God. It is an interesting and
beautiful representation that there are in heaven appropriate
symbols of ascending prayer, and that while in the outer courts here
below we offer prayer, incense, emblematic of it, ascends in the holy
of holies above. The impression which this should leave on our
minds ought to be, that our prayers are wafted before the throne,
and are acceptable to God.
9 And they sung a 204new song, saying, Thou
art worthy to take the book, and to open the
seals thereof: for thou wast slain, and hast
redeemed us to God 205by thy blood, out of
206
every kindred, and tongue, and people, and
nation;
9. And they sung a new song. Comp. ch. xiv. 3. New in the sense
that it is a song consequent on redemption, and distinguished
therefore from the songs sung in heaven before the work of
redemption was consummated. We may suppose that songs of
adoration have always been sung in heaven; we know that the
praises of God were celebrated by the angelic choirs when the
foundations of the earth were laid (Job xxxviii. 7); but the song of
redemption was a different song, and is one that would never have
been sung there if man had not fallen, and if the Redeemer had not
died. This song strikes notes which the other songs do not strike,
and refers to glories of the divine character which, but for the work
of redemption, would not have been brought into view. In this sense
the song was new; it will continue to be new in the sense that it will
be sung afresh as redeemed millions continue to ascend to heaven.
Comp. Ps. xl. 3; xcvi. 1; cxliv. 9; Is. xlii. 10. ¶ Thou art worthy to
take the book, &c. This was the occasion or ground of the “new
song,” that by his coming and death he had acquired a right to
approach where no other one could approach, and to do what no
other one could do. ¶ For thou wast slain. The language here is such
as would be appropriate to a lamb slain as a sacrifice. The idea is,
that the fact that he was thus slain constituted the ground of his
worthiness to open the book. It could not be meant that there was
in him no other ground of worthiness, but that this was that which
was most conspicuous. It is just the outburst of the grateful feeling
resulting from redemption, that he who has died to save the soul is
worthy of all honour, and is fitted to accomplish what no other being
in the universe can do. However this may appear to the inhabitants
of other worlds, or however it may appear to the dwellers on the
earth who have no interest in the work of redemption, yet all who
are redeemed will agree in the sentiment that He who has ransomed
them with his blood has performed a work to do which every other
being was incompetent, and that now all honour in heaven and on
earth may appropriately be conferred on him. ¶ And hast redeemed
us. The word here used—ἀγοράζω—means properly to purchase, to
buy; and is thus employed to denote redemption, because
redemption was accomplished by the payment of a price. On the
meaning of the word, see Notes on 2 Pe. ii. 1. ¶ To God. That is, so
that we become his, and are to be henceforward regarded as such;
or so that he might possess us as his own. See Notes on 2 Co. v. 15.
This is the true nature of redemption, that by the price paid we are
rescued from the servitude of Satan, and are henceforth to regard
ourselves as belonging unto God. ¶ By thy blood. See Notes on Ac.
xx. 28. This is such language as they use who believe in the doctrine
of the atonement, and is such as would be used by them alone. It
would not be employed by those who believe that Christ was a mere
martyr, or that he lived and died merely as a teacher of morality. If
he was truly an atoning sacrifice, the language is full of meaning; if
not, it has no significance, and could not be understood. ¶ Out of
every kindred. Literally, “of every tribe”—φυλῆς. The word tribe
means properly a comparatively small division or class of people
associated together (Professor Stuart). It refers to a family, or race,
having a common ancestor, and usually associated or banded
together—as one of the tribes of Israel; a tribe of Indians; a tribe of
plants; a tribe of animals, &c. This is such language as a Jew would
use, denoting one of the smaller divisions that made up a nation of
people; and the meaning would seem to be, that it will be found
ultimately to be true that the redeemed will have been taken from all
such minor divisions of the human family—not only from the
different nations, but from the smaller divisions of those nations.
This can only be true from the fact that the knowledge of the true
religion will yet be diffused among all those smaller portions of the
human race; that is, that its diffusion will be universal. ¶ And
tongue. People speaking all languages. The word here used would
seem to denote a division of the human family larger than a tribe,
but smaller than a nation. It was formerly a fact that a nation might
be made up of those who spoke many different languages—as, for
example, the Assyrian, the Babylonian, or the Roman nations. Comp.
Da. iii. 29; iv. 1. The meaning here is, that no matter what language
the component parts of the nations speak, the gospel will be
conveyed to them, and in their own tongue they will learn the
wonderful works of God. Comp. Ac. ii. 8‒11. ¶ And people. The word
here used—λαός—properly denotes a people considered as a mass,
made up of smaller divisions—as an association of smaller bodies—
or as a multitude of such bodies united together. It is distinguished
from another word commonly applied to a people—δῆμος—for that
is applied to a community of free citizens, considered as on a level,
or without reference to any minor divisions or distinctions. The
words here used would apply to an army, considered as made up of
regiments, battalions, or tribes; to a mass-meeting, made up of
societies of different trades or professions; to a nation, made up of
different associated communities, &c. It denotes a larger body of
people than the previous words; and the idea is, that no matter of
what people or nation, considered as made up of such separate
portions, one may be, he will not be excluded from the blessings of
redemption. The sense would be well expressed, by saying, for
instance, that there will be found there those of the Gaelic race, the
Celtic, the Anglo-Saxon, the Mongolian, the African, &c. ¶ And
nation. ἔθνους. A word of still larger signification; the people in a still
wider sense; a people or nation considered as distinct from all
others. The word would embrace all who come under one
sovereignty or rule; as, for example, the British nation, however
many minor tribes there may be; however many different languages
may be spoken; and however many separate people there may be—
as the Anglo-Saxon, the Scottish, the Irish, the people of
Hindoostan, of Labrador, of New South Wales, &c. The words here
used by John would together denote nations of every kind, great
and small; and the sense is, that the blessings of redemption will be
extended to all parts of the earth.

10 And hast made us unto our God 207kings


and priests: and we shall 208reign on the earth.
10. And hast made us unto our God kings and priests. See Notes
on ch. i. 6. ¶ And we shall reign on the earth. The redeemed, of
whom we are the representatives. The idea clearly is, in accordance
with what is so frequently said in the Scriptures, that the dominion
on the earth will be given to the saints; that is, that there will be
such a prevalence of true religion, and the redeemed will be so
much in the ascendency, that the affairs of the nations will be in
their hands. Righteous men will hold the offices; will fill places of
trust and responsibility; will have a controlling voice in all that
pertains to human affairs. See Notes on Da. vii. 27, and Re. xx. 1‒6.
To such a prevalence of religion all things are tending; and to this, in
all the disorder and sin which now exist, are we permitted to look
forward. It is not said that this will be a reign under the Saviour in a
literal kingdom on the earth; nor is it said that the saints will
descend from heaven, and occupy thrones of power under Christ as
a visible king. The simple affirmation is, that they will reign on the
earth; and as this seems to be spoken in the name of the redeemed,
all that is necessary to be understood is, that there will be such a
prevalence of true religion on the earth that it will become a vast
kingdom of holiness, and that, instead of being in the minority, the
saints will everywhere have the ascendency.

11 And I beheld, and I heard the voice of


many angels round about the throne and the
beasts and the elders: and the 209number of
them was ten thousand times ten thousand,
and thousands of thousands;
11. And I beheld. And I looked again. ¶ And I heard the voice of
many angels. The inhabitants of heaven uniting with the
representatives of the redeemed church in ascribing honour to the
Lamb of God. The design is to show that there is universal sympathy
and harmony in heaven, and that all worlds will unite in ascribing
honour to the Lamb of God. ¶ Round about the throne and the
beasts and the elders. In a circle or area beyond that which was
occupied by the throne, the living creatures, and the elders. They
occupied the centre, as it appeared to John, and this innumerable
company of angels surrounded them. The angels are represented
here, as they are everywhere in the Scriptures, as taking a deep
interest in all that pertains to the redemption of men, and it is not
surprising that they are here described as uniting with the
representatives of the church in rendering honour to the Lamb of
God. Comp. Notes on 1 Pe. i. 12. ¶ And the number of them was ten
thousand times ten thousand. One hundred millions—a general term
to denote either a countless number, or an exceedingly great
number. We are not to suppose that it is to be taken literally. ¶ And
thousands of thousands. Implying that the number before specified
was not large enough to comprehend all. Besides the “ten thousand
times ten thousand,” there was a vast uncounted host which one
could not attempt to enumerate. The language here would seem to
be taken from Da. vii. 10: “Thousand thousands ministered unto
him, and ten thousand times ten thousand stood before him.” Comp.
Ps. lxviii. 17: “The chariots of God are twenty thousand, even
thousands of angels.” See also De. xxxiii. 2; 1 Ki. xxii. 19.

12 Saying with a loud voice, 210Worthy is the


Lamb that was slain to receive power, and
riches, and wisdom, and strength, and honour,
and glory, and blessing.
12. Saying with a loud voice, Worthy is the Lamb that was slain.
See Notes on ver. 2, 9. The idea here is, that the fact that he was
slain, or was made a sacrifice for sin, was the ground or reason for
what is here ascribed to him. Comp. Notes on ver. 5. ¶ To receive
power. Power or authority to rule over all things. Comp. Notes on
Mat. xxviii. 18. The meaning here is, that he was worthy that these
things should be ascribed to him, or to be addressed and
acknowledged as possessing them. A part of these things were his in
virtue of his very nature—as wisdom, glory, riches; a part were
conferred on him as the result of his work—as the mediatorial
dominion over the universe, the honour resulting from his work, &c.
In view of all that he was, and of all that he has done, he is here
spoken of as “worthy” of all these things. ¶ And riches. Abundance.
That is, he is worthy that whatever contributes to honour, and glory,
and happiness, should be conferred on him in abundance. Himself
the original proprietor of all things, it is fit that he should be
recognized as such; and having performed the work which he has, it
is proper that whatever may be made to contribute to his honour
should be regarded as his. ¶ And wisdom. That he should be
esteemed as eminently wise; that is, that as the result of the work
which he has accomplished, he should be regarded as having ability
to choose the best ends and the best means to accomplish them.
The feeling here referred to is that which arises from the
contemplation of the work of salvation by the Redeemer, as a work
eminently characterized by wisdom—wisdom manifested in meeting
the evils of the fall; in honouring the law; in showing that mercy is
consistent with justice; and in adapting the whole plan to the
character and wants of man. If wisdom was anywhere demanded, it
was in reconciling a lost world to God; if it has been anywhere
displayed, it has been in the arrangements for that work, and in its
execution by the Redeemer. See Notes on 1 Co. i. 24; comp. Mat.
xiii. 54; Lu. ii. 40, 52; 1 Co. i. 20, 21, 30; Ep. i. 8; iii. 10. ¶ And
strength. Ability to accomplish his purposes. That is, it is meet that
he should be regarded as having such ability. This strength or power
was manifested in overcoming the great enemy of man; in his
control of winds, and storms, and diseases, and devils; in triumphing
over death; in saving his people. ¶ And honour. He should be
esteemed and treated with honour for what he has done. ¶ And
glory. This word refers to a higher ascription of praise than the word
honour. Perhaps that might refer to the honour which we feel in our
hearts; this to the expression of that by the language of praise.
¶ And blessing. Everything which would express the desire that he
might be happy, honoured, and adored. To bless one is to desire that
he may have happiness and prosperity; that he may be successful,
respected, and honoured. To bless God, or to ascribe blessing to
him, is that state where the heart is full of love and gratitude, and
where it desires that he may be everywhere honoured, loved, and
obeyed as he should be. The words here express the wish that the
universe would ascribe to the Redeemer all honour, and that he
might be everywhere loved and adored.

13 And 211every creature which is in heaven,


and on the earth, and under the earth, and
such as are in the sea, and all that are in them,
heard I saying, 212Blessing, and honour, and
glory, and power, be unto him that sitteth upon
the throne, and unto the Lamb for ever and
ever.
13. And every creature which is in heaven. The meaning of this
verse is, that all created things seemed to unite in rendering honour
to Him who sat on the throne, and to the Lamb. In the previous
verse a certain number—a vast host—of angels are designated as
rendering praise as they stood round the area occupied by the
throne, the elders, and the living creatures; here it is added that all
who were in heaven united in this ascription of praise. ¶ And on the
earth. All the universe was heard by John ascribing praise to God.
A voice was heard from the heavens, from all parts of the earth,
from under the earth, and from the depths of the sea, as if the
entire universe joined in the adoration. It is not necessary to press
the language literally, and still less is it necessary to understand by
it, as Professor Stuart does, that the angels who presided over the
earth, over the under-world, and over the sea, are intended. It is
evidently popular language; and the sense is, that John heard a
universal ascription of praise. All worlds seemed to join in it; all the
dwellers on the earth, and under the earth, and in the sea, partook
of the spirit of heaven in rendering honour to the Redeemer. ¶ Under
the earth. Supposed to be inhabited by the shades of the dead. See
Notes on Job x. 21, 22; Is. xiv. 9. ¶ And such as are in the sea. All
that dwell in the ocean. In Ps. cxlviii. 7‒10, “dragons, and all deeps;
beasts, and all cattle; creeping things, and flying fowl,” are called on
to praise the Lord; and there is no more incongruity or impropriety in
one description than in the other. In the Psalm, the universe is called
on to render praise; in the passage before us it is described as
actually doing it. The hills, the streams, the floods; the fowls of the
air, the dwellers in the deep, and the beasts that roam over the
earth; the songsters in the grove, and the insects that play in the
sunbeam, in fact, declare the glory of their Creator; and it requires
no very strong effort of the fancy to imagine the universe as sending
up a constant voice of thanksgiving. ¶ Blessing, and honour, &c.
There is a slight change here from ver. 12, but it is the same thing
substantially. It is an ascription of all glory to God and to the Lamb.

14 And the 213four beasts said, Amen. And


the four and twenty elders fell down and
worshipped him that liveth for ever and ever.

You might also like