Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
23 views

(PDF Download) FastAPI: Modern Python Web Development (First Early Release) Bill Lubanovic Fulll Chapter

ebook

Uploaded by

jpablovalado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
23 views

(PDF Download) FastAPI: Modern Python Web Development (First Early Release) Bill Lubanovic Fulll Chapter

ebook

Uploaded by

jpablovalado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Full download test bank at ebookmeta.

com

FastAPI: Modern Python Web Development (First


Early Release) Bill Lubanovic

For dowload this book click LINK or Button below

https://ebookmeta.com/product/fastapi-modern-
python-web-development-first-early-release-bill-
lubanovic/

OR CLICK BUTTON

DOWLOAD EBOOK

Download More ebooks from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

FastAPI: Modern Python Web Development 1st Edition Bill


Lubanovic

https://ebookmeta.com/product/fastapi-modern-python-web-
development-1st-edition-bill-lubanovic/

High-Performance Web Apps with FastAPI: The


Asynchronous Web Framework Based on Modern Python 1st
Edition Malhar Lathkar

https://ebookmeta.com/product/high-performance-web-apps-with-
fastapi-the-asynchronous-web-framework-based-on-modern-
python-1st-edition-malhar-lathkar/

High-Performance Web Apps with FastAPI: The


Asynchronous Web Framework Based on Modern Python 1st
Edition Malhar Lathkar

https://ebookmeta.com/product/high-performance-web-apps-with-
fastapi-the-asynchronous-web-framework-based-on-modern-
python-1st-edition-malhar-lathkar-2/

Modern Mainframe Development (Third Early Release) Tom


Taulli

https://ebookmeta.com/product/modern-mainframe-development-third-
early-release-tom-taulli/
Modern Mainframe Development: COBOL, Databases and
Next-Generation Approaches (Second Early Release) 1 /
2021-11-23: Second Early Release Edition Tom Taulli

https://ebookmeta.com/product/modern-mainframe-development-cobol-
databases-and-next-generation-approaches-second-early-
release-1-2021-11-23-second-early-release-edition-tom-taulli/

Linux System Administration 1st Edition Tom Adelstein


Bill Lubanovic

https://ebookmeta.com/product/linux-system-administration-1st-
edition-tom-adelstein-bill-lubanovic/

Web Application Security 2nd Edition (Early Release)


Andrew Hoffman

https://ebookmeta.com/product/web-application-security-2nd-
edition-early-release-andrew-hoffman/

Web Application Security, 2nd Edition ( First Early


Release) Andrew Hoffman

https://ebookmeta.com/product/web-application-security-2nd-
edition-first-early-release-andrew-hoffman/

Head First Python Third Edition (Early Release) Paul


Barry

https://ebookmeta.com/product/head-first-python-third-edition-
early-release-paul-barry/
FastAPI
FIRST EDITION

Modern Python Web Development

Bill Lubanovic
FastAPI
by Bill Lubanovic
Copyright © 2023 Bill Lubanovic. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc. , 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles (
http://oreilly.com ). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com .

Editors: Corbin Collins and Amanda Quinn

Production Editor: FILL IN PRODUCTION EDITOR

Copyeditor: FILL IN COPYEDITOR

Proofreader: FILL IN PROOFREADER

Indexer: FILL IN INDEXER

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Kate Dullea

November 2023: First Edition


Revision History for the First Edition
2022-09-14: First Early Release
See http://oreilly.com/catalog/errata.csp?isbn=9781098135508 for
release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc.
FastAPI, the cover image, and related trade dress are trademarks of
O’Reilly Media, Inc.
The views expressed in this work are those of the author(s) and do
not represent the publisher’s views. While the publisher and the
author(s) have used good faith efforts to ensure that the information
and instructions contained in this work are accurate, the publisher
and the author(s) disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof
complies with such licenses and/or rights.
978-1-098-13550-8
[FILL IN]
Dedication
To the loving memory of my parents Bill and Tillie, and my wife
Mary. I miss you.
Preface

This is a pragmatic introduction to FastAPI — a modern Python web


framework.
It’s also a story of how, now and then, the bright and shiny objects
that we stumble across can turn out to be very useful. A silver bullet
is nice to have when you encounter a werewolf. (And you will
encounter werewolves later in this book.)
I started programming scientific applications in the mid 1970s. But
not long after I first met UNIX and C on a PDP-11 in 1977, I had a
feeling that this UNIX thing might catch on.
In the 80s and early 90s, the Internet was still non-commercial, but
already a good source for free software and technical info. But when
a “web browser” called Mosaic was distributed on the baby open
Internet in 1993, I had a feeling that this Web thing might catch on.
When I started my own web development company a few years
later, my tools were the usual suspects at the time — PHP, HTML,
and Perl. On a contract job a few years later, I finally experimented
with Python, and was surprised how quickly I was able to access,
manipulate, and display data. In some spare time over two weeks, I
was able to replicate most of a C application that had taken four
developers a year to write. Now I had a feeling that this Python
thing might catch on.
After that, most of my work involved Python and its web
frameworks, mostly Flask and Django. I particularly liked the
simplicity of Flask, and preferred it for many jobs. But just a few
years ago, I spied something glinting in the underbrush — a new
Python web framework called FastAPI, written by Sebastián Ramirez.
As I read his (excellent) documentation, I was impressed by the
design and thought that had gone into it. In particular, his history
page showed how much care he had spent evaluating alternatives.
This was not an ego project or a fun experiment, but a serious
framework for real-world development. Now I had a feeling that this
FastAPI thing might catch on.
I wrote a biomedical API site with FastAPI, and it went so well that a
team of us rewrote our old core API with FastAPI in the next year.
This is still in production, and has held up well. Our group learned
the basics that you’ll read in this book, and all felt that we were
writing better code, faster, with fewer bugs. And by the way, some of
us had not written in Python before, and only I had used FastAPI.
So when I had an opportunity to suggest a followup to my
Introducing Python book to O’Reilly, FastAPI was at the top of my
list. In my opinion, FastAPI will have at least the impact that Flask
and Django have had, and maybe more.
As I mentioned above, the FastAPI website itself provides world-
class documentation, including many details on the usual web topics
— databases, authentication, deployment, and so on. So why write a
book?
This book isn’t meant to be exhaustive because, well, that’s
exhausting. It is meant to be useful — to help you quickly pick up the
main ideas of FastAPI and apply them. I will point out various
techniques that required some sleuthing, and offer advice on day-to-
day best practices.
I start each chapter with a Preview of what’s coming. Next, I try
not to forget what I just promised, with details and random asides.
Finally, there’s a brief digestible Review.
As the saying goes, “These are the opinions on which my facts are
based.” Your experience will be unique, but I hope that you will find
enough of value here to become a more productive web developer.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file
extensions.

Constant width
Used for program listings, as well as within paragraphs to refer to
program elements such as variable or function names, databases,
data types, environment variables, statements, and keywords.

Constant width bold


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

Constant width italic


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

TIP
This element signifies a tip or suggestion.

NOTE
This element signifies a general note.
WARNING
This element indicates a warning or caution.

Using Code Examples


Supplemental material (code examples, exercises, etc.) is available
for download at https://github.com/oreillymedia/title_title.
If you have a technical question or a problem using the code
examples, please send email to bookquestions@oreilly.com.
This book is here to help you get your job done. In general, if
example code is offered with this book, you may use it in your
programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the
code. For example, writing a program that uses several chunks of
code from this book does not require permission. Selling or
distributing examples from O’Reilly books does require permission.
Answering a question by citing this book and quoting example code
does not require permission. Incorporating a significant amount of
example code from this book into your product’s documentation
does require permission.
We appreciate, but generally do not require, attribution. An
attribution usually includes the title, author, publisher, and ISBN. For
example: “Book Title by Some Author (O’Reilly). Copyright 2012
Some Copyright Holder, 978-0-596-xxxx-x.”
If you feel your use of code examples falls outside fair use or the
permission given above, feel free to contact us at
permissions@oreilly.com.
O’Reilly Online Learning

NOTE
For more than 40 years, O’Reilly Media has provided technology and
business training, knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their knowledge


and expertise through books, articles, and our online learning
platform. O’Reilly’s online learning platform gives you on-demand
access to live training courses, in-depth learning paths, interactive
coding environments, and a vast collection of text and video from
O’Reilly and 200+ other publishers. For more information, visit
https://oreilly.com.

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

O’Reilly Media, Inc.

1005 Gravenstein Highway North

Sebastopol, CA 95472

800-998-9938 (in the United States or Canada)

707-829-0515 (international or local)

707-829-0104 (fax)

We have a web page for this book, where we list errata, examples,
and any additional information.
Email bookquestions@oreilly.com to comment or ask technical
questions about this book.
For news and information about our books and courses, visit
https://oreilly.com.
Find us on LinkedIn: https://linkedin.com/company/oreilly-media
Follow us on Twitter: https://twitter.com/oreillymedia
Watch us on YouTube: https://www.youtube.com/oreillymedia

Acknowledgments
Part I. What’s New?

The world has benefited greatly from the invention of the World
Wide Web by Sir Tim Berners-Lee1, and the Python programming
language by Guido van Rossum.
The only tiny problem is that a nameless computer book publisher
often puts spiders and snakes on its relevant Web and Python
covers. If only the Web had been named the World Wide Woof
(cross-threads in weaving, also called weft), and Python were Pooch,
this book might have had a cover like this:

Figure I-1. FastAPI: Modern Pooch Woof Development

But I digress2.
This book is about:

The Web: An especially productive technology, how it has


changed, and how to develop software for it now
Python: An especially productive web development language
FastAPI: An especially productive Python web framework
The two chapters in this first part discuss emerging topics in the
Web and Python: services and APIs, concurrency, layered
architectures, and big big data.
Part II is a high-level tour of FastAPI, a fresh Python web framework
that has good answers to the questions posed in Part I.
Part III rummages much deeper through the FastAPI toolbox,
including tips learned during production development.
Finally, Part IV provides a gallery of FastAPI web examples. They use
a common data source — imaginary creatures — that may be a little
more interesting and cohesive than the usual random expositions.
These should give you a starting point for particular applications.

1 I actually shook his hand once. I didn’t wash mine for a month, but I’ll bet
he did right away.
2 Not for the last time.
Chapter 1. The Modern Web

The Web as I envisaged it, we have not seen it yet. The future is
still so much bigger than the past.
—Tim Berners-Lee

Preview
Once upon a time, the web was small and simple. Developers had
such fun throwing PHP, HTML, and MySQL calls into single files and
proudly telling everyone to check out their website. But the web
grew over time to zillions, nay, squillions of pages — and the early
playground became a metaverse of theme parks.
In this chapter, I’ll point out some areas that have become ever
more relevant to the modern web:
Services and APIs
Concurrency
Layers
Data

The next chapter will show what Python offers in these areas. After
that, we’ll dive into the FastAPI web framework and see what it has
to offer.

Services and APIs


The web is a great connecting fabric. Although there are still much
activity on the content side — HTML, JavaScript, images, and so on
— there’s an increasing emphasis on the APIs (Application
Programming Interfaces) that connect things.
Commonly, a web service handles the backend (database access)
and middle (business logic), while JavaScript or mobile apps provide
rich frontends. These fore and aft worlds have become more
complex and divergent, usually requiring developers to specialize in
one or the other. It’s harder to be a full stack developer than it used
to be1.
The frontends and backends talk to each other using APIs. In the
modern web, API design is as important as the design of web sites
themselves. An API is a contract, similar to a database schema.
Defining and modifying APIs is now a major job.

Kinds of APIs
Each API defines some:

Protocol: Control structure


Format: Content structure
Different API methods have developed as technology has evolved
from isolated machines, to multitasking systems, to networked
servers.
Before networking, an API usually meant a very close connection,
like a function call to a library in the same language as your
application — say, calculating a square root in a math library.
RPCs (Remote Procedure Calls) were invented to call functions in
other processes, on the same machine or others, as though they
were in the calling application. A popular current example is gRPC.
Messaging sends small chunks of data in pipelines among processes.
Communication can follow different patterns:
Request-response: One:one, like a web browser calling a web
server.
Publish-subscribe, or pub-sub: A publisher emits messages, and
subscribers act on each according to some data in the message,
like a subject.
Queues: Like pub-sub, but only one of a pool of subscribers
grabs the message and acts on it.

Messages may be verb-like commands, or may just indicate noun-


like events of interest. Current popular messaging solutions, which
vary broadly from toolkits to full servers, include Kafka, RabbitMQ,
NATS, and ZeroMQ.
But the most common way to perform APIs on the Internet, and the
focus of this book, is through the web’s basic protocol: HTTP.

HTTP
Berners-Lee proposed three components for his World Wide Web:

HTML: A language for displaying data


HTTP: A client-server protocol
URLs: An addressing scheme for web resources

Although these seem obvious in retrospect, they turned out to be a


ridiculously useful combination. As the web evolved, people
experimented, and some ideas, like the IMG tag, survived the
Darwinian struggle. And as needs became more clear, people got
serious about defining standards.

REST(ful)
One chapter in the Ph.D. thesis by Roy Fielding defined REST
(Representational State Transfer) — an architectural style2 for
HTTP use. Although often referenced, it’s been largely
misunderstood.
A roughly shared adaptation has evolved, and dominates the modern
web. It’s called RESTful, with these characteristics:
Uses HTTP and client-server
Stateless: Each connection is independent
Cacheable
Resource-based
A resource is data that you can distinguish and perform operations
on. A web service provides an endpoint — a distinct URL and HTTP
verb (action) — for each feature that it wants to expose. An endpoint
is also called a route, because it routes the URL to a function.
Database users are familiar with the CRUD acronym of procedures
— create, read, update, delete. The HTTP verbs are pretty CRUDdy:
POST: Create (write)

PUT: Modify completely (replace)


PATCH: Modify partially (update)

GET: Um, get (read, retrieve)


DELETE: Uh, delete

A client sends a request to a RESTful endpoint with data in some


area of an HTTP message:
Headers
The URL string
Query parameters
Body values
(NOTE: figure here)
In turn, an HTTP response returns:

An integer status code indicating:


100s: Info, keep going
200s: Success
300s: Redirection
400s: Client error
500s: Server error
Various headers
A body, which may be empty, single, or chunked (in successive
pieces)

At least one status code is an Easter egg: 418 (I’m a teapot) is


supposed to be returned by a web-connected teapot, if asked to
brew coffee.
You’ll find many web sites and books on RESTful API design, all with
useful rules of thumb. This book will dole some out on the way.

JSON and API Data Formats


Frontend applications can exchange plain ASCII text with backend
web services, but how can you express data structures like lists of
things?
Just about when we really started to need it, along came JSON
(JavaScript Object Notation) — another simple idea that solves an
important problem, and seems obvious with hindsight. Although the
J stands for JavaScript, the syntax looks a lot like Python, too.
JSON has largely replaced older attempts like XML and SOAP. In the
rest of this book, you’ll see that JSON is the default web service
input and output format.

JSON:API
The combination of RESTful design and JSON data formats is very
common now. But there’s still some wiggle room for ambiguity and
nerd tussles. The recent JSON:API proposal aims to tighten specs a
bit. This book will use the loose RESTful approach, but JSON:API or
something similarly rigorous may be useful if you have significant
tussles.
(NOTE: discussion of JSON:API vs RESTful)

GraphQL
RESTful interfaces can be cumbersome for some purposes. Facebook
designed GraphQL (Graph Query Language) to specify more flexible
service queries.
(NOTE: brief comparison of how GraphQL requests and responds)

Concurrency
Besides the growth of service orientation, the rapid expansion of the
number of connections to web services requires ever better
efficiency and scale.
We want to reduce:
Latency: The upfront wait time.
Throughput: The number of bytes per second between the
service and its callers.
In the old web days3, people dreamed of supporting hundreds of
simultaneous connections, then fretted about the “10K problem”,
and now assume millions at a time.
The term concurrency doesn’t mean full parallelism. Multiple
processing isn’t occurring in the same nanosecond, in a single CPU.
Instead, concurrency mostly avoids busy waiting. CPUs are very
zippy, but networks and disks are thousand to millions of times
slower. So, whenever we talk to a network or disk, we don’t want to
just sit there with a blank stare.
Instead, asynchronous systems provide an event loop: requests are
sent and noted, but we don’t wait for slow responses. Instead, some
immediate processing is done on each pass through the loop, and
any responses that came in during that time are handled in the next
pass.
It isn’t magic. You still have to be careful to avoid doing too much
CPU-intensive work during the event loop, because that will slow
down everything.
Later in this book, you’ll see the uses of Python’s async and await
keywords, and how FastAPI lets you mix both synchronous and
asynchronous processing.

Layers
Shrek fans may remember he noted his layers of personality, to
which Donkey replied, “Like an onion?”
Well, if ogres and tearful vegetables can have layers, then so can
software. To manage size and complexity, many applications have
long used a so-called three-tier model4. This actually isn’t terribly
new. Terms differ5, but for this book I’m using the following simple
separation and terms:

Router: Get client requests, call service, return responses


Service: The business logic, which calls the data layer when
needed
Data: Access to data stores and other services
(NOTE: image here)
These will help you to scale your site without having to start from
scratch. They’re not laws of quantum mechanics, so consider them
guidelines for this book’s exposition.
The layers talk to one another via APIs. These can be simple
function calls to separate Python modules, but could access external
code via any method. As I showed earlier, this could include RPCs,
messages, and so on. In this book, I’m assuming a single web
server, with Python code importing other Python modules. The
separation and information hiding is handled by the modules.
The Router layer is the one that users see, via client applications and
APIs. We’re usually talking about a RESTful web interface, with
URLs, and JSON-encoded requests and responses. But there may
also be text (or CLI, command line interface) clients. Python Router
code may import Service-layer modules, but should not import Data
modules.
The Service layer contains the actual details of whatever this web
site provides. This essentially looks like a library. It imports Data
modules to access databases and external services, but should not
know the details.
The Data layer provides the service layer access to data, through
files or client calls to other services. There may also be alternative
Data layers, communicating with a single Service layer.
Why do this? Among many reasons, each layer can be:

Written by specialists.
Tested in isolation.
Replaced or supplemented: You might add a second Routing
layer, using a different API such as gRPC, alongside a web one.

Follow one rule from Ghostbusters: don’t cross the streams. That is,
don’t let web details leak out of the Routing layer, or database
details out of the Data layer.
You can visualize “layers” as a vertical stack, like a cake in the British
Baking Show6.

Reasons for separation:

If you don’t, expect a hallowed web meme: Now you have two
problems.
Once they’re mixed, later separation will be very difficult.
You’ll need to know two or more specialties to understand and
write tests if code logic gets muddled.

By the way, even though I call them layers, you don’t need to
assume that one layer is “above” or “below” another, and that
commands flow with gravity. Vertical chauvinism! You could also
view layers as sideways-communicating boxes:
(NOTE: boxes image here)
However you visualize them, the only communication paths between
the boxes/layers are the arrows (APIs). This is important for testing
and debugging. If there are undocumented doors into a factory, the
night watchman will inevitably be surprised.
(NOTE: annotated arrows image here)
Also, the recommended data formats flowing through the arrows
are:

Client ⇔ Router: RESTful HTTP with JSON


Router ⇔ Service: Models
Service ⇔ Data: Models
Data ⇔ Databases and services: Specific APIs
Based on my own experience, this is how I’ve chosen to structure
the topics in this book. It’s workable, and has scaled to fairly
complex sites, but isn’t sacred. You may have a better design!
However you do it, the important points are:
Separate domain-specific details.
Define standard APIs between the layers.
Don’t cheat, don’t leak.
Sometime’s it’s a challenge deciding which layer is the best home for
some code. For example, chapter 10 looks at “auth” requirements,
and how to implement them — as an extra layer between Router and
Service, or within one of them. Software development is sometimes
as much art as science.
Data
The web has often been used as a frontend to relational databases,
although many other ways of storing and accessing data have
evolved, such as NoSQL or NewSQL databases.
But beyond databases, ML (machine learning, or deep learning, or
just AI) is fundamentally remaking the technology landscape. The
development of large models requires lots of messing with data —
traditionally called ETL (extraction / transformation / loading).
As a general purpose service architecture, the web can help with
many of the fiddly bits of ML systems.

Review
The web uses many APIs, but especially RESTful ones.
Asynchronous calls allow better concurrency, which makes things
faster. Web service applications are often large enough to divide into
layers. Data has become a major area in its own right. All of these
concepts are addressed in the Python programming language,
coming in the next chapter.

1 I gave up trying a few years ago.


2 “Style” means a higher level pattern, like “client-server”, rather than a
specific design.
3 Around when caveman played hacky sack with giant ground sloths.
4 Choose your own dialect: tier/layer, tomato/tomahto/arrigato.
5 You’ll often see the term MVC (Model View Controller) and variations. Often
accompanied by religious wars, toward which I’m agnostic.
6 As viewers know, if your layers get sloppy, you may not return to the tent
the next week.
Chapter 2. Modern Python

It’s all in a day’s work for “Confuse-a-Cat”.


—Monty Python

Preview
Python evolves to keep up with our changing technical world. This
chapter discusses specific Python features that apply to issues in the
previous chapter, and a few extras:
Tools
APIs and services
Type hinting and variables
Concurrency
Data Structures
Web frameworks

Tools
Every computing language has:
The core language, and built-in “standard” packages
Ways to add external packages
Recommended external packages
An environment of development tools
The following sections list what’s required or recommended for this
book.
These may change over time! Python packaging and development
tools are moving targets, and better solutions come along now and
then.

Getting Started
You should able to write and run a Python program like this:
Example 2-1. this.py
def paid_promotion():
print("(that calls this function!)")

print("This is the program")


paid_promotion()
print("that goes like this.")

To execute this program from the command line in a text window or


terminal, I’ll use the convention of a $ prompt (your system begging
you to type something, already). What you type after the prompt is
shown in bold print. If you saved the little program above to a file
named this.py, then you can run it like this:

$ python this.py
This is the program
(that calls this function!)
that goes like this.

Some code examples use the interactive Python interpreter, which is


what you get if you just type python:

$ python
Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec 7 2020, 12:10:52)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>>

The first few lines are specific to your operating system and Python
version. The >>> is your prompt here. A handy extra feature of the
interactive interpreter is that it will print the value of a variable for
you if you type its name:

>>> wrong_answer = 43
>>> wrong_answer
43

This also works for expressions:

>>> wrong_answer = 43
>>> wrong_answer - 3
40

If you’re fairly new to Python, or would like a quick review, read the
next few sections.

Python Itself
You will need at least Python 3.7. This includes newer features like
type hints and asyncio, which are core requirements for FastAPI. The
standard source for Python is python.org.

Package Management
You will want to download external Python packages, and install
them safely on your computer. The classic tool for this is pip.
But how do you download this downloader? If you installed Python
from python.org, you should already have pip. If not, follow the
instructions at the pip site to get it. Throughout this book, as I
introduce a new Python package, I’ll include the pip command to
download it.
Although you can do a lot with plain old pip, it’s likely that you’ll also
want to use virtual environments, and consider an alternative tool
like poetry.

Virtual Environments
Pip will download and install packages, but where should it put
them? Although standard Python and its included libraries are
usually installed in some “standard” place on your operating system,
you may not (and probably should not) be able to change anything
there. Pip uses a default directory other than the system one, so you
won’t step on your system’s standard Python files. You can change
this; see the pip site for details for your operating system.
But it’s common to work with multiple versions of Python, or make
installations specific to a project, so you know exactly which
packages are in there. To do this, Python supports virtual
environments. These are just directories (“folders” in the non-Unix
world) into which pip writes downloaded packages. When you
activate a virtual environment, your shell (main system command
interpreter) looks there first when loading Python modules.
The program for this is venv, and it’s been included with standard
Python since version 3.4.
Let’s make a virtual environment called venv1. You can run the venv
module as a standalone program:

$ venv venv1

or as a Python module:

$ python -m venv venv1

To make this your current Python envirnment, run this shell


command (on Linux or Mac; see the venv docs for Windows and
others):

$ source venv1/bin/activate

Now, anytime you run pip install, it will install packages under
venv1. And when you run Python programs, that’s where your
Python interpreter and modules will be found.
To de-activate your virtual environment, type a control-d (Linux or
Mac), or deactivate (Windows).
You can create alternative environments like venv2, and
deactivate/activate to step between them. (although I hope you
have more naming imagination than me).

Poetry
This combination of pip and venv is so common that people started
combining them to save steps, and avoid that source shell
wizardry. One such package is pipenv, but a newer rival called poetry
is becoming more popular.
Having used pip, pipenv, and poetry, I now prefer poetry. Get it with
pip install poetry. Poetry has many subcommands, such as
poetry add to add a package to your virtual environment, poetry
install to actually download and install it, and so on. Check the
poetry site or run the poetry command for help.
Besides downloading single packages, pip and poetry manage
multiple packages in configuration files: requirements.txt for
pip, and pyproject.toml for poetry. They don’t just download
packages, but also manage the tricky dependencies that packages
may have on other packages. You can specify desired package
versions as minima, maxima, ranges, or exact values (also known as
pinning). This can be important as your project grows and the
packages that it depends on change. You may need a minimum
version of a package if a feature that you use first appeared there,
or a maximum if some feature was dropped.

Source Formatting
This is less important, but helpful. Avoid code formatting
(“bikeshedding”) arguments with a tool that massages source into a
standard, non-weird format. One good choice is black. Install it with
pip install black.

Testing
Testing will be covered in detail in Chapter 13. Although there are
simpler tools like nose, the industrial-strength Python test package is
pytest. Install it with pip install pytest.

Source Control and Continuous Integration


(CI)
The almost-universal solution for source control now is git. with
storage repositories (“repos”) at sites like github and gitlab. Ths isn’t
specific to Python or FastAPI, but you’ll very likely spend a lot of
your development time with git. The pre-commit tool runs various
tests on your local machine such as black and pytest) before
committing to git. After pushing to a remote git repo, more CI tests
may be run there.
Chapters 13 (Testing) and 16 (Troubleshooting) will have more
details.

Web Tools
Chapter 3 will show how to install and use the main Python web
tools used in this book:
FastAPI: The web framework itself
Uvicorn: An asynchronous web server
Httpie: A text web client, similar to curl
Requests: A synchronous web client package
Httpx: A synchronous/asynchronous web client package

APIs and Services


Python’s modules and packages are essential for creating large
applications that don’t become “big balls of mud”. Even in a single-
process web service, we can maintain the separation discussed in
Chapter 1 by the careful design of modules and imports.
Python’s built-in data structures are extremely flexible, and very
tempting to use everywhere. But in the coming chapters you’ll see
that we can define higher-level models to make our inter-layer
communication cleaner. These models rely on a fairly recent Python
addition called type hinting. Let’s get into that, but first with a brief
aside into how Python handles variables. This won’t hurt.

Variables Are Names


The term object has many definitions in the software world — maybe
too many. In Python, an object is a data structure that wraps every
distinct piece of data in the program, from an integer like 5, to a
function, to anything that you might define. It specifies, among
other bookkeeping info:

A unique identity value


The low-level type that matches the hardware
The specific value (physical bits)
A reference count of how many variables refer to it

(NOTE: figure here)


Python is strongly typed at the object level (its type above doesn’t
change, although its value might). An object is termed mutable if its
value may be changed, immutable if not.
But at the variable level, Python differs from many other computing
languages, and this can be confusing.
In many other languages, a variable is essentially a direct pointer to
an area of memory that contains a raw value, stored in bits that
follow the computer’s hardware design. If you assign a new value to
that variable, the language overwrites the previous value in memory
with the new one.
(NOTE: figure here)
That’s direct and fast. The compiler keeps track of what goes where.
It’s one reason why languages like C are faster than Python. As a
developer, you need to ensure that you only assign values of the
correct type to each variable.
Now, here’s the big difference with Python: a Python variable is just
a name that is temporarily associated with a higher-level object in
memory.
If you assign a new value to a variable that refers to an immutable
object, you’re actually creating a new object that contains that
value, and then getting the name to refer to that new object. The
old object (that the name used to refer to) is then free, and its
memory can be reclaimed if no other names are still referring to it
(i.e., its reference count is zero).
(NOTE: figure here)
In Introducing Python (O’Reilly, 2020), I compare objects to plastic
boxes sitting on memory shelves, and names/variables to sticky
notes on these boxes. Or you can picture names as tags attached by
strings to those boxes.
(NOTE: figure here)
Usually, when you use a name, you assign it to one object and it
stays attached. Such simple consistency helps you to understand
your code. A variable’s scope is the area of code in which a name
refers to the same object — such as within a function. You can use
the same name in different scopes, but each one refers to a different
object.
(NOTE: figure here)
Although you can make a variable refer to different things
throughout a Python program, that isn’t necessarily a good practice.
Without looking, you don’t know if name x on line 100 is in the same
scope as name x on line 20. (By the way, x is a terrible name. We
should pick names that actually confer some meaning.)

Type Hints
All of this background has a point.
Python 3.6 added type hints to declare the type of object to which a
variable refers. These are not enforced by the Python interpreter as
it’s running! Instead, they can be used by various tools to ensure
that your use of a variable is consistent. The standard type checker
is called mypy, and I’ll show you how it’s used later.
A type hint may just seem like a nice thing, like many “lint” tools
used by programmers to avoid some mistakes. For instance, it may
remind you that your variable count refers to a Python object of
type int. But hints, although they’re optional and unenforced notes
(literally, “hints”), turn out to have unexpected uses. Later in this
book, you’ll see how FastAPI adapted the Pydantic package to make
very clever use of type hinting.
The addition of type declarations may be a trend in other, formerly
typeless, languages. For example, many JavaScript developers have
moved to TypeScript.

Concurrency
For the longest time, Python was strictly synchronous — one thing
ran at a time, for as long as it needed. If you called something slow,
like file or network I/O, then your program blocked (sat there and
waited until the bytes came back). If you wanted to overlap
processing — have some concurrency — Python has had many
alternatives. You’ll see details about these in Chapter 4.

Data Structures
Often, we need to keep a related group of variables together.
Python’s historic data grouping structures (beyond the basic int,
string, and such) are:

Tuple: an immutable sequence of objects


List: A mutable sequence of objects

Set: Mutable distinct objects

Dictionary: Mutable key:value object pairs (the key needs to


be of an immutable type)
Other standard Python data structures can provide something like
what other computer languages call a record (a group of names and
values):

Namedtuple
Dataclass
Actually, you can define a new Python class and add all the
attributes you want to self. But you’ll need to do a lot of typing
just to define them.
And we want more, so while we’re at it, let’s ask Santa for:

A union of possible alternative types


Missing values
Default values
Data validation
Serialization to and from formats like JSON

As you’ll see in chapter 5, the third-party package pydantic. was


chosen by FastAPI to do all of these things.

Web Frameworks
Among other things, a web framework translates between HTTP
bytes and Python data structures. It can save you a lot of effort. On
the other hand, if some part of it doesn’t work as you need it to, you
may need to hack a solution around it.
WSGI (the Web Server Gatewway Interface) is a synchronous
Python standard specification to connect application code to web
servers.
As mentioned in the previous chapter, concurrency has become more
important in recent years. As a result, the Python ASGI
(Asynchronous Standard Gateway Interface) specification was
developed.
Django
Django is a full-featured web framework, that tags itself as the web
framework for perfectionists with deadlines. It was announced by
Adrian Holovaty and Simon Willison in 2003, and named after
Django Reinhardt, a twentieth century Belgian jazz guitarist. Django
is often used for database-backed corporate sites. I’ll include more
details on Django in Chapter 7.

Flask
In contrast, Flask, introduced by Armin Ronacher in 2010, is a micro
framework. Chapter 7 will have more information on Flask, and how
it compares with Django and FastAPI.

FastAPI
Finally we meet FastAPI, the subject of this book. Although FastAPI
was published by Sebastián Ramírez in 2018, it has already climbed
to third place of Python web frameworks, behind Flask and Django.
This chart of github stars (as of July 8, 2022) shows that it may pass
them at some point:
Figure 2-1. Github Stars

After careful investigation into alternatives, Sebastián came up with


a design that was heavily based on two third-party Python packages:
Starlette for web stuff
Pydantic for data stuff
And he added his own ingredients and special sauces to the final
product. You’ll see what I mean in the next chapter.

Review
This chapter covered a lot of ground related to today’s Python:
Useful tools for a Python web developer
The prominence of APIs and Services
Python’s type hinting, objects, and variables
Concurrency
Data structures for web services
Web frameworks
Part II. A FastAPI Tour

This part is a whatever-thousand foot/meter view of FastAPI — more


like a drone than a spy satellite. It covers the basics quickly, but
stays above the water line to avoid drowning you in details. It’s
meant to provide context for the things to come.
After you get used to the ideas in this part, Part III zooms down into
those details. That’s where you can do some serious good, or
damage. No judgement, it’s up to you.
Chapter 3. Overview

FastAPI is a modern, fast (high-performance), web framework for


building APIs with Python 3.6+ based on standard Python type
hints.
—Sebastián Ramírez

Preview
FastAPI was announced in 2018 by Sebastián Ramírez. It’s more
“modern” in many senses than most Python web frameworks —
taking advantage of some features that have been added to Python
3 in the last few years. This chapter is a quick look at FastAPI’s main
features.

What Is FastAPI?
Like any web framework, FastAPI helps you to build web
applications. Every framework is designed to make some operations
easier — by features, omissions, and defaults. As the name implies,
FastAPI targets development of web APIs, although you can use it
for traditional web content applications as well.
Some advantages claimed by the web site include:
Performance: As fast as node and golang in some cases,
unusual for Python frameworks
Faster development: No sharp edges or oddities
Better code quality: Type hinting and models help reduce bugs
Autogenerated documentation and test pages: Much easier than
hand editing OpenAPI descriptions
Another random document with
no related content on Scribd:
David held it a moment, and the tears flowed down his cheeks.
“Poor mother! Poor little Ralph!”
“Yes, they are needing you, my boy. And we’ll get you to them just
as soon as it’s possible.” The rector was silent a moment, stroking
David’s shoulder, giving him time to recover his composure. “I’ll see
that you are provided with money enough. There will be a carriage to
take you to the station at half-past six. It’s now a quarter past five.”
The rector turned to a safe in the corner of the room, and took out
some money. “Here,” he said, “is fifty dollars. You must not be in any
hurry about returning the amount. Good-bye, David, my boy, and
God bless you.”
David went down the stairs blinded with tears. Outside it was dark
except for the scattered lights along the road and the illuminated
windows of the buildings. David saw the dormitory ahead and
thought of the day when he had stood on the steps and received his
father’s last embrace, and as he stumbled on and the lights were
breaking and dancing through his tears he wished with all the
passionate love of his young heart that he could have that day, just
that one day, over again.
The janitor of the building brought the boy’s trunk down from the
loft, and soon David was at work, not merely emptying the drawers
of his wardrobe, but dismantling his room. He would never come
back to this place again; that he knew.
There came presently a knock on the door. He opened it and
found Wallace standing there.
“O Dave!” said Wallace and clasped his friend’s hand. He
continued after a moment, “Mr. Dean sent me to see if I could do
anything for you. He’s coming himself in a few minutes. Is there
anything I can get for you—anything at all?”
“No, thanks, Lester. I’m pretty nearly packed. Just sit with me
awhile.”
“The fellows feel awfully badly about it. Lots of them wanted to
come, but they thought maybe you’d rather be alone.”
“Yes, I think I would, except for you.”
Wallace sat and looked on in dumb sympathy while David
continued his packing. At last it was all finished, and David sat down
and looked out of the window into the darkness. While he waited
thus he spoke only once.
“I wish you’d known him, Lester,” he said.
Soon he saw the lights of a motor-car coming down the avenue;
the driver appeared and took the trunk; Wallace picked up the bag.
At the foot of the stairs Mr. Dean was waiting. David caught
Wallace’s hand and pressed it, unable to speak, and Wallace,
equally inarticulate, returned the pressure. The next moment David
and Mr. Dean were hidden within the automobile.
During most of the drive Mr. Dean occupied himself with advising
David about the practical details of his journey. But, after all, his talk
was chiefly to turn the current of David’s thoughts, for he had put
down on a paper all the important items for the boy’s guidance. As
David pocketed the memorandum that Mr. Dean finally gave him, he
felt that he must seem unresponsive and untouched by so much
kindness.
“O Mr. Dean, you don’t know how good to me I think you are! I—I
wish my father could know!”
“My dear boy, it’s just that we all want to help when we see our
friends in trouble.”
“Yes, but it’s the way you help. I shall always remember it.”
“I shall always remember your father, David. I have seen a great
many fathers here with their sons, but never one whose interest and
affection made quite such an appeal to me as his. It’s a long, long
way back, but he made me think of my own father; I was about your
age, David, when my father died.”
The automobile sped from the country road to the paved streets of
the town and drew up before the station.
“You’ll come back to us after Christmas, I hope, David,” said the
master.
“I shall probably not be able to. I don’t know just what there will be
for me to do,” David answered.
“I hope you will find it possible to continue in the career that your
father had planned.”
“I should like to, for his sake.”
“Whatever happens, David, our friendship mustn’t end here. You
must look on me as always your friend.”
The train drew into the station for its brief stop. David and Mr.
Dean shook hands at the steps and parted.
That night David had a few hours of broken sleep in his stuffy
berth; the next day he spent gazing out of the window at the brown
farming lands of New Jersey and Pennsylvania and the bare, stark
forests and the little villages that seemed to glance up at the train
with a start of wonder and to relapse into rumination after it fled by.
At ten o’clock the next morning the train drew into the station of the
city that was his home.
There was no one to meet him at the station. He took a Rosewood
car and in half an hour alighted at the familiar old street corner. With
his bag banging against his leg and his heart pounding in his breast,
he ran along the sidewalk. And then suddenly, though he had been
trying to prepare himself for this all through the journey, his legs
weakened and threatened to collapse under him, and tears flooded
his eyes. He passed through the gate with uncertain steps and a
sense that the world was reeling round him. The blinds were down,
and a black streamer fluttered beside the door.
From somewhere within the house they had been watching, for the
door opened as he mounted the steps; the next moment he had his
mother in his arms, and Ralph was standing by, with face upturned
to kiss him.
“He died yesterday afternoon at three o’clock,” said Mrs. Ives. “He
didn’t suffer; all that seemed to trouble him was that he couldn’t see
you.”
Trying to comfort his mother, who seemed now wholly to give way,
David controlled his own emotion. Presently she took him upstairs to
the room in which she had been sitting all the morning—the room
into which only slits of light came from behind the drawn shades; and
there David stood and looked upon his father’s face.
A week after the funeral David, returning the money that had been
lent him, wrote to Dr. Davenport that it would be impossible for him to
return to St. Timothy’s School. His mother’s resources were
extremely slender; indeed, David found that the income on which the
family must depend would be barely sufficient to sustain them if they
practiced the most rigid economy. Maggie must go, the house must
be sold or let, and they must move into narrower and less expensive
quarters.
Maggie, however, refused to accept dismissal.
“I’ve been with you altogether too long to be deserting you in your
trouble,” she said to Mrs. Ives.
“But, Maggie, we can’t afford—”
“Sure, and I shouldn’t think you could, the way the doctor was that
easy-going! But I’ve been thrifty—”
It was no use to argue with Maggie, and after some further
ineffectual remonstrance Mrs. Ives succumbed.
Maggie stayed, and a sign “To Let or For Sale” was planted in front
of the house beside the flagstone walk; and Mrs. Ives tried to feel
that it was a stroke of good fortune when within a week a tenant was
secured. She tried equally to feel that good fortune was again hers
when she hired, only a quarter of a mile away, a comfortable
apartment for considerably less than the rent she was to receive for
the house. But she shrank none the less from the preparation that
soon had to be made for moving. Often she burst into tears and left
Maggie to execute or direct the undertaking on which she had been
engaged. In those depressed moods her surest consolation was in
the re-reading of the letters of sympathy that had come to her after
her husband’s death and that had shown her how widely he had
been loved, how truly he had been respected. Perhaps the letter that
she read most often and with the greatest satisfaction was that from
Dr. Wallace; she had always felt that by the men of his profession
her husband had never been accorded full recognition; yet here
surely was the proof that she had been mistaken. Dr. Wallace wrote
as one who had known and appreciated and admired. And his son
had written to David, a boyish, sympathetic letter, with this sentence
at the end, “My father says that yours was fine.” Those letters were
not the only ones that helped to remove the old bitterness over what
had seemed to her the failure of the community to accord her
husband the place that he had earned; now at the end of all came
letters upon letters testifying to the existence of an affection that she
had thought withheld. She read them over and over, but Dr.
Wallace’s oftenest of all.
David’s plan was to go back to the high school after Christmas,
finish out the year and then try to find work in some business office.
He felt that he must abandon his ambition to be a surgeon and must
set about establishing himself in a position where he could at an
early date contribute to the support of the family and to Ralph’s
education. His mother lamented the necessity and protested against
the sacrifice, but was unable to suggest any alternative.
Christmas was a day that David and his mother looked forward to
with no happy expectancy. But on Christmas Eve they all hung up
their stockings as usual, and after Ralph had gone to bed David
assisted his mother in arranging the presents.
“So many,” Mrs. Ives sighed, “that our friends have given us! And
we have been able to give to so few!”
“Never mind,” David answered. “People aren’t going to think about
that.”
He kissed his mother—a paternal sort of kiss. Often in those days
he felt quite paternal toward her.
The next morning, though Mrs. Ives could not bring herself to
respond, “Merry Christmas!” to that greeting, delivered by each of
her sons and by Maggie, she did enjoy the pleasant spectacle of
Ralph’s excitement and of her older boy’s eager interest as they
opened bundles; she even had a mild pleasure in examining the
things that had been given to her. It became more than that; it
became a tenderer emotion when she found the books that were the
gifts of her two boys. But it was the arrival of the postman, about the
middle of the morning, that furnished the great sensation of the day.
He left several Christmas cards, two or three little packages and a
letter for David. The envelope bore the address of St. Timothy’s
School.
David opened it and in a moment was crying with excitement,
“Mother! Mother! Just look at this!” His face was so eager, his eyes
were so shining that Ralph came crowding up to look over his
mother’s shoulder as she read:

My Dear David: One who is deeply interested in you


and who has an affectionate memory of your father
and of his hopes and ambitions for you has
communicated to me his wish that you return to St.
Timothy’s and complete your course. He is not only
well able to bear the expense, but he is eager to do so;
in fact, he has already placed a sum of money to your
credit here, and I am therefore sending you a check to
cover your traveling expenses. He does not wish to
make himself known to you now; he hopes that you will
not make any inquiries concerning him. He has other
grounds than those of modesty for requesting this.
We shall all welcome you back after the Christmas
holidays. And I am very glad indeed that the school is
not after all to lose one of its best pupils.
Sincerely yours,
C. S. Davenport.

“Isn’t that splendid, mother!” David began, and then stopped, for
instead of joy there was an added sadness in his mother’s face.
“Yes, David, yes,” she answered, and quickly tried to assume
cheerfulness. “Only—it will be harder than ever to part with you now.”
“I won’t go if you feel you need me, mother.”
“Of course you must go. You could not decline an offer made by
one who wants to help you to carry out your dear father’s wishes.”
But David was still doubtful. “I wonder if I ought to go. I wonder if I
oughtn’t to stay here and find work—”
“No, David, no. We must look to the future, dear. I couldn’t think of
letting you sacrifice an opportunity so wonderfully offered. Who do
you suppose is giving it to you, David?”
“I can’t imagine.—unless it’s Dr. Wallace.”
“Of course! That’s just who it is!” Mrs. Ives’s thoughts reverted to
the sympathetic letter that he had written her. “Of course it’s Dr.
Wallace. He’s taking this way of showing how much he thought of
your father.”
“I shouldn’t wonder at all if Lester had suggested it to him,” said
David. “Lester’s my best friend. I suppose, though, I mustn’t say
anything to him about it.”
“No, since it’s Dr. Wallace’s wish.”
“Perhaps Lester will come and see me during the vacation;
perhaps he’ll refer to it in some way.”
“Of course, if he should do that. But we must be careful to respect
Dr. Wallace’s wish.”
She could not help rejoicing with her boy over his good fortune,
and she could not help sorrowing for it in her heart. Already she had
come to look upon him as her prop and her companion in the
loneliness with which she must always now be surrounded. Was
there no end to the sacrifices required of women? But even while her
spirit made that outcry, a look into her son’s radiant face comforted
her.
The day after Christmas the moving began. By the middle of the
afternoon it was all accomplished; some of the family possessions
were in storage, the rest were already disposed in a quite orderly
manner in the neat little apartment. David, who had gone back to the
house to effect a final clearance of discarded articles, had turned the
key in the lock for the last time. He looked up and saw Lester
Wallace entering at the gate and ran to meet him eagerly.
“Do you know my great news?”
“No. What?”
“I’m going back next term, after all.”
“O Dave, isn’t that great! Somehow I felt it must be all a mistake
that you weren’t coming back. All the fellows will be so glad.”
From Wallace’s manner David could not be sure whether he had
any knowledge or intimation of his father’s generosity or not. He
seemed, at any rate, not at all interested in the question how the
means for David’s return had been provided. So into that question
David did not go. He prevailed on Wallace to come into the new
apartment for a few minutes and meet his mother; she, with the
thought of Dr. Wallace foremost in her mind, could hardly refrain from
uttering words of gratitude that pressed to her lips. Altogether,
Wallace’s brief visit imparted a pleasant glow of cheerfulness and
hopefulness to Mrs. Ives on that trying first day in her new
surroundings.
Maggie did not disapprove of David’s return to St. Timothy’s so
much as he had expected. “Well,” she said, “I guess you’d better be
there than strammin’ round a small place like this. I’m sure it will
mean less than half as much work for me. I must say, though, if I
was that rich I had to be giving money away, I wouldn’t be doing it to
take a boy from his mother—whoever I was.”
That, to be sure, was just what David’s benefactor was doing, and
it came home to the boy when on the last day his mother
accompanied him to the station. Ralph, who had been excused from
school, was with them, and in the trolley car and afterwards on the
bench in the waiting-room sat snuggled close to his brother—
demonstrative in this way of his affection. Mrs. Ives was silent most
of the time, but often surreptitiously squeezed David’s hand. While
they waited, Wallace, accompanied by his father and mother,
entered; they came up to David and Mrs. Ives; and Mrs. Wallace
said, “It’s hard when we have to send them back, isn’t it?”
Mrs. Ives, mindful even in that moment of the obligation to which
she must not refer, answered, “Yes, it’s hard, but I am trying not to be
sorry. David is so glad.”
Dr. Wallace grasped David’s arm with one hand and his son’s arm
with the other and held the two boys for a moment while he said
genially, “Help each other along all you can, you two fellows.” And
David felt how splendid it must be to be able to give help, instead of
just receiving it—to be giving such help as his father all his life had
given to others; he felt that it was to enable him to do that very thing
that Dr. Wallace was sending him back to St. Timothy’s, and he
resolved to be worthy of the opportunity.
In the train David had the few last moments alone with his mother
and Ralph, just as Lester had with his mother and father. They were
silent moments, so charged with feeling that David sat with tear-
blurred eyes, aware only of his mother pressing his hand and Ralph
crowding against him softly.
“Write to us often, David,” his mother said. “And—and think of your
father every day.”
David nodded, too choked to speak. He kissed each of them—a
long, long kiss for his mother—hugged them close; and the next
moment they were gone.
CHAPTER VI
PROBATION

I t was after dark on the January afternoon when the sleigh in which
David Ives and Lester Wallace drove from the station to the school
drew up in front of the rectory. The boys had made the last stage of
their journey in company with a number of others; from New York it
had been a jolly and exciting trip. David had been surprised as well
as pleased by the greetings of fellows whom he had hardly known,
by the way in which they had said, “Awfully glad you’re coming back
to the school, Ives.” Even Henshaw had been, as David expressed it
afterwards to Lester, “mighty decent to him.”
The welcome from the rector was equally cordial. He kept David
for a few moments after Lester had gone.
“There are just one or two things that I might add to what I wrote in
my letter, David. Your friend who is putting you through wants you to
be under no handicap in your relations with the other fellows; in other
words, he wants you to have the usual amount of spending money,
so that you shall be able to take part freely in the games and sports.”
“That’s pretty fine of him, isn’t it!” David exclaimed. “But honestly,
Dr. Davenport, it doesn’t seem to me right to—to let him be so
generous.”
“I don’t think he will spoil you by over-indulgence,” the rector said
smiling. “If I were you I should accept the situation and make the
best of it. By the way, I wish you’d stop in and see Mr. Dean. He has
been expressing the greatest pleasure at the prospect of having you
back here, and I know he will appreciate your looking him up.”
So at once David betook himself to Mr. Dean’s cottage, and there
in the study he found the master, sitting in front of the fire, with the
old green eye-shade over his eyes.
“Hello, David!” Mr. Dean rose and came forward; he led David into
the room. “Something told me that we should have you with us
again; I felt sure that somehow you’d manage it.”
“I didn’t manage it,” David said. “It came to me as a great surprise
—a Christmas surprise, too.” Mr. Dean looked interested. “I suppose
you know, Mr. Dean, how it happens that I’m back.”
“I understood that some one who sympathized with your father’s
wishes for you was arranging it.”
“Yes. I don’t know who it is; at least I’m supposed not to know,
though I can’t help suspecting.”
Mr. Dean took off his glasses and polished them with his
handkerchief.
“It’s odd that the man should want to make a mystery of it,” he
remarked.
“Yes, I don’t quite understand that. He’s a doctor at home who
knew my father and wrote the finest letter about him! Well, I don’t
see why I shouldn’t tell you who I think it is; it’s Lester Wallace’s
father.”
“An old St. Timothy’s boy himself. Good for him! He won’t be
sorry.”
“I hope you had a good vacation, Mr. Dean.”
“Not the best. I had to spend most of it in Boston under an oculist’s
care, and I have to look forward to some tedious hours. No more
reading at night. Take care of your eyes, my boy.”
“They’re pretty strong, I guess. I’m sorry you’re having trouble with
yours, Mr. Dean. If you ever want somebody to come and read to
you, I wish you’d send for me.”
“Thank you, David; I’ll do that.”
But Mr. Dean did not care to talk about himself; he questioned
David concerning his mother and Ralph, expressed his sympathy for
Mrs. Ives’s feeling of forlornness at her son’s return to St. Timothy’s
and said he should think she would really hate the man who was
responsible for it. “Oh, no,” David hastened to say; “she’s just as
grateful to him as I am; only she couldn’t help being sorry, too.”
“Well, if it’s Dr. Wallace, it’s a pretty good investment, so far as his
own boy’s concerned,” remarked Mr. Dean. “Lester slid off badly last
term after you left us. Do you think you can take hold of him again
and keep him going?”
David was willing to try; he found Wallace willing to submit.
Indeed, Wallace seemed unwilling to make any independent effort
with his lessons; he needed the stimulus of David’s interest and
David’s prompting. Without them his mind was incorrigibly
preoccupied with athletics; it did not matter what the season might
be; his passion for athletics was universal. Now, in midwinter,
snowballing, coasting, snowshoeing, and hockey were keeping his
mind as active as his body; in study hours he was planning
expeditions, arranging snowball fights and ambuscades, imagining
himself the hero of exciting hockey games, in which he dodged
brilliantly through the opposing forces, steering the puck always
before him. Even when the weather was so bad that no form of
outdoor sport was possible, Wallace’s attention was not more easily
fixed on books. Then thoughts of the gymnasium engrossed him, of
the brilliant feats that could be executed there.
Indeed, as the time of the spring exhibition drew near, he became
more and more intent on qualifying himself for some prominent part
in it. He and Monroe practiced together daily and became proficient
in feats of ground and lofty tumbling. David, going into the
gymnasium one afternoon, was much impressed by the quickness,
sureness, and rhythm of their performance—somersaulting over
each other, snapping each other up from the mat, giving each other
a hand at just the right moment. “Pretty slick,” was David’s admiring
comment. “You make a great team.”
That was the opinion of the gymnasium instructor, who looked
forward to putting them on as one of the principal features of the
exhibition. Wallace lived in the gymnasium not merely during
playtime; his thoughts were there at all hours, and his studies
suffered accordingly. He rejected David’s offer to help him with his
Latin out of hours, and, as Mr. Dean did not see fit to renew the
arrangement that had been so advantageous to him the preceding
term, he no longer received any assistance from his friend. His Latin
recitations grew more and more uncertain; frequently he attempted
to bluff them through—seldom with any degree of success. A week
before the gymnasium exhibition, Mr. Dean set the class an hour
examination; David, glancing up from the task, which he found
simple, observed Wallace lolling indifferently in his seat and tapping
his teeth idly with his pencil. Later, when he looked again, Wallace
was writing busily, and David felt encouraged; he relinquished hope,
however, when he saw Wallace leave his seat half an hour before
the full time allotted for the examination had expired, hand in his
work at the desk, and depart jauntily from the room.
He did not encounter Wallace until after luncheon; then they met in
the hall of the dormitory.
“Cinch, wasn’t it?” Wallace said, and in surprise David asked,
“What?”
“Old Dean’s exam. I killed it. Did you see me get through way
ahead of time?”
“Yes, I was afraid that meant you hadn’t been able to do much with
it.”
“Oh, there were some things I didn’t know and others that I just
made a stab at. But I’m pretty sure I killed it. And I had an extra half-
hour practicing in the gym while you poor guys were writing away.”
David thought no more of the episode. Two days later, after the
Latin recitation, Mr. Dean returned to the boys their examination
books, with marks showing their rating. A was the highest mark
attainable, E meant failure. David, well pleased at seeing the large A
in red ink on the cover of his book, walked slowly down the corridor,
turning over the pages. Monroe joined him, happy at being awarded
a B, and they descended the stairs together and stood outside the
door of their building comparing their books. Suddenly Wallace burst
out upon them; they looked up, startled by his flaming, angry face.
“What do you think of that?” he cried and thrust his examination
book under their eyes. His hand shook in his rage. “See what that
old fossil’s done to me!”
The letter E adorned the cover, and under it was written: “I have
hesitated over this mark. In ordinary circumstances I might have
given such work as this D; it is poor enough at best, but it is not
wholly bad. Had you chosen to exert your mind to the utmost during
the full examination period, you would unquestionably have passed;
because you did not choose to do this, I mark you E.”
“A dirty trick!” exclaimed Monroe. “He admits you wrote a paper
good enough to pass you, and then he turns round and gives you E!”
“How does he know what I might have done if I’d stayed through
the hour!” Lester turned irately upon David. “Well, what do you think
of your friend now, Dave?”
David looked troubled. “It does seem pretty rough. But I suppose
Mr. Dean thought that was the only way of making you work.”
“Making me work!” Wallace’s eyes flashed more angrily than ever.
“I did enough work to pass; he admits it. That’s all I want. I’m not a
grind, like you; I don’t have to be. I don’t want to get A’s like you; I
don’t have to. Fooling round old Dean so much has turned you into a
prig.”
He walked rapidly away and left both David and Monroe to an
uncomfortable silence. David felt hurt; that Lester should take a fling
at his necessity was unkind. He sympathized with Lester, but he
sympathized with Mr. Dean, too. He said to Monroe, “Mr. Dean’s not
trying to be nasty; he’s just trying to keep Lester headed straight.”
“If Lester’s paper was good enough to pass him, he ought to have
passed,” replied Monroe obstinately.
The next morning in the Latin class Wallace sullenly said, “Not
prepared,” when his name was called. Mr. Dean looked at him for a
moment and then said, “I will ask you to wait and speak to me,
Wallace, after the hour.”
What that interview brought forth David was soon to learn. In the
noon intermission he was walking up to the dormitory when Wallace
joined him.
“He’s put me on probation,” Wallace announced, “because of my
Latin flunk. If I’d passed my Latin, I’d have been all right.”
“It’s hard luck.” David could think of nothing more to say.
“It’s pretty tough because now I can’t take part in the gymnasium
exhibition. It’s hard on Monroe because it cuts him out of a good half
of his stunts.”
“Did you talk to Mr. Dean about it?”
“Oh, yes, but it did no good. When I tried to argue with him, he
said he didn’t care to hear me. He has it in for me; that’s the size of
it. There’s just one thing that might help.”
“What?”
“Well, if you went to him and told him that you thought he hadn’t
been quite fair in his treatment of me, and if you’d show him how
unfair to Monroe it all is, he might reconsider. He likes you, and he’d
listen to anything you say.”
“I’ll explain to him about you and Monroe,” said David.
“I wrote home about the stunts we were going to do, and father
thought it was great. He’ll be awfully disappointed if I tell him I
couldn’t take part because of being on probation.”
So David went on his mission of intercession. He pleaded
Wallace’s cause as well as he could, but Mr. Dean remained
unmoved.
“The boy has been loafing, and now he has to pay the penalty,”
declared Mr. Dean. “And when he urges that it’s hard on Monroe, the
only answer is that in most cases the innocent are involved with the
guilty.”
“But if he really wrote an examination good enough to pass him, it
seems hardly fair—”
“Do you think, David, that I am choosing to be unfair to Wallace?”
“No, I shouldn’t have said that; but Lester thinks that you’re being
unfair to him.”
“He’s not willing to abide by consequences. It’s not a case for
leniency, David.”
David delivered the message and received nothing but
reproaches.
“I guess you didn’t let him see what a skunk he is,” Wallace
grumbled, and David replied:
“You know I don’t think he’s anything of the kind.”
“Monroe thinks he is,” declared Wallace with satisfaction. “I don’t
see why they keep an old fossil like that on here. You can stand up
for him, of course, because you’re one of his favorites; he’s a great
fellow for having pets.”
David walked away without making any retort. He was depressed
and disappointed. He had not believed Wallace could be so unjust.
His sense of obligation to Wallace’s father made his distress all the
more keen. It was not only Wallace that blamed him; Monroe also
was cool to him and thought that he could have made things right
with Mr. Dean if he had chosen to exert himself.
For a few days they let him alone, and he was quite unhappy.
Then came the night of the gymnasium exhibition; he sat among the
spectators and saw Monroe execute his various acrobatic feats in
partnership with Calvert, a stripling of the fourth form; it was a
creditable performance, but not what it would have been with
Wallace to assist. Nevertheless the applause was generous, and
Monroe was awarded a medal—first prize—for his work. This
success apparently took the soreness out of Monroe; at any rate, he
responded heartily to David’s congratulations afterwards and
resumed his old friendly relations with him, as if they had never been
interrupted. But Wallace’s stiffness did not relax; he did not drop into
David’s room, or do any of the little things that had formerly been the
natural signs and consequences of intimacy.
For David those were the dullest days of the year. The weather
was so bad that there were no outdoor sports; on account of
Wallace’s attitude he could not thoroughly enjoy the companionship
of any one, for somehow the friendship of no one else could
compensate him for the loss of Wallace’s.
And then, too, there was the sense that to Wallace indirectly, to
Wallace’s father certainly, he was under an obligation that he could
never repay. It made him unhappy to dwell on those thoughts, and
so he occupied himself as much as possible with his studies and
with reading; and he went more often to Mr. Dean’s rooms. He and
the master took walks together; in the evening sometimes Mr. Dean
summoned David from the schoolroom and asked him to read aloud;
it would be usually from something that David enjoyed—Thackeray
or Dickens or Shakespeare. Mr. Dean would sit in an armchair
before the fire, with his green eye-shade over his eyes and his
fingers interlocked; sometimes he would chuckle over a phrase, or
ask David to read a passage a second time; and David, thus having
his attention particularly drawn to those passages, was not long in
seeing why they were noteworthy. Those evenings with Mr. Dean
were the most pleasant of his diversions, though they did not tend to
increase his popularity. He knew that he was growing more and
more to be regarded as a grind and, worse than that, as a master’s
protégé.
Ruth took him to drive one day when the first breath of spring was
in the air.
“Oh,” said Ruth, “won’t you be glad when it’s summer again? Don’t
you get restless at this time of year?”
“There isn’t much to do in the way of sports,” David admitted. “Yes,
it does get tiresome.”
“Father says that there’s always more disorder just before the
spring vacation than at any other time—and less studying. Just think
of Lester Wallace. I wanted to see him win in the gymnasium
exhibition—and the foolish boy got into trouble instead.”
“Yes, it was too bad.”
“I scolded him for it, and he tried to lay the blame on Mr. Dean. But
it was too silly! He seemed to think that you and Mr. Dean were
under some obligation to put him through!”
David’s face clouded over. “I don’t know about Mr. Dean, but I feel
under such an obligation. Only it hasn’t seemed as if Lester wanted
my help.”
“He oughtn’t to want it. I’m disappointed in him. I told him so right
out.”
She sat up straight with her lips firmly together and her cheeks
flushed; David, glancing at her, decided that he should dislike very
much hearing from her that she was disappointed in him.
“I told him,” she went on, “that he was getting dependent on
everybody but himself, and that if he had any proper spirit he
wouldn’t accept help now from any one. And he got sarcastic at that
and thanked me for my helpful advice and said that he could get
along very well without any more of it. Since then we’re very cool to
each other.”
“That’s the way it is with Lester and me,” said David. “I dare say
I’ve given him too much helpful advice, too.”
“Anyway, he’ll have a good chance to come to his senses during
the spring vacation. You will probably be going home with him, won’t
you?”
“I’m not sure yet that I’m going home. It’s a long trip and pretty
expensive.”
David wondered if Ruth had reported that uncertainty of his to her
father, for that evening the rector summoned him to his study.
“I should have told you before this,” he said, “of a communication
that I’ve had from your friend, David. He wants you to spend your
vacation with your family. And so you may regard that as arranged.”
David’s face lighted up. “Isn’t that splendid! Oh, I wish you’d tell
him, Dr. Davenport, since I can’t, how thoughtful and generous I
think he is!”
Dr. Davenport smiled. “I’ll convey your appreciation, though I think
he is aware of it.”
David’s happiness was further increased when two days before
the close of the term Wallace said to him, “Want to share a section
with me on the train west of New York?”
“Sure, I do,” David answered.
“All right. I’ll match you for the lower berth.”
They matched, and David won. “I’d just as soon take the upper,”
he said, but Wallace would not consider such a change.
David was so glad to renew the old relations with Wallace that he
did not wonder very much why there had been any lapse in them. On
the journey Wallace took a Vergil out of his bag and began to study.
“I’m going to make up my Latin this vacation,” he explained. “I
want to play ball next term.”
“Let me help you,” urged David. “I’ll translate with you if you like.”
“No, I told Ruth Davenport I wouldn’t let anybody help me after
this, and I won’t. She got pretty fresh, taking me to task, and I’ll show
her.”
Wallace wore an injured look as he settled down in his seat and
began to study. After about half an hour, he glanced up. “Confound
it, Dave, I’ve got to have help on this! Here, how does it go?”
And David spent most of the journey tutoring his friend, and had
the satisfaction of feeling that in a way he was paying for his trip
home.
CHAPTER VII
BLINDNESS

I n the spring vacation David saw little of Wallace. He lunched one


day at his friend’s house and felt that he was under Dr. Wallace’s
particular scrutiny; it made him self-conscious. The surgeon, he
observed, looked at him shrewdly from time to time, as if measuring
him with some mental standard; David had an uncomfortable feeling
that he fell short of what was expected.
However, the doctor’s only comment was favorable enough. “You
lead the form in studies,” he said. “Lester tells me you’ve helped him
in his work. I wish he would work hard enough not to need help.”
“Well, you saw the Latin books I brought home with me,” said
Lester in an aggrieved voice.
“Yes, I saw them, but I haven’t seen you using them.”
“That’s all right; I’m going to. I studied on the train, didn’t I, Dave?”
And Mrs. Wallace came to his defense. “After all, boys shouldn’t
be expected to study hard in their vacations.”
On the train returning to St. Timothy’s Wallace was again
accompanied by his Latin books, and again invited David’s
coöperation. David observed that he opened to the place at which on
the homeward journey he had left off and concluded that Mrs.
Wallace’s sympathy had not quickened his zeal. Lester was too full
of reminiscences to keep long or steadily at work; he would interrupt
his studies to relate to David anecdotes of parties that he had
attended or of automobile trips that he had made. David listened with
eager interest and from time to time conscientiously directed his
friend’s thoughts back to the channels from which they so readily
escaped. With all his help the amount of ground covered in Vergil
during that trip was not appreciable.

You might also like