SlideShare a Scribd company logo
Microservice Apis Using Python Flask Fastapi
Openapi And More 1st Edition Jos Haro Peralta
download
https://ebookbell.com/product/microservice-apis-using-python-
flask-fastapi-openapi-and-more-1st-edition-jos-haro-
peralta-47399612
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Microservices In Sap Hana Xsa A Guide To Rest Apis Using Nodejs 1st
Edition Sergio Guerrero
https://ebookbell.com/product/microservices-in-sap-hana-xsa-a-guide-
to-rest-apis-using-nodejs-1st-edition-sergio-guerrero-11396532
Go Programming Cookbook Over 75 Recipes To Program Microservices
Networking Database And Apis Using Golang Ian Taylor
https://ebookbell.com/product/go-programming-cookbook-over-75-recipes-
to-program-microservices-networking-database-and-apis-using-golang-
ian-taylor-55484320
Effortless Cloudnative Apps Development Using Skaffold Simplify The
Development And Deployment Of Cloudnative Spring Boot Microservices On
Kubernetes With Skaffold Ashish Choudhary
https://ebookbell.com/product/effortless-cloudnative-apps-development-
using-skaffold-simplify-the-development-and-deployment-of-cloudnative-
spring-boot-microservices-on-kubernetes-with-skaffold-ashish-
choudhary-57415862
Microservices Communication In Net Using Grpc A Practical Guide For
Net Developers To Build Efficient Communication Mechanism For
Distributed Apps Fiodar Sazanavets
https://ebookbell.com/product/microservices-communication-in-net-
using-grpc-a-practical-guide-for-net-developers-to-build-efficient-
communication-mechanism-for-distributed-apps-fiodar-
sazanavets-38379570
Implementing Eventdriven Microservices Architecture In Net 7 Develop
Eventbased Distributed Apps That Can Scale With Everchanging Business
Demands Using C 11 And Net 7 1st Edition Joshua Garverick
https://ebookbell.com/product/implementing-eventdriven-microservices-
architecture-in-net-7-develop-eventbased-distributed-apps-that-can-
scale-with-everchanging-business-demands-using-c-11-and-net-7-1st-
edition-joshua-garverick-48224172
Principles Of Web Api Design Delivering Value With Apis And
Microservices Final Release 1st Edition James Higginbotham
https://ebookbell.com/product/principles-of-web-api-design-delivering-
value-with-apis-and-microservices-final-release-1st-edition-james-
higginbotham-36338630
Pro Restful Apis With Micronaut Build Javabased Microservices With
Rest Json And Xml 2nd Edition 2nd Sanjay Patni
https://ebookbell.com/product/pro-restful-apis-with-micronaut-build-
javabased-microservices-with-rest-json-and-xml-2nd-edition-2nd-sanjay-
patni-48103874
Pro Restful Apis With Micronaut Build Javabased Microservices With
Rest Json And Xml 2 Converted Sanjay Patni
https://ebookbell.com/product/pro-restful-apis-with-micronaut-build-
javabased-microservices-with-rest-json-and-xml-2-converted-sanjay-
patni-53591534
Pro Restful Apis With Micronaut Build Javabased Microservices With
Rest Json And Xml Sanjay Patni
https://ebookbell.com/product/pro-restful-apis-with-micronaut-build-
javabased-microservices-with-rest-json-and-xml-sanjay-patni-232237072
Microservice Apis Using Python Flask Fastapi Openapi And More 1st Edition Jos Haro Peralta
M A N N I N G
José Haro Peralta
Using Python, Flask, FastAPI, OpenAPI and more
Documentation-driven development is an API-first development method in which you design and document the
API first; then, you build the API server and the API client against the documentation; and finally, you use the API
documentation to validate the server and client implementations. Documentation-driven development helps you
reduce the chances of API integration failure, and it gives you more control and visibility of integration errors.
3. Test the implementation
against the specification.
API specification
API server developers
API client developers
1. API design and
documentation
2. Build the client
and the server
against the API
documentation.
REST APIs are structured around endpoints. We distinguish between singleton endpoints, such as GET /orders/8,
and collection endpoints, such as GET /orders. REST APIs leverage the semantics of HTTP methods to indicate
actions (such as POST to create resources), and they use HTTP status codes that signal the result of processing
the request (such as 200 for successful responses).
Singleton endpoints
PUT /orders/8
{payload}
DELETE /orders/8
Update an order Delete an order
Status code: 200
{payload}
Status code: 204
HTTP equests
r HTTP esponses
r
POST /orders/8/pay
{payload}
POST /orders/8/cancel
{payload}
Pay for an order Cancel an order
Status code: 200
{payload}
Status code: 200
{payload}
Collection endpoints
POST /orders
{payload}
Place an order
Status code: 201
{payload}
GET /orders
Get a collection
of orders
Status code: 200
{payload}
GET /orders/8
Retrieve an order
Status code: 200
{payload}
Singleton endpoints
Orders
service
API lient
c
Microservice APIs
Microservice Apis Using Python Flask Fastapi Openapi And More 1st Edition Jos Haro Peralta
Microservice APIs
USING PYTHON, FLASK, FASTAPI,
OPENAPI AND MORE
JOSÉ HARO PERALTA
M A N N I N G
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com
©2023 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning Publications
was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.
The author and publisher have made every effort to ensure that the information in this book
was correct at press time. The author and publisher do not assume and hereby disclaim any
liability to any party for any loss, damage, or disruption caused by errors or omissions, whether
such errors or omissions result from negligence, accident, or any other cause, or from any usage
of the information herein.
Manning Publications Co. Development editor: Marina Michaels
20 Baldwin Road Technical development editor: Nick Watts
PO Box 761 Review editor: Mihaela Batinić
Shelter Island, NY 11964 Production editor: Andy Marinkovich
Copy editor: Michele Mitchell
Proofreader: Katie Tennant
Technical proofreader: Al Krinker
Typesetter: Dennis Dalinnik
Cover designer: Marija Tudor
ISBN: 9781617298417
Printed in the United States of America
To Jiwon, without whose constant support and encouragement I wouldn’t
have been able to write this book, and to Ivy, that boundless spark of joy
that makes everything I do worth it.
Microservice Apis Using Python Flask Fastapi Openapi And More 1st Edition Jos Haro Peralta
vii
brief contents
PART 1 INTRODUCING MICROSERVICE APIS...............................1
1 ■ What are microservice APIs? 3
2 ■ A basic API implementation 20
3 ■ Designing microservices 45
PART 2 DESIGNING AND BUILDING REST APIS ........................59
4 ■ Principles of REST API design 61
5 ■ Documenting REST APIs with OpenAPI 90
6 ■ Building REST APIs with Python 110
7 ■ Service implementation patterns for microservices 144
PART 3 DESIGNING AND BUILDING GRAPHQL APIS ...............183
8 ■ Designing GraphQL APIs 185
9 ■ Consuming GraphQL APIs 210
10 ■ Building GraphQL APIs with Python 233
BRIEF CONTENTS
viii
PART 4 SECURING, TESTING, AND DEPLOYING
MICROSERVICE APIS ..................................................267
11 ■ API authorization and authentication 269
12 ■ Testing and validating APIs 302
13 ■ Dockerizing microservice APIs 331
14 ■ Deploying microservice APIs with Kubernetes 342
ix
contents
preface xvi
acknowledgments xviii
about this book xx
about the author xxv
about the cover illustration xxvi
PART 1 INTRODUCING MICROSERVICE APIS.....................1
1 What are microservice APIs? 3
1.1 What are microservices? 4
Defining microservices 4 ■
Microservices vs. monoliths 5
Microservices today and how we got here 7
1.2 What are web APIs? 8
What is an API? 8 ■
What is a web API? 9 ■
How do APIs help
us drive microservices integrations? 9
1.3 Challenges of microservices architecture 11
Effective service decomposition 11 ■
Microservices integration
tests 12 ■
Handling service unavailability 12 ■
Tracing
distributed transactions 13 ■
Increased operational complexity
and infrastructure overhead 14
1.4 Introducing documentation-driven development 15
CONTENTS
x
1.5 Introducing the CoffeeMesh application 17
1.6 Who this book is for and what you will learn 17
2 A basic API implementation 20
2.1 Introducing the orders API specification 21
2.2 High-level architecture of the orders application 22
2.3 Implementing the API endpoints 23
2.4 Implementing data validation models with pydantic 30
2.5 Validating request payloads with pydantic 34
2.6 Marshalling and validating response payloads
with pydantic 38
2.7 Adding an in-memory list of orders to the API 41
3 Designing microservices 45
3.1 Introducing CoffeeMesh 46
3.2 Microservices design principles 46
Database-per-service principle 46 ■
Loose coupling principle 48
Single Responsibility Principle 49
3.3 Service decomposition by business capability 49
Analyzing the business structure of CoffeeMesh 49 ■
Decomposing
microservices by business capabilities 50
3.4 Service decomposition by subdomains 52
What is domain-driven design? 52 ■
Applying strategic analysis to
CoffeeMesh 53
3.5 Decomposition by business capability vs. decomposition by
subdomain 57
PART 2 DESIGNING AND BUILDING REST APIS ..............59
4 Principles of REST API design 61
4.1 What is REST? 62
4.2 Architectural constraints of REST applications 63
Separation of concerns: The client-server architecture principle 64
Make it scalable: The statelessness principle 64 ■
Optimize for
performance: The cacheability principle 65 ■
Make it simple for the
client: The layered system principle 66 ■
Extendable interfaces: The
code-on-demand principle 66 ■
Keep it consistent: The uniform
interface principle 67
CONTENTS xi
4.3 Hypermedia as the engine of application state 67
4.4 Analyzing the maturity of an API with the Richardson
maturity model 70
Level 0: Web APIs à la RPC 71 ■
Level 1: Introducing the concept
of resource 71 ■
Level 2: Using HTTP methods and status
codes 72 ■
Level 3: API discoverability 72
4.5 Structured resource URLs with HTTP methods 73
4.6 Using HTTP status codes to create expressive HTTP
responses 77
What are HTTP status codes? 77 ■
Using HTTP status codes to
report client errors in the request 78 ■
Using HTTP status codes to
report errors in the server 82
4.7 Designing API payloads 83
What are HTTP payloads, and when do we use them? 83 ■
HTTP
payload design patterns 84
4.8 Designing URL query parameters 87
5 Documenting REST APIs with OpenAPI 90
5.1 Using JSON Schema to model data 91
5.2 Anatomy of an OpenAPI specification 95
5.3 Documenting the API endpoints 96
5.4 Documenting URL query parameters 97
5.5 Documenting request payloads 98
5.6 Refactoring schema definitions to avoid repetition 100
5.7 Documenting API responses 102
5.8 Creating generic responses 105
5.9 Defining the authentication scheme of the API 107
6 Building REST APIs with Python 110
6.1 Overview of the orders API 111
6.2 URL query parameters for the orders API 112
6.3 Validating payloads with unknown fields 115
6.4 Overriding FastAPI’s dynamically generated
specification 118
6.5 Overview of the kitchen API 120
6.6 Introducing flask-smorest 122
CONTENTS
xii
6.7 Initializing the web application for the API 123
6.8 Implementing the API endpoints 125
6.9 Implementing payload validation models
with marshmallow 129
6.10 Validating URL query parameters 133
6.11 Validating data before serializing the response 136
6.12 Implementing an in-memory list of schedules 140
6.13 Overriding flask-smorest’s dynamically generated API
specification 142
7 Service implementation patterns for microservices 144
7.1 Hexagonal architectures for microservices 145
7.2 Setting up the environment and the project
structure 148
7.3 Implementing the database models 149
7.4 Implementing the repository pattern for data access 155
The case for the repository pattern: What is it, and why is it
useful? 155 ■
Implementing the repository pattern 157
7.5 Implementing the business layer 162
7.6 Implementing the unit of work pattern 172
7.7 Integrating the API layer and the service layer 177
PART 3 DESIGNING AND BUILDING GRAPHQL APIS......183
8 Designing GraphQL APIs 185
8.1 Introducing GraphQL 186
8.2 Introducing the products API 189
8.3 Introducing GraphQL’s type system 192
Creating property definitions with scalars 192 ■
Modeling
resources with object types 193 ■
Creating custom scalars 194
8.4 Representing collections of items with lists 195
8.5 Think graphs: Building meaningful connections between
object types 196
Connecting types through edge properties 196 ■
Creating
connections with through types 198
CONTENTS xiii
8.6 Combining different types through unions
and interfaces 200
8.7 Constraining property values with enumerations 202
8.8 Defining queries to serve data from the API 203
8.9 Altering the state of the server with mutations 206
9 Consuming GraphQL APIs 210
9.1 Running a GraphQL mock server 211
9.2 Introducing GraphQL queries 214
Running simple queries 214 ■
Running queries with
parameters 215 ■
Understanding query errors 215
9.3 Using fragments in queries 217
9.4 Running queries with input parameters 219
9.5 Navigating the API graph 219
9.6 Running multiple queries and query aliasing 221
Running multiple queries in the same request 221 ■
Aliasing our
queries 222
9.7 Running GraphQL mutations 225
9.8 Running parameterized queries and mutations 226
9.9 Demystifying GraphQL queries 229
9.10 Calling a GraphQL API with Python code 230
10 Building GraphQL APIs with Python 233
10.1 Analyzing the API requirements 234
10.2 Introducing the tech stack 234
10.3 Introducing Ariadne 235
10.4 Implementing the products API 241
Laying out the project structure 241 ■
Creating an entry point
for the GraphQL server 242 ■
Implementing query resolvers 243
Implementing type resolvers 246 ■
Handling query parameters 252
Implementing mutation resolvers 256 ■
Building resolvers for custom
scalar types 258 ■
Implementing field resolvers 262
CONTENTS
xiv
PART 4 SECURING, TESTING, AND DEPLOYING
MICROSERVICE APIS ........................................267
11 API authorization and authentication 269
11.1 Setting up the environment for this chapter 270
11.2 Understanding authentication and authorization
protocols 271
Understanding Open Authorization 271 ■
Understanding
OpenID Connect 276
11.3 Working with JSON Web Tokens 278
Understanding the JWT header 279 ■
Understanding JWT
claims 280 ■
Producing JWTs 282 ■
Inspecting JWTs 284
Validating JWTs 286
11.4 Adding authorization to the API server 287
Creating an authorization module 287 ■
Creating an
authorization middleware 289 ■
Adding CORS
middleware 292
11.5 Authorizing resource access 293
Updating the database to link users and orders 294
Restricting user access to their own resources 297
12 Testing and validating APIs 302
12.1 Setting up the environment for API testing 303
12.2 Testing REST APIs with Dredd 304
What is Dredd? 304 ■
Installing and running Dredd’s default
test suite 305 ■
Customizing Dredd’s test suite with hooks 307
Using Dredd in your API testing strategy 315
12.3 Introduction to property-based testing 315
What is property-based testing? 315 ■
The traditional approach to
API testing 316 ■
Property-based testing with Hypothesis 318
Using Hypothesis to test a REST API endpoint 319
12.4 Testing REST APIs with Schemathesis 322
Running Schemathesis’s default test suite 322 ■
Using links to
enhance Schemathesis’ test suite 323
12.5 Testing GraphQL APIs 327
Testing GraphQL APIs with Schemathesis 327
12.6 Designing your API testing strategy 329
CONTENTS xv
13 Dockerizing microservice APIs 331
13.1 Setting up the environment for this chapter 332
13.2 Dockerizing a microservice 333
13.3 Running applications with Docker Compose 338
13.4 Publishing Docker builds to a container registry 340
14 Deploying microservice APIs with Kubernetes 342
14.1 Setting up the environment for this chapter 343
14.2 How Kubernetes works: The “CliffsNotes” version 344
14.3 Creating a Kubernetes cluster with EKS 346
14.4 Using IAM roles for Kubernetes service accounts 350
14.5 Deploying a Kubernetes load balancer 351
14.6 Deploying microservices to the Kubernetes cluster 353
Creating a deployment object 354 ■
Creating a service object 357
Exposing services with ingress objects 359
14.7 Setting up a serverless database with AWS Aurora 361
Creating an Aurora Serverless database 361 ■
Managing secrets
in Kubernetes 364 ■
Running the database migrations and
connecting our service to the database 367
14.8 Updating the OpenAPI specification
with the ALB’s hostname 370
14.9 Deleting the Kubernetes cluster 372
appendix A Types of web APIs and protocols 376
appendix B Managing an API’s life cycle 387
appendix C API authorization using an identity provider 391
index 403
xvi
preface
APIs and microservices have taken the software industry by storm. Under the pressure
of increasing software complexity and the need to scale, more and more organizations
are migrating from monolithic to microservices architecture. O’Reilly’s “Microservices
Adoption in 2020” report found that 77% of respondents had adopted microservices,
a trend that is expected to continue growing in the coming years.
Using microservices poses the challenge of driving service integrations through
APIs. According to Nordic APIs, 90% of developers work with APIs and they spend
30% of their time building APIs.1
The growth of the API economy has transformed
the way we build applications. Today, it’s more and more common to build products
and services that are delivered entirely over APIs, such as Twilio and Stripe. Even tradi-
tional sectors like banking and insurance are finding new lines of business by opening
their APIs and integrating within the Open Banking ecosystem. The wide availability
of API-first products means that we can focus on our core business capabilities when
building our own applications, while using external APIs to handle common tasks
such as authenticating users and sending emails.
It’s exciting to be part of this growing ecosystem. However, before we embrace
microservices and APIs, we need to know how to architect microservices, how to
design APIs, how to define an API strategy, how to make sure we deliver reliable inte-
grations, how to choose a deployment model, and how to protect our systems. In my
1
J. Simpson, “20 Impressive API Economy Statistics” (https://nordicapis.com/20-impressive-api-economy-statistics/
[accessed May 26, 2022]).
PREFACE xvii
experience, most organizations struggle with one or more of these questions, and a
recent report by IBM found that 31% of businesses haven’t adopted microservices due
to lack of internal expertise.2
Equally, Postman’s 2022 State of the API Report found
that 14% of respondents experience API integration failures 11%–25% of the time
(http:/
/mng.bz/Xa9v), and according to Salt Security, 94% of organizations experi-
enced API security incidents in 2022.3
Many books address the problems mentioned in the previous paragraph, but they
typically do it from a highly specific point of view: some focus on architecture, others
on APIs, and yet others on security. I felt there’s a gap for a book that brings all these
questions together and addresses them with a practical approach: essentially, a book
that can get an average developer up and running quickly with the best practices,
principles, and patterns for designing and building microservice APIs. I wrote this
book with that goal in mind.
Over the past years, I’ve had the opportunity to work with different clients helping
them to architect microservices and deliver API integrations. Working on those proj-
ects gave me a vantage view into the major hurdles that development teams face when
working with microservices and APIs. As it turns out, both technologies are deceivingly
simple. A well-designed API is easy to navigate and consume, while well-architected
microservices boost developer productivity and are easily scalable. On the other side
of the spectrum, badly designed APIs are error prone and difficult to use, and badly
architected microservices result in so-called distributed monoliths.
The obvious questions arise: How do you design good APIs? And how do you archi-
tect loosely coupled microservices? This book will help you answer these questions and
more. You’ll also get your hands dirty building APIs and services, and you’ll learn how to
secure them, test them, and deploy them. The methods, patterns, and principles that I
teach in this book are the outcome of many years of trials and experimentation, and I’m
very excited about sharing them with you. I hope you find this book a valuable resource
in your journey towards becoming a better software developer and architect.
2
“Microservices in the enterprise, 2021: Real benefits, worth the challenges,” (https://www.ibm.com/downloads/
cas/OQG4AJAM [accessed 26th May 2022]).
3
Salt Security, “State of API Security Q3 2022”, p. 4 (https://content.salt.security/state-api-report.html).
xviii
acknowledgments
Writing this book has been one of the most fascinating journeys in my career, and I
couldn’t have done it without the help and support of my family and an amazing
team of colleagues. The book is dedicated to my wonderful wife, Jiwon, without
whose constant encouragement and understanding I wouldn’t have been able to
complete this book, and to our daughter, Ivy, who made sure I never had a dull
moment in my schedule.
I have benefited enormously from the people who contributed ideas for the book,
helped me better understand the tools and protocols I use in it, and provided feedback
on various chapters and drafts. Special thanks go to Dmitry Dygalo, Kelvin Meeks,
Sebastián Ramírez Montaño, Chris Richardson, Jean Yang, Gajendra Deshpande, Oscar
Islas, Mehdi Medjaoui, Ben Hutton, Andrej Baranovskij, Alex Mystridis, Roope
Hakulinen, Steve Ardagh-Walter, Kathrin Björkelund, Thomas Dean, Marco Antonio
Sanz, Vincent Vandenborne, and the amazing maintainers of Ariadne at Mirumee.
Since 2020, I’ve presented drafts and ideas from the book at various conferences,
including EuroPython, PyCon India, API World, API Specifications Conference, and
various podcasts and meetups. I want to thank everyone who attended my presenta-
tions and gave me valuable feedback. I also want to thank the attendants to my work-
shops at microapis.io for their thoughtful comments on the book.
I want to thank my acquisitions editor, Andy Waldron. Andy did a brilliant job
helping me get my book proposal in good shape and keeping the book focused on rel-
evant topics. He also supported me tirelessly to promote the book and helped me to
reach a wider audience.
ACKNOWLEDGMENTS xix
The book you now have in your hands is readable and understandable thanks to
the invaluable work of my editor, Marina Michaels, who went far and beyond to help
me write a better book. She did an outstanding job helping me improve my writing
style, and keeping me on track and motivated.
I want to thank my technical editor, Nick Watts, who rightly pointed out many inac-
curacies and always challenged me to provide better explanations and illustrations,
and my technical proofreader, Al Krinker, who diligently checked all the code listings
and the GitHub repository for this book, making sure the code is correct and executes
without issues.
I also want to thank the rest of the Manning team who was involved in the produc-
tion of this book, including Candace Gillhoolley, Gloria Lukos, Stjepan Jureković,
Christopher Kaufmann, Radmila Ercegovac, Mihaela Batinić, Ana Romac, Aira Dučić,
Melissa Ice, Eleonor Gardner, Breckyn Ely, Paul Wells, Andy Marinkovich, Katie
Tennant, Michele Mitchell, Sam Wood, Paul Spratley, Nick Nason, and Rebecca
Rinehart. Thanks also go to Marjan Bace for betting on me and giving this book a
chance.
While working on this book, I had the opportunity to receive detailed and out-
standing feedback from the most amazing group of reviewers, including Alain
Lompo, Björn Neuhaus, Bryan Miller, Clifford Thurber, David Paccoud, Debmalya
Jash, Gaurav Sood, George Haines, Glenn Leo Swonk, Hartmut Palm, Ikechukwu
Okonkwo, Jan Pieter Herweijer, Joey Smith, Juan Jimenez, Justin Baur, Krzysztof
Kamyczek, Manish Jain, Marcus Young, Mathijs Affourtit, Matthieu Evrin, Michael
Bright, Michael Rybintsev, Michal Rutka, Miguel Montalvo, Ninoslav Cerkez, Pierre-
Michel Ansel, Rafael Aiquel, Robert Kulagowski, Rodney Weis, Sambasiva Andaluri,
Satej Kumar Sahu, Simeon Leyzerzon, Steven K Makunzva, Stuart Woodward, Stuti
Verma, and William Jamir Silva. I credit them all with much of the good content that
made its way into the book.
Since the book went into MEAP, I’ve been blessed by the words of encouragement
and feedback that many of my readers sent me through various channels, such as
LinkedIn and Twitter. I was also lucky to converse with a brilliant community of read-
ers who actively participated in the book’s forum in Manning’s liveBook platform. I’m
heartily grateful to all of you.
This book wouldn’t have been possible without the tireless work of thousands of
open source contributors who created and maintain the amazing libraries that I use in
this book. I’m very thankful to all of you, and I hope my book helps to make your
amazing work more visible.
Finally, thank you, the reader, for acquiring a copy of my book. I can only hope
that you find this book useful and informative and that you enjoy reading it as much
as I enjoyed writing it. I love to hear from my readers, and I’d be delighted if you
share your thoughts on the book with me.
xx
about this book
The goal of this book is to teach you how to build microservices and drive their inte-
grations using APIs. You’ll learn to design a microservices platform and to build REST
and GraphQL APIs to enable communication between microservices. You’ll also learn
to test and validate your microservice APIs, to secure them, and to deploy and operate
them in the cloud.
Who should read this book?
This book is helpful for software developers who work with microservices and APIs.
The book uses a very practical approach, and nearly every chapter illustrates the
explanations with full coding examples. Therefore, hands-on developers who work
directly with microservice APIs will find the book’s contents valuable.
The coding examples are in Python; however, knowledge of the language isn’t nec-
essary to be able to follow along with them. Before introducing new code, every con-
cept is explained thoroughly.
The book contains a lot of emphasis on design strategies, best practices, and devel-
opment workflows, and therefore it’s also useful for CTOs, architects, and VPs of engi-
neering who need to decide whether microservices are the right architectural solution
for them, or who need to choose between different API strategies and how to make
the integrations work.
ABOUT THIS BOOK xxi
How this book is organized: A roadmap
The book is divided into four sections with a total of 14 chapters.
Part 1 introduces the concepts of microservices and APIs, shows how to build a
simple API, and explains how to design a microservices platform:
 Chapter 1 introduces the main concepts of the book: microservices and APIs. It
explains how microservices differ from monolithic architecture, and when it
makes sense to use monoliths versus microservices. It also explains what APIs
are and how they help us drive integrations between microservices.
 Chapter 2 offers a step-by-step guide for implementing APIs using Python’s pop-
ular FastAPI framework. You’ll learn to read an API specification and under-
stand its requirements. You’ll also learn to build APIs in gradual steps, and how
to test your data validation models.
 Chapter 3 explains how to design a microservices platform. It introduces three
fundamental microservice design principles, and it explains how to decompose
a system into microservices, using decomposition by business capability and
decomposition by subdomains.
Part 2 explains how to design, document, and build REST APIs, and how to build a
microservice:
 Chapter 4 explains the design principles of REST APIs. It introduces the six
constraints of REST architecture and the Richardson Maturity Model, and
then moves on to explain how we leverage the HTTP protocol to design well-
structured and highly expressive REST APIs.
 Chapter 5 explains how to document a REST API using the OpenAPI specifica-
tion standard. You’ll learn the basics of JSON Schema syntax, how to define
endpoints, how to model your data, and how to refactor your documentation
with reusable schemas.
 Chapter 6 explains how to build REST APIs using two popular Python frame-
works: FastAPI and Flask. You’ll learn about the differences between the two
frameworks, but you’ll also learn how the principles and patterns for building
APIs remain the same and transcend the implementation details of any techni-
cal stack.
 Chapter 7 explains fundamental principles and patterns for building microser-
vices. It introduces the concept of hexagonal architecture, and it explains how
to enforce loose coupling between the layers of an application. It also explains
how to implement database models using SQLAlchemy and how to manage
database migrations using Alembic.
Part 3 explains how to design, consume, and build GraphQL APIs:
 Chapter 8 explains how to design GraphQL APIs and how the Schema Defini-
tion Language works. It introduces GraphQL’s built-in types, and it explains
ABOUT THIS BOOK
xxii
how to define custom types. You’ll learn how to create relationships between
types, and how to define queries and mutations.
 Chapter 9 explains how to consume GraphQL APIs. You’ll learn to run a mock
server and how to explore GraphQL documentation using GraphiQL. You’ll
learn to run queries and mutations against a GraphQL server and how to
parametrize your operations.
 Chapter 10 explains how to build GraphQL APIs using Python’s Ariadne frame-
work. You’ll learn to leverage the API documentation to automatically load data
validation models, and also to implement resolvers for custom types, queries,
and mutations.
Part 4 explains how to test, secure, and deploy your microservice APIs:
 Chapter 11 explains how to add authentication and authorization to your APIs
using standard protocols such as OpenID Connect (OIDC) and Open Authori-
zation (OAuth) 2.1. You’ll learn how to produce and validate JSON Web Tokens
(JWTs) and how to create an authorization middleware for your APIs.
 Chapter 12 explains how to test and validate your APIs. You’ll learn what property-
based testing is and how to use it to test your APIs, and you’ll also learn to use
API testing automation frameworks like Dredd and schemathesis.
 Chapter 13 explains how to Dockerize your microservice APIs, how to run them
locally using Docker Compose, and how to publish your Docker builds to AWS
Elastic Container Registry (ECR).
 Chapter 14 explains how to deploy your microservice APIs to AWS using Kuber-
netes. You’ll learn to create and operate a Kubernetes cluster using AWS EKS,
how to launch an Aurora serverless database into a secure network, how to
inject application configuration securely using envelope encryption, and how
to set up your services to operate at scale.
All chapters have a common theme: building components of a fictitious, on-demand
coffee delivery platform called CoffeeMesh. We introduce CoffeeMesh in chapter 1,
and in chapter 3, we break the platform down into microservices. Therefore, I recom-
mend reading chapters 1 and 3 to get a better understanding of the examples intro-
duced in later chapters. Otherwise, every part of the book is fairly independent, and
each chapter is pretty self-contained. For example, if you want to learn how to design
and build REST APIs, you can jump straight to part 2, and if your interest lies with
GraphQL APIs, you can focus on part 3. Equally, if you want to learn to add authenti-
cation and authorization to your APIs, you can jump straight into chapter 11, or if you
want to learn how to test APIs, you can go directly to chapter 12.
There’re some cross-references between chapters: for example, chapter 12 refer-
ences the API implementations from parts 2 and 3, but if you’re comfortable building
APIs, you should be able to skip directly to chapter 12. The same is true for the other
chapters in part 4.
ABOUT THIS BOOK xxiii
About the code
This book contains many examples of source code both in numbered listings and in
line with normal text. In both cases, source code is formatted in a fixed-width font
like this to separate it from ordinary text. Sometimes code is also in bold to high-
light code that has changed from previous steps in the chapter, such as when a new
feature adds to an existing line of code.
In many cases, the original source code has been reformatted; we’ve added line
breaks and reworked indentation to accommodate the available page space in the
book. In some cases, even this was not enough, and listings include line-continuation
markers (➥). Additionally, comments in the source code have often been removed
from the listings when the code is described in the text. Code annotations accompany
many of the listings, highlighting important concepts.
Except for chapters 1, 3, and 4, every chapter of the book is full of coding exam-
ples that illustrate every new concept and pattern introduced to the reader. Most of
the coding examples are in Python, except in chapters 5, 8, and 9, which focus on API
design, and therefore contain examples in OpenAPI/JSON Schema (chapter 5) and
the Schema Definition Language (chapters 8 and 9). All the code is thoroughly
explained, and therefore it should be accessible to all readers, including those who
don’t know Python.
You can get executable snippets of code from the liveBook (online) version of this
book at https:/
/livebook.manning.com/book/microservice-apis. The complete code
for the examples in the book is available for download from the Manning website at
www.manning.com, and from a GitHub repository dedicated to this book at: https://
github.com/abunuwas/microservice-apis. Every chapter has a corresponding folder
in the GitHub repo, such as ch02 for chapter 2. Unless otherwise specified, all file
references in each chapter are relative to their corresponding folder in GitHub.
For example, in chapter 2, orders/app.py refers to the ch02/orders/app.py file in
GitHub.
The GitHub repository for this book shows the final state of the code in every
chapter. Some chapters show how to build features progressively, in iterative steps. In
those cases, the version of the code you’ll find on GitHub matches the final version of
the code in the chapter.
The Python code examples in the book have been tested with Python 3.10, although
any version of Python upwards of 3.7 should work just the same. The code and the com-
mands that I use throughout the book have been tested on a Mac machine, but they
should work without problems on Windows and Linux as well. If you work on Windows,
I recommend you use a POSIX-compatible terminal, such as Cygwin.
I’ve used Pipenv to manage dependencies in every chapter. In each chapter’s
folder, you’ll find Pipfile and Pipfile.lock files that describe the exact dependencies
that I used to run the code examples. To avoid problems running the code, I recom-
mend you download those files at the start of every chapter, and install the dependen-
cies from them.
ABOUT THIS BOOK
xxiv
liveBook discussion forum
Purchase of Microservice APIs includes free access to liveBook, Manning’s online reading
platform. Using liveBook’s exclusive discussion features, you can attach comments to
the book globally or to specific sections or paragraphs. It’s a snap to make notes for your-
self, ask and answer technical questions, and receive help from the author and other
users. To access the forum, go to https:/
/livebook.manning.com/book/microservice
-apis/discussion. You can also learn more about Manning’s forums and the rules of
conduct at https://livebook.manning.com/discussion.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialogue between individual readers and between readers and the author can take
place. It is not a commitment to any specific amount of participation on the part of
the author, whose contribution to the forum remains voluntary (and unpaid). We
suggest you try asking him some challenging questions lest his interest stray! The
forum and the archives of previous discussions will be accessible from the publisher’s
website for as long as the book is in print.
Other online resources
If you want to learn more about microservice APIs, you can check out my blog, https://
microapis.io/blog, which contains additional resources that complement the lessons
of this book. On the same website, I also keep an up-to-date list of workshops and sem-
inars that I organize frequently, which also complement this book.
xxv
about the author
JOSÉ HARO PERALTA is a software and architecture consultant.
With over 10 years of experience, José has helped organizations
big and small to build complex systems, architect microservice
platforms, and deliver API integrations. He’s also the founder
of microapis.io, a company that provides software consulting
and training services. Recognized as a thought leader in the
fields of cloud computing, DevOps, and software automation,
José speaks regularly at international conferences and frequently
organizes public workshops and seminars.
xxvi
about the cover illustration
The figure on the cover of Microservice APIs is captioned “L’invalide,” or “The Dis-
abled,” and depicts a wounded French soldier who was a resident at the Hôtel
national des Invalides, or National House of the Disabled. This image is taken from a
collection by Jacques Grasset de Saint-Sauveur, published in 1797. Each illustration is
finely drawn and colored by hand.
In those days, it was easy to identify where people lived and what their trade or sta-
tion in life was just by their dress. Manning celebrates the inventiveness and initiative
of the computer business with book covers based on the rich diversity of regional cul-
ture centuries ago, brought back to life by pictures from collections such as this one.
Part 1
Introducing
Microservice APIs
Microservices are an architectural style in which components of a system
are designed as standalone and independently deployable applications. The
concept of microservices has been around since the early 2000s, and since the
2010s it has gained in popularity. Nowadays, microservices are a popular choice
for building modern websites. As you’ll learn in chapter 1, microservices allow
you to leverage the power of distributed applications, scale components more
easily, and release faster.
However, for all their benefits, microservices also come with challenges of
their own. They bring a substantial infrastructure overhead, and they’re more
difficult to monitor, operate, and trace. When working with microservices, the
first challenge is to get their design right, and in chapter 3 you’ll learn several
principles and strategies that will help you build robust microservices.
Microservices collaborate through APIs, and in this book, you’ll learn to
design and build REST and GraphQL APIs for your microservices. Chapter 2
gives you a taste of building a REST API, and in the second part of this book,
you’ll learn additional patterns and principles to build robust REST APIs. The
most challenging aspect of working with APIs is ensuring that both the API cli-
ent and the API server follow the API specification, and in chapter 1 you’ll learn
about documentation-driven development and the importance of starting the
API journey with a good and well-documented design.
2 PART 1 Introducing Microservice APIs
The first part of this book teaches you foundational patterns and principles for
building microservices and driving their integrations with APIs. In the rest of this
book, we build on top of the concepts introduced here, and you’ll learn how to build
robust APIs, how to test them, how to protect them, and how to deploy your microser-
vice APIs to the cloud. Our intrepid journey is just about to begin!
3
What are
microservice APIs?
This chapter defines the most important concepts in this book: microservices and
APIs. Microservices are an architectural style in which components of a system are
designed as independently deployable services, and APIs are the interfaces that allow
us to interact with those services. We will see the defining features of microservices
architecture and how they compare with monolithic applications. Monolithic appli-
cations are structured around a single code base and deployed in a single build.
We’ll discuss the benefits and the disadvantages of microservices architecture.
The last part of this chapter talks about the most important challenges that we face
when designing, implementing, and operating microservices. This discussion is not
to deter you from embracing microservices, but so that you can make an informed
decision about whether microservices are the right choice of architecture for you.
This chapter covers
 What microservices are and how they compare
with monolithic applications
 What web APIs are and how they help us drive
integrations between microservices
 The most important challenges of developing
and operating microservices
4 CHAPTER 1 What are microservice APIs?
1.1 What are microservices?
In this section, we define what microservices architecture is, and we analyze how
microservices compare with monolithic applications. We’ll look into the benefits and
challenges of each architectural pattern. Finally, we’ll also take a brief look at the his-
torical developments that led to the emergence of modern microservices architecture.
1.1.1 Defining microservices
So, what are microservices? Microservices can be defined in different ways, and,
depending on which aspect of microservices architecture we want to emphasize,
authors provide slightly different yet related definitions of the term. Sam Newman,
one of the most influential authors in the field of microservices, provides a minimal
definition: “Microservices are small, autonomous services that work together.”1
This definition emphasizes the fact that microservices are applications that run
independently of each other yet can collaborate in the performance of their tasks.
The definition also emphasizes that microservices are “small.” In this context, “small”
doesn’t refer to the size of the microservices’ code base, but to the idea that micro-
services are applications with a narrow and well-defined scope, following the Single
Responsibility Principle of doing one thing and doing it well.
A seminal article written by James Lewis and Martin Fowler provides a more detailed
definition. They define microservices as an architectural style with “an approach to
developing a single application as a suite of small services, each running in its own
process and communicating with lightweight mechanisms, often an HTTP resource
API” (https://martinfowler.com/articles/microservices.html). This definition empha-
sizes the autonomy of the services by stating that they run in independent processes.
Lewis and Fowler also highlight that microservices have a narrow scope of responsibil-
ities by saying that they are “small,” and they explicitly describe how microservices
communicate through lightweight protocols, such as HTTP.
DEFINITION A microservice is an architectural style in which components of a
system are designed as independently deployable services. Microservices are
designed around well-defined business subdomains, and they talk to each
other using lightweight protocols, such as HTTP.
From the previous definitions, we can see that microservices can be defined as an
architectural style in which services are components that perform a small and clearly
defined set of related functions. As you can see in figure 1.1, this definition means
that a microservice is designed and built around a specific business subdomain, for
example, processing payments, sending emails, or handling orders from a customer.
Microservices are deployed as independent processes, typically running in indepen-
dent environments, and expose their capabilities through well-defined interfaces. In
this book, you will learn to design and build microservices that expose their capabilities
1
Sam Newman, Building Microservices (O’Reilly, 2015), p. 2.
5
1.1 What are microservices?
through web APIs, though other types of interfaces are also possible, such as messag-
ing queues.2
1.1.2 Microservices vs. monoliths
Now that we know what microservices are, let’s see how they compare with the mono-
lithic application pattern. In contrast with microservices, a monolith is a system where
all functionality is deployed together as a single build and runs in the same process.
For example, figure 1.2 shows a food delivery application with four services: a pay-
ments service, an orders service, a delivery service, and a customer support service.
Since the application is implemented as a monolith, all functionality is deployed
together. We can run multiple instances of a monolithic application and have them
run in parallel for redundancy and scalability purposes, but it’s still the whole applica-
tion running in each process.
DEFINITION A monolith is an architectural pattern in which the whole applica-
tion is deployed as a single build.
In some situations, the monolith is the right choice of architecture. For example, we’d
use a monolith when our code base is small and it isn’t expected to grow very large.3
Monoliths also come with advantages. First, having the whole implementation in the
same code base makes it easier to access data and logic from different subdomains.
And because everything runs within the same process, it is easy to trace errors through
the application: you only need to place a few breakpoints in different parts of your
code, and you will get a detailed picture of what happens when something goes
wrong. Besides, because all the code falls within the scope of the same project, you
2
For a comprehensive view of the different interfaces that can be used to enable communication between
microservices, see Chris Richardson, Microservices Patterns (Manning, 2019).
3
For a thorough analysis of strategic architectural decisions around monoliths and microservices, see Vernon,
Vaughn and Tomasz Jaskula, Strategic Monoliths and Microservices (Addison-Wesley, 2021).
Payments service Orders service Email service
Food elivery pp
d a
Figure 1.1 In microservices architecture, every service implements a specific business
subdomain and is deployed as an independent component that runs in its own process.
6 CHAPTER 1 What are microservice APIs?
can leverage the productivity features of your favorite development editor when con-
suming functionality from a different subdomain.
However, as the application grows and becomes more complex, this type of architec-
ture shows limitations. This happens when the code base grows to a point where it
becomes difficult to manage, and when finding your way through the code becomes
arduous. Additionally, being able to reuse code from other subdomains within the same
project often leads to tight coupling among components. Tight coupling happens when
a component depends on the implementation details of another piece of code.
The bigger the monolith, the longer it takes to test it. Every part of the monolith
must be tested, and as we add new features to it, the test suite grows larger. Conse-
quently, deployments become slower and encourage developers to pile up changes
within the same release, which makes releases more challenging. Because many
changes are released together, if a new bug is introduced in the release, it is often dif-
ficult to spot the specific change that caused the bug and roll it back. And because the
whole application runs within the same process, when you scale the resources for one
component, you are scaling for the whole application. Long story short, code changes
become increasingly risky and deployments become more difficult to manage. How
can microservices help us address these issues?
Microservices address some of the issues associated with monolithic applications
by enforcing strict boundaries separating components. When you implement an
Food delivery app
Payments service Orders service
Delivery service
Customer support
service
Food delivery app
Payments
service
Orders service
Delivery service
Customer support
service
Food delivery app
Payments
service
Orders service
Delivery service
Customer support
service
Figure 1.2 In a monolithic application, all functionality is deployed together as a single build to each
server.
7
1.1 What are microservices?
application using microservices, each microservice runs in a different process, often
in different servers or virtual machines, and can have a completely different deploy-
ment model. As a matter of fact, they can be written in completely different program-
ming languages (that does not mean they should!).
Because microservices contain smaller code bases than a monolith, and because
their logic is self-contained and defined within the scope of a specific business subdo-
main, it is easier to test them, and their test suites run faster. Because they do not have
dependencies with other components of the platform at the code level (except per-
haps for some shared libraries), their code is clearer, and it is easier to refactor them.
This means the code can get better over time and become more maintainable. Con-
sequently, we can make small changes to the code and release more often. Smaller
releases are more controllable, and if we spot a bug, the releases are easier to roll back.
I’d like to emphasize that microservices are not a panacea. As we will see in section 1.3,
microservices also have limitations and bring challenges of their own.
Now that we know what microservices are and how they compare with monolithic
applications, let’s take a step back and see what developments led to the emergence of
this type of architecture.
1.1.3 Microservices today and how we got here
In many ways, microservices are not new.4
Companies were implementing and deploy-
ing components as independent applications well before the concept of microser-
vices became popular. They just did not call it microservices. Werner Vogels, CTO of
Amazon, explains how Amazon started to experiment with this type of architecture in
the early 2000s. By that time, the code base for the Amazon website had grown into a
complex system without a clear architectural pattern, where making new releases and
scaling the system had become serious pain points. To combat these issues, they
decided to look for independent pieces of logic within the code and separate them
out into independently deployable components, with an API in front of them. As part
of this process, they also identified the data that belongs to those components and
made sure that other parts of the system could not access the data except through an
API. They called this new type of architecture service-oriented architecture (https:/
/vimeo
.com/29719577). Netflix also pioneered this type of architectural style at scale, and
they referred to it as “fine-grained Service Oriented Architecture.”5
4
For a more comprehensive analysis of the history of microservices architecture and its precursors, see Nicola
Dragoni et al, “Microservices: Yesterday, Today, and Tomorrow,” Present and Ulterior Software Engineering (Springer,
2017), pp. 195–216.
5
Allen Wang and Sudhir Tonse, “Announcing Ribbon: Tying the Netflix Mid-Tier Services Together,” Netflix
Technology Blog, January 18, 2013, https://netflixtechblog.com/announcing-ribbon-tying-the-netflix-mid-tier
-services-together-a89346910a62. For an excellent discussion of the difference between service-oriented archi-
tecture (SOA) and microservices architecture, see Richardson, Microservices Patterns, pp. 13–14.
8 CHAPTER 1 What are microservice APIs?
The term microservice grew in popularity in the early 2010s to describe this type of
architecture. For example, James Lewis used this concept in a presentation at the 33rd
Degree conference in Krakow in 2012, under the title “Micro-Services—Java, the Unix
way” (https:/
/vimeo.com/74452550). In 2014 the concept was consolidated with a
paper written by Martin Fowler and James Lewis about the architectural features of
microservices (https://martinfowler.com/articles/microservices.html), as well as the
publication of Newman’s influential book Building Microservices.
Today, microservices are a widely used architectural style. Most companies in which
technology plays an important role are already using microservices or moving toward
its adoption. It is also common for startups to begin implementing their platform
using a microservices approach. However, microservices are not for everyone, and
although they bring substantial benefits, as we have shown, they also carry consider-
able challenges, as we will see in section 1.3.
1.2 What are web APIs?
In this section, we will explain web APIs. You will learn that a web API is a specific
instance of the more general concept of an application programming interface (API).
It is important to understand that an API is just a layer on top of an application, and
that there are different types of interfaces. For this reason, we will begin this section
by defining what an API is, and then we will move on to explaining how APIs help us
drive integrations between microservices.
1.2.1 What is an API?
An API is an interface that allows us to programmatically interact with an application.
Programmatic interfaces are those we can use from our code or from the terminal, as
opposed to graphic interfaces, in which we use a user interface to interact with the
application. There are multiple types of application interfaces, such as command-line
interfaces (CLIs; interfaces that allow you to use an application from a terminal),
desktop UI interfaces, web UI interfaces, or web API interfaces. As you can see in fig-
ure 1.3, an application can have one or more of these interfaces.
To illustrate this idea, think of the popular client URL (cURL). cURL is a CLI to the
libcurl library. libcurl implements functionality that allows us to interact with URLs,
Web application
programming interface
Command- ine
l
interface
Web user
interface
Desktop user
interface
Application
logic
Figure 1.3 An application can
have multiple interfaces, such
as a web API, a CLI, a web UI,
and a desktop UI.
9
1.2 What are web APIs?
while cURL exposes those capabilities through a CLI. For example, we can use cURL
to send a GET request to a URL:
$ curl -L http://www.google.com
We can also use cURL with the -O option in order to download the contents of a URL
to a file:
$ curl -O http://www.gnu.org/software/gettext/manual/gettext.html
The libcurl library sits behind the cURL CLI, and nothing prevents us from access-
ing it directly through the source code (if you are curious, you can pull it from
Github: https://github.com/curl/curl) and building additional types of interfaces for
this application.
1.2.2 What is a web API?
Now that we understand what an API is, we will explain the defining features of a web
API. A web API is an API that uses the Hypertext Transfer Protocol (HTTP) protocol
to transport data. HTTP is the communication protocol that underpins the internet,
and it allows us to exchange different kinds of media types, such as text, images, video,
and JSON, over a network. HTTP uses the concept of a Uniform Resource Locator
(i.e., URL) to locate resources on the internet, and it has features that can be lever-
aged by API technologies to enhance the interaction with the server, such as request
methods (e.g., GET, POST, PUT) and HTTP headers. Web APIs are implemented
using technologies such as SOAP, REST, GraphQL, gRPC, and others that are dis-
cussed in more detail in appendix A.
1.2.3 How do APIs help us drive microservices integrations?
Microservices communicate with each other using APIs, and therefore APIs represent
the interfaces to our microservices. APIs are documented using standard protocols.
The API documentation tells us exactly what we need to do to interact with the micro-
service and what kind of responses we can expect from it. The better the API docu-
mentation, the clearer it is for the API consumer how the API works. In that sense, as
you can see in figure 1.4, API documentation represents a contract between services:
Figure 1.4 API specifications
represent a contract between
the API server and the API
client. As long as both the
client and the server follow
the specification, the API
integration will work.
10 CHAPTER 1 What are microservice APIs?
as long as both the client and the server follow the API documentation, communica-
tion will work as expected.
Fowler and Lewis popularized the idea that the best strategy for integrating micro-
services is by exposing smart endpoints and communicating through dumb pipes (https://
martinfowler.com/articles/microservices.html). This idea is inspired by the design
principles of Unix systems, which establish that
 A system should be made up of small, independent components that do only
one thing.
 The output for every component should be designed in such a way that it can
easily become the input for another component.
Unix programs communicate with each other using pipelines, which are simple mech-
anisms for passing messages from one application to another. To illustrate this pro-
cess, think of the following chain of commands, which you can run from the terminal
of a Unix-based machine (e.g., a Mac or Linux computer):
$ history | less
The history command shows you the list of all commands you have run using your
Bash profile. The list of commands can be long, so you may want to paginate history’s
output using the less command. To pass data from one command to the another, use
the pipe character (|), which instructs the shell to capture the output from the history
command and pipe it as the input of the less command. We say that this type of
pipe is “dumb” because its only job is passing messages from one process to another.
As you can see in figure 1.5, web APIs exchange data through HTTP. The data trans-
port layer knows nothing about the specific API protocol we are using, and therefore
it represents our “dumb pipe,” while the API itself contains all the necessary logic to
process the data.
GET /orders
Host: Coffeemesh.com
Connection: Keep-alive
Content-type: Application/json
Content-length: 345
GET /orders
Orders API
Transport layer: TCP / UDP
(packets)
API
request
HTTP
protocol
Transport
layer
Figure 1.5 Microservices
communicate over APIs using
a data transport layer, such as
HTTP over TCP.
11
1.3 Challenges of microservices architecture
APIs must be stable, and behind them you can change the internal implementations
of any service provided they comply with the API documentation. This means that the
consumer of an API must be able to continue calling the API in the exact way as
before, and it must get the same responses. This leads to another important concept
in microservices architecture: replaceability.6
The idea is that you should be able to
completely replace the code base that lies behind an endpoint, yet the endpoint, and
therefore communication across services, will still work. Now that we understand what
APIs are and how they help us drive integrations between services, let’s look at the
most important challenges posed by microservices.
1.3 Challenges of microservices architecture
As we saw in section 1.1.2, microservices bring substantial benefits. However, they also
come with significant challenges. In this section, we discuss the most important chal-
lenges that microservices pose, which we classify into five main categories:
 Effective service decomposition
 Microservices integration tests
 Handling service unavailability
 Tracing distributed transactions
 Increased operational complexity and infrastructure overhead
All the problems and difficulties that we discuss in this section can be addressed with
specific patterns and strategies, some of which we detail over the course of this book.
You’ll also find references to other resources that deal with these issues in depth. The
idea here is to make you aware that microservices are not a magical cure for all the
problems that monolithic applications present.
1.3.1 Effective service decomposition
One of the most important challenges when designing microservices is service decom-
position. We must break down a platform into loosely coupled yet sufficiently inde-
pendent components with clearly defined boundaries. You can tell whether you have
unreasonable coupling between your services if you find yourself changing one service
whenever you change another service. In such situations, either the contract between
services is not resilient, or there are enough dependencies between both compo-
nents to justify merging them. Failing to break down a system into independent
microservices can result in what Chris Richardson, author of Microservices Patterns,
calls a distributed monolith, a situation where you combine all the problems of mono-
lithic architectures with all the problems of microservices, without enjoying the bene-
fits of any of them. In chapter 3, you’ll learn useful design patterns and service
decomposition strategies that will help you break down a system into microservices.
6
Newman, Building Microservices, pp. 7–8.
12 CHAPTER 1 What are microservice APIs?
1.3.2 Microservices integration tests
In section 1.1.2, we said that microservices are usually easier to test, and that their test
suites generally run faster. Microservices integration tests, however, can be signifi-
cantly more difficult to run, especially in cases where a single transaction involves col-
laboration among several microservices. When your whole application runs within the
same process, it is fairly easy to test the integration between different components,
and most of it will simply require well-written unit tests. In a microservices context, to
test the integration among multiple services you need to be able to run all of them
with a setup similar to your production environment.
You can use different strategies to test microservices integrations. The first step is
making sure that each service has a well-documented and correctly implemented
API. You can test the API implementation against the API specification using tools
like Dredd and Schemathesis, as you’ll learn in chapter 12. You must also ensure
that the API client is consuming the API exactly as dictated by the API documenta-
tion. You can write unit tests for the API client using the API documentation to gener-
ate mocked responses from the service.7
Finally, none of these tests will be sufficient
without a full-blown end-to-end test that runs the actual microservices making calls to
each other.
1.3.3 Handling service unavailability
We have to make sure that our applications are resilient in the face of service unavail-
ability, connections and request timeouts, erroring requests, and so on. For example,
when we place an order through a food delivery application such as Uber Eats, Deliv-
ery Hero, or Deliveroo, a chain of requests between services unfolds to process and
deliver the order, and any of those requests can fail at any point. Let’s take a high-level
view of the process that takes place when a user places an order (see figure 1.6 for an
illustration of the chain of requests):
1 A customer places an order and pays for it. The order is placed using the orders
service, and to process the payment, the orders service works together with the
payments service.
2 If payment is successful, the orders service makes a request to the kitchen ser-
vice to schedule the order for production.
3 Once the order has been produced, the kitchen service makes a request to the
delivery service to schedule the delivery.
In this complex chain of requests, if one of the services involved fails to respond as
expected, it can trigger a cascading error through the platform that leaves the order
unprocessed or in an inconsistent state. For this reason, it is important to design
7
To learn more about API development workflows and how to use API mock servers to build the client, check
out my presentation “API Development Workflows for Successful Integrations,” Manning API Conference,
August 3, 2021, https://youtu.be/SUKqmEX_uwg.
13
1.3 Challenges of microservices architecture
microservices so that they can deal reliably with failing endpoints. Our end-to-end tests
should consider these scenarios and test the behavior of our services in those situations.
1.3.4 Tracing distributed transactions
Collaborating services must sometimes handle distributed transactions. Distributed
transactions are those that require the collaboration of two or more services. For
example, in a food delivery application, we want to keep track of the existing stock of
ingredients so that our catalogue can accurately reflect product availability. When a
user places an order, we want to update the stock of ingredients to reflect the new
availability. Specifically, we want to update the stock of ingredients once the payment
has been successfully processed. As you can see in figure 1.7, the successful processing
of an order involves the following actions:
1 Process the payment.
2 If payment is successful, update the order’s status to indicate that it’s in progress.
3 Interface with the kitchen service to schedule the order for production.
4 Update the stock of ingredients to reflect their current availability.
Orders service Kitchen service
2. Upon successful payment, the orders service schedules the order.
Handle error
Orders service Payments service
1. The customer places an order and pays for it.
Handle error
Kitchen service Delivery service
3. Once the order is ready, the kitchen arranges its delivery.
Handle error
Figure 1.6 Microservices must be resilient to events such as service
unavailability, request timeouts, and processing errors from other
services and either retry the requests or come back to the user with
a meaningful response.
14 CHAPTER 1 What are microservice APIs?
All of these operations are related, and they must be orchestrated so that they either
all succeed or fail together. We can’t have an order successfully paid without correctly
updating its status, and we shouldn’t schedule its production if payment fails. We may
want to update the availability of the ingredients at the time of making the order, and
if payment fails later on, we want to make sure we rollback the update. If all these
actions happen within the same process, managing the flow is straightforward, but
with microservices we must manage the outcomes of various processes. When using
microservices, the challenge is ensuring that we have a robust communication process
among services so that we know exactly what kind of error happens when it does, and
we take appropriate measures in response to it.
In the case of services that work collaboratively to serve certain requests, you also
must be able to trace the cycle of the request as it goes across the different services to
be able to spot errors during the transaction. To gain visibility of distributed transac-
tions, you’ll need to set up distributed logging and tracing for your microservices.
You can learn more about this topic from Jamie Riedesel’s Software Telemetry (Man-
ning, 2021).
1.3.5 Increased operational complexity and infrastructure overhead
Another important challenge that comes with microservices is the increased opera-
tional complexity and operational overhead they add to your platform. When the
whole backend of your website runs within a single application build, you only need to
deploy and monitor one process. When you have a dozen microservices, every service
must be configured, deployed, and managed. And this includes not only the provi-
sioning of servers to deploy the services, but also log aggregation streams, monitoring
Products and
ingredients service
Kitchen service
Orders
service
Payments
service
Customer
Payment successful
Payment failed
Process the payment.
Update the
order’s state.
Notify the
customer.
Schedule the
order for
production.
Update the
stock of
ingredients.
Figure 1.7 A distributed transaction involves collaboration among multiple services. If any of these services
fails, we must be able to handle the failure and provide a meaningful response to the user.
15
1.4 Introducing documentation-driven development
systems, alerts, self-recovery mechanisms, and so on. As you’ll learn in chapter 3, every
service owns its own database, which means they also require multiple database setups
with all the features needed to operate at scale. And it is not unusual that a new deploy-
ment changes the endpoint for a microservice, whether it’s the IP, the base URL, or
a specific path within a generic URL, which means its consumers must be notified of
the changes.
When Amazon first started their journey toward a microservices architecture, they
discovered that development teams would spend about 70% of their time managing
infrastructure (https://vimeo.com/29719577 at 07:53). This is a very real risk that you
face if you do not adopt best practices for infrastructure automation from the begin-
ning. And even if you do, you are likely to spend a significant amount of time develop-
ing custom tooling to manage your services effectively and efficiently.
1.4 Introducing documentation-driven development
As we explained in section 1.2.3, the success of an API integration depends on good
API documentation, and in this section, we introduce an API development workflow
that puts documentation at the forefront of API development. As you can see in fig-
ure 1.8, documentation-driven development is an approach to building APIs that works
in three stages:
1 You design and document the API.
2 You build the API client and the API server following the documentation.
3 You test both the API client and the API server against the documentation.
Let’s dive into each of these points. The first step involves designing and documenting
the specification. We build APIs for others to consume, so before we build the API, we
must produce an API design that meets the needs of our API clients. Just as we involve
users when we design an application’s user interface (UI), we must also engage with
our API consumers when we design the API.
Good API design delivers good developer experience, while good API documenta-
tion helps to deliver successful API integrations. What is API documentation? API doc-
umentation is a description of the API following a standard interface description
language (IDL), such as OpenAPI for REST APIs and the Schema Definition Lan-
guage (SDL) for GraphQL APIs. Standard IDLs have ecosystems of tools and frame-
works that make it easier to build, test, and visualize our APIs, and therefore it’s worth
investing time in studying them. In this book, you’ll learn to document your APIs with
OpenAPI (chapter 5) and the SDL (chapter 8).
Once we have produced a documented API design, we move on to the second
stage, which consists of building the API server and the API client against the API
documentation. In chapters 2 and 6, you’ll learn to analyze the requirements of an
OpenAPI specification and to build an API application against them, and in chap-
ter 10, we’ll apply the same approach to GraphQL APIs. API client developers can
16 CHAPTER 1 What are microservice APIs?
also leverage the API documentation to run API mock servers and test their code
against them.8
The final stage involves testing our implementation against the API documenta-
tion. In chapter 12, you’ll learn to use automated API testing tools such as Dredd and
Schemathesis, which can generate a solid battery of tests for your API. Running Dredd
and Schemathesis in combination with your application unit test suite will give you
confidence that your API implementation works as it should. You should run these
tests in your continuous integration server to make sure you don’t release any code
that breaks the contract with the API documentation.
8
To learn how API server and client developers can leverage API documentation in their software development
process, check out my talk “Leveraging API Documentation to Deliver Reliable API Integrations,” API Specifi-
cations Conference, September 28–29, 2021, https:/
/youtu.be/kAWvM-CVcnw.
1. API design and
documentation
2. Build the client
and the server
against the API
documentation.
3. Test the implementation
against the specification.
Figure 1.8 Documentation-driven development works in three stages: design and document, implement,
and validate.
17
1.5 Who this book is for and what you will learn
By putting API documentation at the forefront of the development process,
documentation-driven development helps you avoid one of the most common problems
API developers face: disagreements between the client and the server development
teams about how the API should work. In the absence of robust API documentation,
developers often need to guess on implementation details of the API. In such cases,
the API rarely succeeds its first integration test. Although documentation-driven devel-
opment won’t give a 100% guarantee that your API integrations will work, it will sig-
nificantly reduce the risk of API integration failure.
1.5 Introducing the CoffeeMesh application
To illustrate the concepts and ideas that we explain throughout this book, we’ll build
components of an application called CoffeeMesh. CoffeeMesh is a fictitious applica-
tion that allows customers to order coffee in any location, at any time. The Cof-
feeMesh platform consists of a collection of microservices that implement different
capabilities, such as processing orders and scheduling deliveries. We’ll undertake a
formal analysis and design of the CoffeeMesh platform in chapter 3. To give you a
taste of the kinds of things you’ll learn in this book, we’ll begin implementing the API
of CoffeeMesh’s orders service in chapter 2. Before we close this chapter, I’d like to
dedicate a section to explaining what you’ll learn from this book.
1.6 Who this book is for and what you will learn
To make the most out of this book, you should be familiar with the basics of web devel-
opment. The code examples in the book are in Python, so a basic understanding of
Python is beneficial but not necessary to be able to follow along with them. You do not
need to have knowledge of web APIs or microservices, as we will explain these technol-
ogies in depth. It is useful if you are familiar with the model-view-controller (MVC)
pattern for web development or its variants, such as the model-template-view (MTV)
pattern implemented by Python’s popular Django framework. We will draw compari-
sons with these patterns from time to time to illustrate certain concepts. Basic familiar-
ity with Docker and cloud computing will be useful to get through the chapters about
deployments, but I’ll do my best to explain every concept in detail.
This book shows you how to develop API-driven microservices with Python
through a hands-on approach. You will learn
 Service decomposition strategies for designing microservice architectures
 How to design REST APIs and how to document them using the OpenAPI spec-
ification
 How to build REST APIs in Python using popular frameworks like FastAPI and
Flask
 How to design and consume GraphQL APIs and how to build them using
Python’s Ariadne framework
 How to test your APIs using property-based testing and API testing frameworks
such as Dredd and Schemathesis
18 CHAPTER 1 What are microservice APIs?
 Useful design patterns to achieve loose coupling in your microservices
 How to add authentication and authorization to your APIs using Open Authori-
zation (OAuth) and OpenID Connect (OIDC)
 How to deploy your microservices using Docker and Kubernetes to AWS
By the end of this book, you will be familiar with the benefits that microservices archi-
tectures bring for web applications as well as the challenges and difficulties that come
with them. You will know how to integrate microservices using APIs, you will know
how to build and document those APIs using standards and best practices, and you
will be prepared to define the domain of an API with clear application boundaries.
Finally, you’ll also know how to test, deploy, and secure your microservice APIs.
Summary
 Microservices are an architectural pattern in which components of a system are
designed and built as independently deployed services. This results in smaller
and more maintainable code bases and allows services to be optimized and
scaled independently of each other.
 Monoliths are an architectural pattern in which whole applications are deployed
in a single build and run in the same process. This makes the application easier
to deploy and monitor, but it also makes deployments more challenging when
the code base grows large.
 Applications can have multiple types of interfaces, such as UIs, CLIs, and APIs.
An API is an interface that allows us to interact with an application program-
matically from our code or terminal.
 A web API is an API that runs on a web server and uses HTTP for data trans-
port. We use web APIs to expose service capabilities through the internet.
 Microservices talk to each other using smart endpoints and “dumb pipes.” A
dumb pipe is a pipe that simply transfers data from one component to another.
A great example of a dumb pipe for microservices is HTTP, which exchanges
data between the API client and the API server without knowing anything about
the API protocol being used. Therefore, web APIs are a great technology for
driving integrations between microservices.
 Despite their benefits, microservices also bring the following challenges:
– Effective service decomposition—We must design services with clear boundar-
ies around specific subdomains; otherwise, we risk building a “distributed
monolith.”
– Microservice integration tests—Running integration tests for all microservices is
challenging, but we can reduce the risk of integration failures by ensuring
APIs are correctly implemented.
– Handling service unavailability—Collaborating services are vulnerable to service
unavailability, request timeouts, and processing errors, and therefore must be
able to handle those scenarios.
19
Summary
– Tracing distributed transactions—Tracing errors across multiple services is chal-
lenging and requires software telemetry tools that allow you to centralize
logs, enable API visibility, and trace requests across services.
– Increased operational complexity and infrastructure overhead—Each microservice
requires its own infrastructure provisioning, including servers, monitoring
systems, and alerts, so you need to invest additional efforts in infrastructure
automation.
 Documentation-driven development is an API development workflow that works
in three stages:
– Design and document the API.
– Build the API against the documentation.
– Test the API against the documentation.
By putting API documentation at the forefront of the development process,
documentation-driven development helps you avoid many common problems
that API developers face and therefore reduce the chances of API integration
failure.
20
A basic API
implementation
In this chapter, we implement the API for the orders service, which is one of the
microservices of the CoffeeMesh website, the project we introduced in section 1.5.
CoffeeMesh is an application that makes and delivers coffee on demand at any
time, wherever you are. The orders service allows customers to place orders with
CoffeeMesh. As we implement the orders API, you will get an early look into the
concepts and processes that we dissect in more detail throughout this book. The
code for this chapter is available under the ch02 folder of the GitHub repository
provided with this book.
This chapter covers
 Reading and understanding the requirements
of an API specification
 Structuring our application into a data layer,
an application layer, and an interface layer
 Implementing API endpoints using FastAPI
 Implementing data validation models (schemas)
using pydantic
 Testing the API using a Swagger UI
21
2.1 Introducing the orders API specification
2.1 Introducing the orders API specification
Let’s begin by analyzing the requirements of the orders API. Using the orders API, we
can place orders, update them, retrieve their details, or cancel them. The orders API
specification is available in a file named ch02/oas.yaml in the GitHub repository for
this book. OAS stands for OpenAPI specification, which is a standard format for docu-
menting REST APIs. In chapter 5, you’ll learn to document your APIs using OpenAPI.
As you can see in figure 2.1, the API specification describes a REST API with four
main URL paths:
 /orders—Allows us to retrieve lists of orders (GET) and create orders (POST).
 /orders/{order_id}—Allows us to retrieve the details of a specific order
(GET), to update an order (PUT), and to delete an order (DELETE).
 /orders/{order_id}/cancel—Allows us to cancel an order (POST).
 /orders/{order_id}/pay—Allows us to pay for an order (POST).
In addition to documenting the API endpoints, the specification also includes data
models that tell us what the data exchanged over those endpoints looks like. In
OpenAPI, we call those models schemas, and you can find them within the compo-
nents section of the orders API specification. Schemas tell us what properties must be
included in a payload and what their types are.
For example, the OrderItemSchema schema specifies that the product and the size
properties are required, but the quantity property is optional. When the quantity
property is missing from the payload, the default value is 1. Our API implementation
must therefore enforce the presence of the product and the size properties in the
payload before we try to create the order.
/orders/{order_id}
/cancel
/orders/{order_id}
/pay
GET
Returns an order
PUT
Updates an order
DELETE
Deletes an order
POST
Cancels an order
POST
Pays for an order
/orders/{order_id}
/orders
GET
Returns a list of orders
POST
Places an order
Figure 2.1 The orders API exposes seven endpoints structured around four URL paths. Each
endpoint implements different capabilities, such as placing and cancelling an order.
22 CHAPTER 2 A basic API implementation
# file: oas.yaml
OrderItemSchema:
type: object
required:
- product
- size
properties:
product:
type: string
size:
type: string
enum:
- small
- medium
- big
quantity:
type: integer
default: 1
minimum: 1
Now that we understand the requirements for building the orders API, let’s look at
the architectural layout we will use for the implementation.
2.2 High-level architecture of the orders application
This section offers a high-level overview of the orders API’s architectural layout. Our
goal is to identify the layers of the application and to enforce clear boundaries and
separation of concerns between all layers.
As you can see in figure 2.2, we organize into three layers: the API layer, the busi-
ness layer, and the data layer.
This way of structuring the application is an adaptation of the three-tier architecture
pattern, which structures applications into a data layer, a business layer, and a presen-
tation layer. As you can see in figure 2.3, the data layer is the part of the application
Listing 2.1 Specification for OrderItemSchema
API
Exposes the capabilities of the service
and controls interactions with the user
Business layer
Implements the capabilities
of the service
Data layer
Interfaces with the
source of data
Figure 2.2 To enforce separation of concerns among the different components of our service, we
structure our code around three layers: the data layer knows how to interface with the source of data;
the business layer implements the service’s capabilities; and the interface layer implements the
service’s API.
Random documents with unrelated
content Scribd suggests to you:
hänellä ase varana. Mutta käsipä hänellä vapisee, tärähtää pyssy
käsissä; niin on kiihtynyt veren kulku saanut suonet ja sydämmen
sykkimään, ett'eivät jäsenet pysy vakavina.
Isäntäkin on kuullut risahdukset ja päättää niistä, että karhu on
tulossa, mutta risahdusten ääni kuuluu toisen haaskan läheltä ja
varmaankin on metsän vilja sinne menossa. Kunhan vaan Lauri
pysyisi vakavana, liikahtamatta, jott'ei pelästyisi, ja tähtäisi tarkkaan,
niin kävisi kaikki hyvin.
Todella nyt liikkuu tiheikössä metsän mahtava kuningas. Se on
menossa sille haaskalle, missä Lauri vahtia pitää. Kun se vielä on
etempänä, liikkuu se sukkelammin, ja sen vuoksi kuuluukin joskus
risahdus, kun risut sen jalkojen alla katkeilevat, mutta, kuta
lähemmäs haaskaa se ehtii, sitä enemmän se vauhtiaan hiljentää ja
astuu sitten hyvin keveästi, varovasti, kuono maata vasten, tarkan
vainunsa avulla helposti osaten kulkea haaskaa kohti. Se astuu
askeleen pari kerralla ja sitten se pysähtyy, tarkkaa eteensä ja
sivulleen, ikäänkuin ajatellen, ett'eihän vaan mikään mahtane
havaita sen tuloa. Sitten se taas ottaa askeleen ja taas pysähtyy,
kääntää keveästi pyöreätä päätänsä, katselee ja kuuntelee. Niin se
kulkee hyvin varovasti ja pysähtyy melkein joka askeleella ja usein se
näyttää hyvin epäilevän, ett'ei olekaan hyvä mennä ikäänkuin aikoen
takaisin palata. Mutta kuitenkin se vähitellen lähenee haaskaa,
kunnes se tulee niin lähelle, että se on ainoastaan muutaman sylen
päässä siitä.
Lauri voipi nyt hämärästi huomata, että musta esine esiintyy
kuusten lomasta. Se on nyt se metsän kuningas; sen hän tietää
varmaan. Tuossa se nyt seisoo haaskan lähellä ihan liikahtamatta.
Johan sitä siihen saattaisi ampua, vaan pimeäpä on vielä haitaksi.
Antaahan likemmäksi tulla. Nyt se taas astuu askeleen, mutta
seisahtuu heti. Kyllä taitaa olla paras jo ampua; kenties se ei enää
lähenekään. Lauri pitää pyssynsä karhua kohti ojennuttuna ja
tähtää, käsi hanassa kiinni. Mutta ei ota pyssy vakaantuakseen
hänen käsissään. Niin kädet vapisevat, kun hän ajattelee, että nyt se
on ratkaiseva hetki. Kaiken pahan lisäksi on niin pimeä, ett'ei hän voi
nähdä, mihinkä kohtaan olisi paras ampua. Hän yhä tähtäelee ja
koettaa saada pyssynsä vakaantumaan; mutta se vaan yhä tärisee;
ja hän miettii, että jos ei satu käymään, niin kyllä pahat asiat saattaa
hänelle tulla. Mutta ei jouda hän kauan miettimään; hän vaan
tähtää, ja melkein vahingossa pyssy laukeaa; ja hän samalla itse
kovasti kiljahtaa pelosta, että nyt taisi käydä huonosti.
Isäntä, heti laukauksen kuultuaan, ajattelee että kuinkahan on
mahtanut käydä, mutta samassa Laurin huudon kuullessaan hän
arvelee, että nyt taitavat asiat olla huonosti; ja lähtee heti Laurin
vahtuupaikalle astumaan.
Mutta karhu, pyssyn lauettua, ei kaadukaan paikalleen, eikä se
karkaa ampujan kimppuun, vaan säikähtyneenä, kuitenkin aivan
vahingoittumatonna, se heti kääntyy takaisin ja lähtee kiireimmän
kautta pakoon pötkimään, laukkaa yli risujen ja kantojen, ja on pian
kaukana kuulumattomissa.
Lauri jääpi kummissaan miettimään, että näinkö se nyt kävi, ja
ajattelee sitten, että olipa se paha, kun ei pyssy ruvennut käsissä
vakaantumaan.
Kun isäntä ehtii haaskalle, kysyy hän heti: "No, mitenkä kävi?"
"Eipä käynyt hyvin", vastaa Lauri nolona. "Ei tainnut sattua, kun
minä ammuin."
"No, mitenkä sinä niin huonosti ammuit? Eikö se otus tullut aivan
lähelle."
"Ka, tulihan se kyllä. Mutta miten lie niin huonosti käynyt; minulla
ei ruvennut pyssy vakaantumaan käsissä."
"Pelottiko sinua?"
"Eipä kovin pelottanut, vaan ne kädet minulla niin vapisivat, niin se
tunnusti oudolta metsää ampua, jott'en saanut pyssyä
vakaantumaan, vaikka kuinka koetin, ja melkeinpä vahingossa
minulla pyssy laukesikin."
"Kyllä taisi pelko vaivata. Mutta mitä sinä rupesit kiljumaan?"
"No, minä kun ajattelin, että jos ei satukaan käymään, niin pääsi
minulta semmoinen huuto tulemaan."
"No, jopa tämä nyt oli! Meni hyvä saalis käsistä."
"Kyllähän tämä on paha asia. Mutta eihän sille enää voi mitään."
"Eihän sille enää voi mitään. Tottapa se niin oli sallittu. Mutta kyllä
nyt metsä saattaa olla kauan haaskalle tulematta."
Päivä alkaa nyt vähäsen kajastaa, ja isäntä ja Lauri lähtevät nyt,
huonosti onnistuneen yövahtuunsa perästä, aamuhämärässä
Mäntyvaaraan astumaan.
X.
Aamulla nukkuvat Mäntyvaaran miehet tavallista pitempään, he kun
ovat koko yön valvoneet, ja sillä aikaa ovat Anni ja Tiina lypsyllä.
Mutta vähemmin karttuu nyt maitoa kuin ennen, sillä paraimmat
lypsylehmäthän on karhu kaatanut ja jälillä olevat lypsävät
huonommin kuin ennen, ne kun ovat metsän tuloa säikähtäneet
eivätkä sen vuoksi uskalla kulkea paremmilla laiduinpaikoilla.
Kun oli ollut puhe, että joku vaimosista lähtisi karjalle paimeneksi,
niin oli syntynyt keskustelu siitä, kuka se lähtee, mutta kun Anni ja
Tiina olivat sanoneet pelkäävänsä, että mörkö paimenen hävittää,
niin oli Kaisu lausunut, jotta hän ei pelkää ja hän kyllä uskaltaa
lähteä, eikä möröstä välitä.
Kun siis lehmät ovat lypsetyt, lähtee Kaisu, eväskontti selässään,
karjan muassa metsään. Karjan polkua hän lähtee astumaan ja karja
pysyy koossa hänen ympärillään, ei yritäkään erota hänestä, sillä niin
se seuraa häntä kuin suojeliata ainakin. Se näyttää tietävän, että
sillä on vaarallinen vihollinen metsässä. Sen vuoksi se nyt ei etsi
ruohokkopaikkoja, ei pyri etäisemmille ruokaseuduille, vaan seuraa
paimenta minne tämä menee. Mutta sitä suuntaa, missäpäin
Kellokkaan ja Halunan raadot makaavat, se välttää ja rupeaa
ammoilemaan, kun paimen sinnepäin sattuu kääntymään. Kaisu
rientää iloisena karjan seurassa ja usein hän aikansa huviksi
kajahuttaa ilmoille laulun ja silloin metsä kai'ullaan vastaa hänen
laulusäkeihinsä. Milloin istahtaa hän pehmeälle mättäälle tai sileälle
kivelle levähtämään, kun karja on sattunut löytämään
ruohokkopaikan, milloin hän taas rientää kanervaisia kankaita ja
hakee tiensä mäntymetsän kautta, missä ei näy heinän korttakaan.
Kun hän metsässä kulkiessaan sattuu syrjään karjan näkyvistä, silloin
rupeaa karja kovasti mylvimään, ammoilee surkeasti, ikäänkuin
suurikin hätä olisi tarjona, mutta kun Kaisun lauluääni kajahtaa,
silloin karja taas lähtee hänen luokseen rientämään ja vasikat oikein
ilosta hyppelevät. Kilajaa nyt entinen Kellokkaan vaskikello toisen
lehmän, Kirjon, kaulassa, kilajaa, kun Kirjo laukata vilistää Kaisun
lähelle, ja rämisee läppä, lyöpi tiheään vasten laitoja, ja tiheään
lenkkasee kello puolelta toiseen. Niin kuuluu metsässä monenlaisia
ääniä: tuulen hiljainen humina korkeiden kuusten ja petäjäin
latvoissa, Kaisun heleästi kaikuva laulu, kellojen kilinä, lehmäin ja
vasikkain ammonta ja härän karhea mylvinä. Mutta ei mikään
häiritse paimenen ja karjan kulkua; ei kuulu metsän pedon ääntä
samoin kuin ei ihmisääntäkään muuta kuin Kaisun laulua. Metsän
kuningas ei näytä itseään, ei hätyytä karjaa, vaan makaa jossain
piilopaikassa, jossain mättään kolossa kuusen oksain peitossa.
Lämpimiinsä asti astuu Kaisu karjaa paimentaessaan ja hänen
punoittavat poskensa rupeavat tavallista enemmin hohtamaan,
mutta metsälle ne nyt saavat hohtaa, taivaalle punoittaa, sillä ei
kukaan ole niitä ihmettelemässä. Vihdoin Kaisu, koko päivän oltuaan
paimenessa, illan tultua paimentaa karjan kotiin tarhalle, missä se
pian pääsee suittusavun ääreen märehtimään ja Anni sekä Tiina
tulevat lehmiä lypsämään.
Ennen Kaisun kotiatuloa, ovat isäntä ja Lauri koteutuneet, he kun
ovat olleet talaitten teossa. Kummankin haaskan lähelle ovat he
läheisiin kuusiin istumasijat laittaneet, jotta siellä voisivat karhua
väijyä.
Mäntyvaaran isäntä kuvaellen mielessään, kuinka kunniakas teko
olisi saada metsän kuningas kaadetuksi, on päättänyt, että ainakin
monioita öitä on vahtuussa kulkeminen ja odottaminen, eikö sattuisi
mörkö vielä jommallekummalle haaskalle tulemaan. Vastakohtana
sille vahingolle, jonka karhu on talolle tuottanut, ovat kaikki
Mäntyvaaralaiset elähtyneet toivosta saada kenties vielä
mesikämmenen peijaita pitää, ja sen vuoksi kaikki vaan ajattelevat,
kuinka olisi hyvä asia, jos sattuisi karhu kaatumaan.
Mutta kun isäntä ja Lauri seuraavaksi yöksi vahtuuseen lähtevät,
ajattelevat he kuitenkin ett'ei mahtane mörkö sinä yönä näyttäytyä,
se kun oli viime yönä käynyt, ja luultavasti on se pahastunut
päivällisestä paukkeesta, sillä syntyihän sitä vähän möykettä, kun
talaita tehtiin. No, eihän kuitenkaan ennakolta voida tietää, mitä on
tapahtuva, ja sen vuoksi miehet lähtevät vahtaamaan karhua, kun
talaat vahtuuta varten ovat laitetut; ja kaksi jälkien palauttajaa
saattaa heitä nytkin niinkuin edellisellä kerralla.
Kun jälkien paluuttajat ovat kotia tulleet, jäävät naiset odottamaan
eikö sattuisi kuulumaan laukausta metsästä. Ammunta kyllä selvästi
kuuluisi taloon asti haaskoilta; ovat ne haaskat siksi lähellä. Mutta ei
kuulu mitään pyssyn laukausta, ei sittenkään kun päivä on mailleen
mennyt ja pimeys tullut. Odottajat paneutuvat vihdoin levolle ja
nukahtavat; ja yhä ovat vahtaajat poissa. Häiritsemättöminä
nukkuvat naiset ja lapset yönsä; ei heiltä unta riistä mikään outo
ääni tai liike, paikoillaan pysyvät talaillaan vahtaajat koko yön, ja
seinäkellon tasaiseen käyntiin he jo ovat niin tottuneet, että se ei voi
heitä häiritä.
Aamulla heidän noustessaan tulevat miehet kotia yölliseltä
vahtuultaan.
"No, kuinka kävi?" kysyy heti Kaisu.
"Arvaahan tuon, mitenkä on käynyt", vastaa Lauri. "Elossa on vielä
metsän kuningas."
"No, eikö sitä ole näkynytkään."
"Ka, eihän se näyttäynyt."
"Jopa tuota saatettiin jo ennakolta arvata", sanoo isäntä, "että
mörkö oli tulematta jäävä viime yöksi. Vaan kyllä se vielä käypi,
kunhan jaksetaan monioita öitä odottaa."
"Kukapa tuon tiennee, mitä se tekee!" puuttuu puheeseen
emäntä. "Se saattaa sitä ennen taas jonkun lehmän kaataa."
"No, ei tiedä mitenkä on sallittu."
"Eiköhän tuo mahtane tyytyä ennen kaatamiinsa", arvelee Lauri,
"niin kauan kuin niitä piisaa."
"Kyllä se karja säilyy, kun vaan aina on joku paimenessa",
vakuuttaa
Kaisu.
"Eipä kannata joka päiväksi paimenta panna", sanoo isäntä.
"Leikkuuseen tarvittaisiin väkeä, vaan eihän sinne jää paljon ketään
niin kauan kuin me miehet kuljemme vahtuussa ja joku nainen joka
päivä paimenessa."
"Pitää karjalla kuitenkin paimen olla niin kauan kuin mörkö näillä
seuduilla liikkuu."
"Lieneeköpä tuosta kovin isoa apua!" sanoo isäntä ja paneutuu
penkille levähtämään samoinkuin Lauri.
Levoltaan noustuaan lähtevät miehet pellolle — sitä ennen on
Kaisu mennyt lehmiä paimentamaan — ja illalla taas ennen pimeää
haaskoille. Isäntä on karhunpyyntihommassaan saanut tavallista
enemmän vireyttä ja elää toivossa vielä saada metsän kuningas
kaadetuksi. Lauriakin elähyttää sama toivo; hänkin odottaa vaan sen
päivän koittavan, jolloin mesikämmenen kunniaksi kemut pidetään.
Sen vuoksi he alusta pitäen joka yö käyvät vahtuussa. Mutta metsän
kuningas ei nyt näyttäydykään pitkään aikaan. Useat aamut
peräkkäin palaavat vahtaajat tyhjin toimin takaisin, mutta
tyynimielisenä ajattelee kuitenkin isäntä karhusta, että tottapahan se
vielä joskus tulee, kun lie tullakseen.
Niin kuluu päivä päivän perästä, ja peltotyö jääpi melkein
kokonaan vaimosten varaan, jotka kulkevat leikkuussa milloin vaan
muilta töiltään joutavat; mutta miehet kulkevat yöt vahtuussa ja
nukkuvat sitten päivillä niin kauan, ett'ei heiltä monta tuntia liikene
leikkuuta varten. Vähäksi avuksi on siis talolle, kun sinne muuanna
päivänä sattuu tulemaan kylästä kylään kuljeksiva Mikko niminen
kiertolainen, jonka isäntä heti laittaa pellolle leikkaamaan. Mutta
Mikko on vanha ja vaivainen ja muutenkin hidasliikkeinen, eikä
hänellä siis paljon valmista tule; hitaasti edistyy hänellä leikkuu.
Joka päivä kulkee karja laitumella, milloin Kaisu milloin Anni tai
Tiina paimenena, joskus paimenettakin, mutta aina kun se illalla
palaa kotia, antavat lehmät aina vähemmän maitoa; ne ehtyvät
ehtymistään. Karhu ei ole vielä toista kertaa käynyt haaskoilla, vaan
ei se ole lehmiäkään hätyyttänyt siitä hetkestä asti kuin se kaatoi
Kellokkaan ja Halunan.
Muutamana iltana taas ovat isäntä ja Lauri menneet vahtuuseen ja
kiivenneet kumpikin talailleen. On erittäin tyyni ilta. Päivä on ollut
lämmin ja poutainen, ja poudassa aurinko nyt laskee. Kyllähän heti
päivän mailleen mentyä alkaa hämärtää ja ilta pimenee; mutta yö ei
tule kuitenkaan aivan pilkko pimeä, sillä taivas on pilvetön ja siellä
vilkkuu nyt useita tähtiä. Aukealla kyllä näkisi vaikka linnunkin
ampua. Sitä vastoin täällä tiheässä metsässä tiheäoksaiset kuuset
niin varjostavat seudut, että pimeys tekisi isoa haittaa ampuessa.
Kuitenkin olisi nyt paljon helpompi huomata karhun tuloa kuin
esimerkiksi ensimmäisenä vahtuuyönä.
Vahtaajat istuvat talaillaan, odottavat odottamistaan ja ajattelevat,
että jopa se nyt saisi mörkö alkaa tulla, koska se ei taas moneen
yöhön ole näyttäynyt; alkaa se vahtuu lopulta ikäväksi käydä, kun he
joka yö saavat tyhjin toimin aina aamuun asti istua kököttää, jäsentä
liikuttamatta. He vuottavat vuottamistaan, kun yö tekee tuloaan,
vaan vielä ei kuulu mitään ääntä, ei näy liikettä missään. Näyttää jo
siltä, että tulisi yö yhtä pitkä ja ikävä kuin edellisilläkin kerroilla.
Mutta yhtäkkiä isäntä kuulee metsässä risuja rasahtelevan.
"No, nyt!" miettii hän iloisena ja kääntää jo pyssynsä valmiiksi
ääntä kohti. "Joko nyt viimein sinä armas metsän vilja tuloa teet!
Joko tuot turkkisi katsottavaksi! Tule pois vaan! En minä sinua
pahoin pitele. Kunnialla sinä kotiin saatetaan."
Piilopaikastaan oli todella metsän kuningas lähtenyt liikkeelle ja
kulkenut korpien läpi, soiden yli. Nyt se lähenee haaskaa varovin
askelin, astuu hiljaa ja aina väliin pysähtyy tarkataksensa, huomaako
kukaan sen tuloa. Tuolta astuu se nyt kuusten välistä näkyviin, astuu
varovasti ja pysähtyy joka askeleen päästä katsomaan,
kuuntelemaan. Se ei ole enää kaukana raadosta. Isäntä kiihtynein
mielin katselee, jott'eikö se tule vielä likemmäksi, mutta ei hän luule
malttavansa odottaa niin kauan että se käypi käsiksi raatoon. Nyt se
taas askeleen astuttuaan pysähtyy. Kaikki on hiljaista; ei kuulu
vähintäkään ääntä.
Tuli ja leimaus! Kuuluu kova pyssyn pamaus, ja kovasti kajahtaa
metsä.
Mäntyvaaran isäntä on laukaissut pyssynsä.
"No, mitenkähän nyt, armas mesikämmen —" miettii hän ja
rupeaa katsomaan, kellistyykö maahan metsän kuningas.
Mutta karhu heti pyssyn lau'ettua katsahtaa ääntä kohti ja huomaa
miehen. Sitä kovin suututtaa, että se on tullut häirityksi juuri kun se
on ollut aikeessa käydä käsiksi makeaan ateriaan, suututtaa niin,
että, kun se ei voi ampujalle mitään tehdä, se, väkevyytensä ja
vihansa näytteeksi, voimakkailla käpälillään kiskasee viereltään puun
kannon juurineen maasta irti ja paiskaa sen sitten voimakkaasti
maata vasten, jotta koko kanto hajoaa pirstaleiksi ja pauke kaikuu
kauas metsässä.
"Tyhjää siinä voimiasi näytät", arvelee isäntä, luullen karhun kohta
henkensä heittävän.
Mutta eipä uuvukaan metsän vilja, ei kaadu siihen paikkaan, vaan
heti, kannon käsistään paiskattuaan, se kiireimmän kautta lähtee
takaisin laukkaamaan samoja jälkiä kuin oli tullutkin, laukkaa yli
risujen ja mättäiden kauas kuulumattomiin.
"Voi ihmettä! Nyt kumma tuli", miettii isäntä, korvallistaan kynsien.
"Tämäpä nyt — No, mikähän nyt tuli, kun ei kaatunutkaan mörkö!"
Ja hän laskeupi hitaasti alas puusta.
Hän menee sille paikalle seisomaan, jossa karhu vast'ikään oli
ollut, ja siinä hän katselee ja kuuntelee, jotta eikö kuulu metsän
kuningasta missään; siinä hän siunaelee ja päivittelee ja kynsii
päätään ja ajattelee, että ihan todellako se saalis pääsi käsistä. Niin
— kyllä se nyt on mennyt.
"Voi kuitenkin! Kuinka tämä on mahdollista!" miettii hän pahoillaan
ja huutaa Lauria.
Lauri tuleekin vähän ajan perästä ja kysyy heti: "No, joko nyt
kaatui?"
"Kaatui! Eikö!" vastaa isäntä. "Minkälainen se lie eläjä! Ei siihen
pyssy tehonnut."
"Tosiaanko! Sepä nyt! No, ammuittehan te tarkkaan?"
"Ka, minä ammuin niin tarkkaan, jott'ei kyllä ammunnassa vikaa
ollut, ja kyllä sattui."
"Mutta jos ei sattunutkaan?"
"Sattunutko! Ihan vissiin sattui ja hyvään paikkaan. Minä ammuin
ihan sydäntä kohti."
"Mutta eihän kuitenkaan ole sanottu, että te osasitte sydämmeen.
Kuinka tuli likelle mörkö?"
"Tässä näin, juuri tällä kohdalla, jossa minä nyt olen, seisoi se. Ja
olisi se tullut likeimnäksikin, vaan minä en malttanut odottaa."
"Siinäpä se! On saattanut, kun kuitenkaan ei otus ollut tämän
likempänä, ja pimeäkinhän on tehnyt haittaa, — on saattanut
kuitenkin teillä käsi pettää."
"Eipä pettänytkään, totta vie. Niin totta kuin minä olen minä, niin
minä ammuin ihan tarkkaan ja luoti kyllä kävi oikeaan paikkaan."
"No, sitten kai on mörkö kaatunut. Jos se vaan on saanut luodin
rintaansa, niin ei se kaukana olekaan täältä."
"Niin sen luulisi; vaan mikä lie ollut pyssyssäni vikana, kun se ei
tehonnut. Metsä vaan, heti kun olin ampunut, ikäänkuin ei olisi
käynytkään, tempasi maasta irti kannon, — tuossahan tuo vielä kolo
näkyy — ja lyödä läjähytti sen sitten pirstaleiksi maata vasten
semmoisella jytäkällä, jotta se vasta jytäkkää oli."
"Niin, kuulinhan minäkin jotain sen tapaista."
"Ja sitten se heti kääntyi poispäin, sinnepäin, mistä oli tullutkin,
otti laukan semmoisen, jotta se vasta kyytiä oli. Nyt se jo saattaa
hyvinkin kaukana olla."
"Entäpä, jos ei olisikaan!"
"Voi, kyllä se ei tämän seudun likellä ole."
"Kukapa sen vielä tietää! Jos siihen vaan on luoti käynyt, niin se ei
ole hyvin kauas mahtanut päästä. Eiköhän mahtane tässä verijälkiä
olla näkyvissä! Katsotaanpa! Piti kai minulla tikkuja olla — minne
lienevät painuneet — no, eikö niitä — luulisippa — jopa löytyi."
Lauri kun on saanut tulitikkuunsa valkean, niin sen valossa hän ja
isäntä katselevat, jotta näkyykö mitään; ja todella onkin kannon
sijan vieressä muutamia veritilkkoja. Siinä on yhdessä kohti
sammalikko punertunut verestä, mutta muualla siinä lähellä ei näy
yhtään verijälkeä, vaikka Lauri uudestaan virittää tulen toiseen
tikkuun.
"Onpahan käynyt", sanoo Lauri.
"No, tiesinhän minä, että kävi se", sanoo vastuuksi isäntä, "ihan
sydämmeen kävi."
"Tokkopahan lie sydämmeen käynyt! Sittenhän olisi peto tähän
paikkaan kaatunut."
"Ka, niinhän minäkin luulin ampuessani, jotta kyllä se nyt tähän
paikkaan kaatuu. Mutta älähän! Hyvin kummiini menin, kun se lähti
täältä pois laukkaamaan. Siihen ei minun pyssyni tehonnut; ja minä
alan luulla, että kunhan ei liene minun pyssyni pilattu."
"Pilattuko!"
"No, niinpä minusta tunnustaa, että pilattu se mahtaa olla,
koskapahan ei tappanut."
"Mikäpä sen olisi pilannut?"
"Ka, Kuuselainen sen on mahtanut pilata."
"Mitenhän lienee! Mutta emmehän vielä tiedä, onko mörkö
kaatunut vai ei. Entäpä jos ei luoti sattunutkaan ihan sydämmeen."
"Kylläpä sen piti sattua."
"Mikäpä sen niin tarkkaan tietää! On saattanut sattua semmoiseen
paikkaan, ett'ei ole heti tehonnut, vaan on se kuitenkin saattanut
jälestäpäin vaikuttaa, ja olisihan mahdollista, että metsän kuningas
jossain mättään kolossa kuolleena maata mätköttää."
"Eipä mahtane kuolleena olla minun luullakseni. Semmoiseltapa
sen lähtö näytti, että ihan terveenä se oli."
"On siihen kuitenkin vika tullut, koskapahan on verta vuotanut.
Saamme tulla aamulla vielä katsomaan, jotta eikö sattuisi sitä
löytymään missään."
"Ka saisihan tuota tulla. Jos siltä on verta muualle vuotanut kuin
tähän, niin sittenhän tuota voitaisiin sen jälille päästä. Mutta jos vaan
minun pyssyni on pilattu, niinkuin pelkään, niin kyllä silloin on turha
vaiva hakea. Mutta olkoonpa miten tahansa, niin niinhän kuitenkin
on tapahtunut kuin on sallittu."
"Ka niin. Eihän se tämä asia enää muutu. Mutta eipä tässä vielä
varmuudella tiedetä, kuinka on käynytkään. Sittenpähän huomenna
nähdään."
Vihdoin keskustelunsa lopetettuaan lähtevät vahtaajat kotiapäin
astumaan, kun kuitenkin pitävät varmana, ett'ei metsä sinä yönä
enää haaskoille tule. Ja kotia tultuaan he heti käyvät levolle, kerran
taas yönsä rauhassa nukkumaan monien valvomisien perästä.
XI.
Seuraavana päivänä Mäntyvaaran miehet, kerrottuaan koko talon
väelle, kuinka vahtuu ja ammunta oli huonosti onnistunut, käyvät
vielä metsässä katsomassa, eikö sattuisi karhu jostain löytymään.
Mutta verijälkiä näkyy ainoastaan siinä paikassa, jossa karhu oli
seisonut isännän sitä ampuessa ja monioita vähempiä jälkiä siitä
pikkusen matkaa sitä suuntaa kohti, minne karhu oli kadonnut, vaan
sittenpä ne jäljet loppuvatkin, katoavat kerrassaan, eikä metsän
kuningasta löydetä mistään, ei elävänä eikä kuolleena; ja tyhjin
toimin täytyy miesten kotia palata, kun eivät kuitenkaan voi osata
karhun olopaikalle.
Nyt on isäntä yhä enemmän vakuutettu siinä luulossa, että hänen
pyssynsä on pilattu eli lumottu, eikä se siis voi tehota, vaikka kuinka
hyvään paikkaan sattuisi käymään. Sen vuoksi hän jo on kyllästynyt
koko vahtuuhommaan ja miettii, että toinen tuuma on keksittävä
metsän kuninkaan tappamiseksi. Senkin vuoksi on joku muutos
tarpeen, koska kovin paljon aikaa menee kahdessa eri paikassa joka
yö vahtia pitää. Siinähän menee kahdelta mieheltä aika melkein
kokonaan, niin että peltotyöt hyvin huonosti edistyvät. Mutta
mikähän tuuma se keksittäisiin? Kun vaan olisi hyvä karhukoira, niin
sittenhän ei olisi muuta ajattelemista kuin heti ruveta karhua
metsästämään. Vaan mistäpä se semmoinen koira saadaan!
Mietteissään istuu isäntä penkillä akkunan kohdalla, polttaen pitkiä
lehtiä. Vasta on hän, samoin kuin muu talonväki, einepöydän äärestä
noussut, mutta Tiina on kuitenkin aamusta asti karjan paimenena
metsää kierrellyt.
"Minä tässä ajattelen", sanoo isäntä, hetken äänettömyyden
kuluttua, kun Mäntyvaaran väestä kaikki muut paitsi Tiina istuvat
koolla pirtissä, pitäen loma-aikaa, ennenkuin leikkuutyöhön lähtevät.
"Minä ajattelen, että kyllä jo heitän sikseen kaikki yövahtuut minun
osaltani."
"No, joko rupeaa kyllästyttämään?" kysyy Kaisu.
"Eipä paljon muutenkaan. Ei se teho kuitenkaan minun pyssyni."
"Vai ei teho. Niinkö siis todella luulette, että se on pilattu?"
"No, niinpä uskon. Olisihan se muuten tappanut, kun viime yönä
metsän kuningasta ammuin, ell'ei se olisi ollut pilattu."
"Mitenpä se olisi tappanut, kun ei sattunut hyvään paikkaan!"
"Sattunut! Ihan vissiin sattui, vaan eihän se tappanut, kun
pyssyssä oli vika. — Mutta minä rupean tässä toista tuumaa
miettimään."
"Mikähän sinulla nyt on mielessä?" huudahtaa emäntä.
"Mitenkähän olisi loukas laittaa!"
"Loukas!" puuttuu puheeseen Lauri. "Eihän se aivan hullu tuuma
ole."
"Pistipä isällä hyvä ajatus päähän!" naurahtaa Kaisu. "Metsän
petoa ruvetaan pyytämään samalla lailla kuin hiirtä ansalla. Mutta
eiköhän mörkö paremmin osaa itseään varoa kuin hiiri!"
"Kyllä se sekin joskus saattaa erehtyä, vaikka sillä on miehen
mieli", vastaa isäntä. "Ja erehtyyhän se ihminenkin. — Tietävätpähän
vanhat ihmiset mainita semmoisista tapauksista, että metsän
kuningas on loukkaassa surmansa saanut. Muistanpa minäkin, että
minun lapsena ollessani täällä kotonani — juuri tässä talossa —
vietettiin mesikämmenen peijaita, ja se oli loukkaassa kuollut."
"Tuohan Vanhalan Matti", saapi sanoakseen Mikko, joka äänetönnä
on istunut lavitsalla, muista vähän syrjällä, "joka on tunnettu karhun
tappaja, kuuluu saaneen joskus loukkaallakin metsän pedon
hengiltä."
"Onhan se saanut", sanoo Lauri, "puheitten mukaan. Ja kyllä on
meidän tehtävä se loukas. Tulisihan se ansaksi sekin ja saattaisi kyllä
metsän kuninkaalta hengen ottaa, kun se vaan sattuisi sinne
menemään."
"Siinäpä se", sanoo Kaisu. "Mutta kyllä se ei sinne mene niin
kauan kuin sillä on vielä ne lehmäin raadot syömättä."
"Kyllä se silti saattaa mennä", väittää Lauri, "kun pannaan sille
oikein hyvä syötti; enkä minä vielä vahtuuta heitä."
"Tehkäähän loukas!" kehoittaa Anni. "Ehkäpä sattuisi sitten pyynti
paremmin onnistumaan."
"Mutta oletteko isä koskaan loukasta nähnyt?" kysyy Lauri.
"En minä kyllä nähnyt ole", vastaa isäntä, "vaan olen minä siitä
siksi paljon kuullut puhuttavan, jotta tiedän, minkälainen se on.
Vivusta en varmaan voisi sanoa, minkälainen se on. Mutta minä
ajattelen, että me otamme Vanhalan Matin neuvojaksi ja vivun
laittajaksi."
"Se kyllä käypi laatuun. Mutta milloinka me rupeamme siihen
loukkaan tekoon."
"No, laitetaan heti sana Vanhalaan, niin pääsemme työhön käsiksi
niin pian kuin Matti tänne ehtii, ehkä huomenna. — Mutta nyt
lähtekäämme leikkuuta jatkamaan!"
Anni lähtee Vanhalaan sanaa viemään ja toiset hankkiutuvat
pellolle lähtemään. Lauri ja isäntä sekä Kaisu lähtevät edeltä, vaan
Mikko jo heidän mentyään rupeaa hitaasti pellolle päin astumaan.
Emännällä on nyt muuta tekemistä, jottei hän jouda leikkuutyöhön.
Tuskin ovat leikkuumiehet saaneet ohraa leikatuksi yhdeksi
kuhilaaksi asti, ja Mikko vasta saanut sirpin käteensä, kun Tiina
hengästyneenä saapuu pellolle ja jo kaukaa huutaa: "Joutukaa
apuun! Mörkö viepi vasikan."
"Mitä ihmettä!" kurmnailee isäntä ja heittää leikkuun.
"Mitä sinä puhut!" ihmettelee Laurikin. "Onko se tosi?"
"No, tosi se on", vastaa Tiina läähättäen ja jo likelle ehdittyään.
"Tuolla vaaran rinteellä kun karja oli, niin yht'äkkiä, aivan
aavistamattani, mörkö sieppasi vasikan."
"Miks'et säikytellyt sitä petoa?" kysyy Kaisu.
"Enhän minä kerennyt ja minkäpä olisin sille tehnyt! — Mutta
joutukaa pian apuun. Mörkö syöpi Mielikin! Eikö lie jo syönytkin!"
Mutta Lauri lähtee heti pirttiin juoksemaan ja hänen jälissään
isäntä, ja sieltä he heti sieppaavat pyssynsä ja pikimmältään sanoen
emännälle, että mörkö vei vasikan, he ryntäävät taas ulos, Lauri
edellä, isäntä jälessä, ja emäntä jääpi kummissaan seisomaan ja
toisten kiirettä lähtöä katselemaan.
Tiina viittaa miehille suunnan, missä vasikka oli ollut ja sinne
rientävät nyt miehet ja heidän jälessään juosta hilkkasee Kaisu ja
takimmaisena Tiina, vielä läähättäen äskösestä juoksustaan. Mikko
astuu hiljokselleen heidän jälissään pyörtänöä pitkin pellon aidalle
asti, ja sinne hän jääpi seisomaan, katsellen, kuinka kauas ne
juoksevat. Kartanolla seisoo emäntä katselemassa hänkin ja hän
pahoilee mielessään, kun taas vahinko tapahtui karjalle.
Kun miehet ja Kaisu sekä Tiina, jotka yhä vaan juoksevat heidän
perässään, ehtivät mäkirinteelle sille paikalle, josta vasikka oli
kadonnut, niin siellä likellä karja ammoilee kovasti ja näyttää
peloissaan olevan. Sen joukossa ei tosiaan enää näy kadonnutta
vasikka. Tiina selittää, missä kohti se oli ollut ja minnekkä päin hän
luulee mörön sen vieneen. Miehet ajatellen, jotta katosikohan tuo
nyt koppinaan, lähtevät metsään rientämään. Siellä he
juoksentelevat ja katselevat, jotta eikö satu näkymään joko mörköä
tai vasikkaa. Vaimoset eivät lähde heitä hyvin kauas seuraamaan,
vaan katseltuaan ja kuunneltuaan likitienoilta, he palaavat takaisin.
Lauri ja isäntä sillä aikaa koettavat löytää karhun jälille, vaan
turhaan. Karhusta ei näy jälkeäkään missään, eikä vasikan
ammontaa kuulu missään. Hetken aikaa haettuaan, haettavaansa
löytämättä, he palaavat takaisin ja asettavat pyssynsä paikoilleen
pirtin seinälle.
Pirtissä ovat nyt kaikki Mäntyvaaran asujat, paitsi Anni, koolla.
Vähää ennen miesten tuloa olivat Kaisu ja Tiina sinne tulleet ja
emäntä heiltä tarkkaan kyseli siitä vasikan katoamisesta. Nyt ei
malta Mikkokaan olla poissa muitten joukosta, vaan lähtee hänkin
kuulemaan toisten puheita.
"No, eikö löytynyt?" kysyy emäntä heti miesten sisään astuttua.
"Eipä", vastaa isäntä ja istahtaa penkille. "Se katosi, se vasikka,
kerrassaan, nahkoineen kaikkineen."
"No, katosi se", vakuuttaa Lauri, hänkin istumapaikan itselleen
valiten. "Ei kuulunut siitä niin ääntäkään, ja metsän kuningas oli siksi
viisas, ett'ei pannut puumerkkiään siihen, mistä oli kulkenut."
"No, kyllä se pahuus oli sukkela menemään. Kumma oli, mitenkä
se pääsi jättämään, vaikka sillä oli elukka kannettavana. Miten tuo
lieneekin sitä kantanut, vaan ei siltä kulku kuitenkaan hidastunut,
koskapahan emme tavottaneet."
"No, oli se tapausta!" lausuu kummissaan emäntä.
"Kyllä se oli soma tapaus", päivittelee Tiina. "En tuota ennakolta
osannut aavistaa."
"Kukapa sitä osasi aavistaa!" sanoo isäntäkin.
"Se vasta kummaa oli minusta", puuttuu keskusteluun Mikko, "että
se uskalsi ihan paimenen nähden vasikkaan kajota. Enpä ole
sattunut kuulemaan, että se koskaan ennen olisi niin tehnyt."
"Kyllä oli tapausta tämä", pahoilee yhä emäntä. "Ja kovinhan se
tuntuu ikävältä, kun ei karja enää säily paimenenkaan turvissa."
"Olihan se ikävä asia", myöntää isäntä, "että joutui Mielikki metsän
saaliiksi, ja kyllä mörkö on sen jo niin hyvään paikkaan kätkenyt tai
jo syönyt sen suuhunsa nahkoilleen kaikkineen, ett'ei sitä voida enää
löytää mistään. Mutta ei tälle asialle enää voida mitään. Se oli niin
sallittu ja sen vuoksi se tapahtui. — Näet nyt Kaisu", sanoo hän
sitten Kaisun puoleen kääntyen, "ett'ei ole paimenestakaan apua
karjalle."
"Kyllä siitä on apua", puolustelee Kaisu itseään. "Mutta Tiina ei
ollut oikein valpas ja tarkkaavainen."
"Minäkö!" huudahtaa Tiina. "Teinhän minä kaikkea mitä voin."
"Olisit huutanut ja säikytellyt sitä petoa, kun se rupesi karjaa
hätyyttämään."
"Enhän minä kerennyt havaitakaan sitä ennenkuin sillä jo oli
vasikka kynsissä. Enhän silloin voinut sille mitään eikä olisi
toinenkaan minun sijassani mitään saattanut tehdä."
"Eihän tämä asia ole Tiinan syy", sanoo isäntä. "Se kun oli kerta
määrätty tapahtuvaksi, niin sen täytyi tapahtua, eikä siihen paimen
mitään voinut. Eihän kukaan voi sallimukselle mitään."
"No, en tiedä", väittää Kaisu. "Mutta kyllä en minä Tiinan sijassa
olisi yhtään elukkaa karjasta päästänyt metsän kynsiin."
"Oleppa sanomatta!" vastustaa Tiina, "Kun olisit ollut minun
sijassani, niin et olisi kerennyt mitään ajatellakaan, ennenkuin jo
metsä vasikan kanssa olisi ollut kaukana näkymättömissä."
"Älähän! Ei olisi metsä tullut likellenikään, kun minä olisin aina
huutanut tai laulellut."
"No, mitä tuossa tyhjää intätte!" virkkoo isäntä. "Tämä asia ei
kuitenkaan muutu. Se tapahtui niinkuin oli sallittu."
"Niin", myöntää emäntä. "Tulihan tosin vahinko, vaan minkäpä sille
tekee! Se oli sallittu. Mutta, Tiina, saat sinä vielä mennä paimeneksi;
sillä karja peloissaan ammoilee tuolla vaaran rinteellä, eikä uskalla
mihinkään liikkua paimenetta."
"Tosiaan", sanoo isäntäkin, "saapi karjalla olla paimen sen vuoksi,
että karja paremmin uskaltaisi kulkea ruokaisemmilla paikoilla, mutta
ei suinkaan sen vuoksi, että paimenesta olisi mitään apua karjalle
mörköä vastaan."
"Saisihan tuonne mennä paimeneksi", sanoo Tiina, "mutta jos se
mörkö vielä päälle tulee."
"Siitä ei ole pelkoa", keskeyttää isäntä Tiinan puhetta. "Harvoinpa
se ihmisen päälle tulee."
"Entäpä jos nyt tulisi, koska se on jo niin rohkeaksi tullut, että
uskaltaa karjaan kajota paimenen nähden."
"Ole huoleti! Sinun päällesi se ei tule, kun et sinä voi sitä millään
aseella uhata. Menehän nyt! Me muut täältä lähdemme taas
leikkaamaan, — ja huomenna rupeamme loukkaan tekoon, jotta eikö
sattuisi mörkö sinne menemään ja siellä surmansa saamaan."
Niin poistuu kukin töihinsä, mielessään usein ajatellen karhujuttua.
Pienokaiset vaan, mistään huolehtimatta, leikkivät iloisina kartanon
hietikolla.
XII.
Seuraavan päivän aamulla Mäntyvaaran isäntä, Lauri sekä Vanhalan
Matti lähtevät loukkaan tekoon. He astuvat karhun vahtuun vuoksi jo
usein kulettuja seutuja, ensin rantatietä myöten ja kääntyvät sitten
vasemmalle ja kulkevat tiheän metsikön kautta sitä suuntaa kohti,
missä haaskat ovat. Etummaisena astuu Lauri, sitten isäntä ja
takimmaisena Matti. Enimmästä keskustelutta kuluu matka ja
varsinkin Matti, joka on harvapuheinen, jäykkäluontoinen vanhus, ei
monta sanaa sano.
Miehet valitsevat metsässä paikan likelle niitä seutuja, missä
lehmäin raadot ovat, vaan vähän ylemmäksi, kuivemmalle maalle.
Siellä he rupeavat puita jystämään ja hakkaavat sylen pituisia hirtten
tapaisia palkkeja joko kasvavista puista tai osaksi myös siellä täällä
olevista kaatuneista hongista. Isännän ja Laurin kirveet enite jälkeä
tekevät ja Matti vaan tekee pienempiä veistotöitä sekä antaa toisille
tarvittaessa neuvoja ja auttaa heitä isompia puita kuljetettaessa.
Kuuluu nyt kirveitten kalketta ja puitten pauketta palkkeja tehdessä;
sillä semmoisessa työssä ei jyskettä saateta välttää; ja metsän
kuningas, jos vaan mailla lienee, saapi kummissaan kuunnella ja
ajatella, jotta mikä se nyt semmoista jytäkkää pitää sen ennen
rauhaisan ruokapaikan läheisyydessä. Kuluu aikaa melkonen palkkeja
tehdessä, niitä kun tarvitaan koko joukko, vaan kun arvellaan niiden
riittävän, ruvetaan niistä loukkaalle seiniä tekemään. Ne ladotaan
pystyyn maata vasten ihan toistensa viereen kolmeksi seinäksi eli
sivuksi, niin että kaksi seinää tulee yhtäsuuntaisiksi toistensa kanssa
ja kolmas yhdistää niiden päät toisiinsa, vaan yksi sivu jääpi siis
avoimeksi. Tälle neljännelle sivulle vedetään iso kokonainen hirsi ja
asetetaan maata pitkin ikäänkuin kynnykseksi loukkaalle, niin että
tyvipuoli koskettaa molempia yhtäsuuntaisia seiniä, vaan latvapuoli
ulottuu kauas niiden ulkopuolelle. Vielä tarvitaan tätä loukkaan
etusivua varten hirsi tai kaksi; mutta, ennenkuin ne hakataan ja
tuodaan määräpaikkoihinsa, on Matti ukko ruvennut vivun tekoon.
Hän veistelee kaikenlaisia palukoita, jotka tarvitaan vipua varten, ja
on työhönsä niin kiintynyt, ett'ei paljon jouda ympärilleen silmäellä
eikä sekaantua isännän ja Laurin puheisiin. Nämä kun tuumaavat ja
miettivät, mitenkä mikin on tehtävä, niin ukko vaan äänetönnä
työtään toimittaa, eikä hän muulloin kuin toisten jotain kysyessä
lyhyesti jonkun sanan vastaukseksi ärähtää, ja vaikka hän näkee,
ett'eivät aina älyä, mitä varten hän mitäkin tekee, niin ei hän
kuitenkaan ennen aikojaan selityksiin rupea; hän olla jöröttää vaan
vakavana ja totisena ja tekee työnsä varmana kuin kokenut mestari
ainakin.
Matin veistäessä ja vuollessa vipulaitokseen tarvittavia kaluja, ovat
isäntä ja Lauri puuhassa isoa hirttä valmistaessaan. Kun se on valmis
kuljetettavaksi, tuumaa isäntä Laurille, hirttä kohottaessaan: "Tuskin
tämä kahden miehen saadaankaan paikoilleen."
"Näkyy tässä painoa olevan", vastaa Lauri, hänkin hirttä
kohottaessaan.
"Raskas tämä raato on", huutaa isäntä Matille. "Etköhän Matti
tulisi avustamaan!"
"Vai raskaalta tuntuu", vastaa Matti. "No, minä tulen täältä heti."
Kolmen miehen vedetään sitten hirsi loukkaan eteen ja siinä
kantajat eli vetäjät heittävät taakan käsistään ja niin pudota
romahtaa hirsi maahan toisen viereen. Siihen se sitten jätetään
vähäksi aikaa, ennenkuin se nostetaan siihen paikkaan, mihin se on
pantava.
Ennenkuin nyt isäntä ja Lauri muihin töihin rupeavat, käyvät he
toisen haaskan purkamassa ja tuovat sitten koko haisevan
lehmänraadon loukkaan lähelle, jotta Matti saisi siitä syöttiä ottaa
loukkaaseen karhua varten pantavaksi.
Matilla alkaa nyt vipulaitos olla lopulleen valmis. Loukkaan sisälle
peräseinään on hän kiinnittänyt puukoukun, johon syötti tulee
pantavaksi, ja siitä johtuu vipu etusivulle, siinä olevan hirren
tyvipuolen kohdalle. Kun lehmän raato on tuotu siihen likelle, niin
Matti leikkaa raadosta pään erilleen, jonka hän vielä halkaisee ja
panee sitten toisen puoliskon, johon myös kieli on jäänyt,
puukoukkuun. Isännälle ja Laurille, jotka katselevat hänen
hommaansa, sanoo hän: "Päällystäkäähän loukas kokonaan havuilla
ja katsokaa, että joka paikka tulee niin hyvin peitetyksi, ett'ei vieras
katsoja voi ollenkaan tietää niiden peitossa minkään rakennuksen
olevan!"
Niin ruvetaankin loukasta havuilla peittämään ja sillä aikaa Matti
lehmän raatoa silpoilee sekä syytää siitä palan palan perästä
loukkaan sisälle ja etupuolellekin. Ne ovat sitä varten, että karhu, jos
se kerta sille mieluisesta hajusta vieteltynä tulisi loukkaalle, rupeaisi
nuuskimaan ja syömään siellä täällä olevia paloja, joista se pääsisi
hyvään makuun, eikä sitten malttaisi olla syömättä syöttiä
puukoukusta.
Vihdoin, kun loukas on kokonaan havuilla peitetty, niin että se on
aivan kuin havumaja, viritetään vipu. Se hirsi, joka äsken tuotiin,
nostetaan toisen hirren päälle, joka oli pantu loukkaalle kynnykseksi,
siten että latvat tulevat päällekkäin, vaan ylemmäisen hirren tyvipuoli
kohotetaan, joten aukko tulee hirtten väliin, ja tähän väliin asettaa
nyt Matti kepin oli palukan pystyyn päällimmäistä hirttä
kannattamaan. Tämä palukka on yhteydessä vipulaitoksen kanssa,
joka on sillä lailla laitettu, että, jos se sattuu liikahtamaan, silloin heti
hirttä kannattava palukka kaatuu ja samalla hirsi alas romahtaa.
Kun nyt loukas on valmis ja vipu viritetty, tuumaa isäntä, loukasta
ja vipua katsellen: "Tämmöinen se nyt tuli ansa metsän kuninkaalle.
Nyt ei puutu muuta kuin että se metsän peto tulisi tähän ansaan,
niin sittenhän ne tulisivat jo vaivat palkituiksi."
"Ka, sehän tässä on toivottava", vastaa Lauri, hänkin vipulaitosta
tarkkaan katsoen. "On tämä somanen laitos, ja tässä se salojen eläjä
pian saattaa surmansa saada."
"Hetihän sen täytyy henkensä heittää, kun se tulee tuohon syöttiin
koskemaan."
"Niin, ensin se tästä ulkopuolelta syöpi mitä löytää ja tuolta sisältä
se tietysti myöskin rupeaa lihapalasia maistelemaan, pistäen
turpansa tästä välistä tuonne sille. No, sitten sillä tekee mieli tuota
pään puoliskoa tuolta puukoukusta. Mutta sinne ei sen kuono
uletukaan."
"Silloin se toisella jalallaan astuu tästä alushirren yli ja nyt se
saattaa suullaan koskettaa syöttiä."
"Vaan kun syötti on lujasti kiinni sidottu, niin se rupeaa sitä
retuuttamaan, irti saadakseen."
"Mutta eipä irtaukaan syötti helposti; se näkyy hyvin lujaan olevan
nuoralla sidottu."
"Ja kun se sitä retuuttaa, niin silloin puukoukku liikahtaa ja vipu
laukeaa. Tämä palukka tässä paikoiltaan solahtaa ja samalla tämä
vankka hirsi mörön niskaan pudota romahtaa."
"No, se vasta rymäystä on!"
"Ka, siinä tulee semmoinen paino mörkö paran päälle, jotta —"
"Heh! Paikallahan se kuoliaaksi litistyy."
"Ei auta sillä voimain ponnistukset enää."
"Ka, hetihän tuommoinen paino siltä hengen viepi."
"Se on tietty", puuttuu puheeseen Matti. "Sen päälle tulee niin
raskas paino, ett'ei se ennätä parahtaakaan. — Mutta hyvä on
kuitenkin, että pannaan paljon painoa. Otetaanpa tuolta viellä tuo
vanha hirsiremu, joka tuossa likellä näkyy, ja pannaan se
lisäpainoksi!"
"No, so kun vielä pannaan", sanoo isäntä, "niin kyllä sitten —."
"Kyllä sitten jo tulee painoa", lausuu Lauri.
Tuodaan sitten se vanha jo melkein lahonnut hirsi ja nostetaan
sekä kiinnitetään lisäpainoksi painohirren päälle.
Sittenpä se loukas vihdoin saadaan semmoisekseen jättää. Mutta
Matin palasiksi silpoma lehmän raato on johonkin korjattava.
"Mihinkä ne nämä pannaan?" kyselee Lauri raadon paloja
kosketellen.
"Eihän näitä metsälle suinkaan syötäviksi jätetä?"
"Ei toki", vastaa Matti. "Kyllä ne pois korjataan."
"Poishan ne ovat korjattavat", sanoo isäntäkin. "Maahan niitä olisi
hyvä kätkeä, mutta sanotaanpa metsän niitä ylös kaivavan."
"Ei niitä maahan panna", sanoo Matti. "Sieltä kyllä metsä ne pian
ylös kaivaa."
"No, puuhun ne vissiin pannaan", sanoo Lauri. "Mutta kyllähän se
mörkö ne sieltäkin saattaa saada."
"Pääseehän se puuhun kyllä vähän matkaa", myöntää Matti. "Vaan
kun ne viedään korkealle ylemmille oksille, niin kyllä pysyvät siellä."
"Niinpä luulisi", arvelee isäntäkin.
Kun sitten lehmän raadon palaset ovat ripustetut läheisten puitten
oksille niin korkealle kuin mahdollista sekä loukkaan teossa
syntyneet lastut huolellisesti havuilla peitetyt, niin miehet,
tyytyväisinä työnsä päättymisestä, lähtevät kotia päin astumaan.
Peräkkäin he astuvat taas, samassa järjestyksessä kuin olivat
tulleetkin, mutta nyt he ovat iloisemmalla mielellä, isäntä varsinkin,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
CORS in Action Creating and consuming cross origin APIs 1st Edition Monsur Ho...
PDF
Designing Evolvable Web APIs with ASP NET 1st Edition Glenn Block
PDF
DevOps with OpenShift 1st Edition Mike Hepburn
PDF
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind
PDF
Spring Start Here Learn what you need and learn it well 1st Edition Laurentiu...
PDF
VoIP Handbook Applications Technologies Reliability and Security 1st Edition ...
PDF
Programming Wcf Services 4th Edition Juval Lwy Michael Montgomery
PDF
Programming Wcf Services 4th Edition Juval Lwy Michael Montgomery
CORS in Action Creating and consuming cross origin APIs 1st Edition Monsur Ho...
Designing Evolvable Web APIs with ASP NET 1st Edition Glenn Block
DevOps with OpenShift 1st Edition Mike Hepburn
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind
Spring Start Here Learn what you need and learn it well 1st Edition Laurentiu...
VoIP Handbook Applications Technologies Reliability and Security 1st Edition ...
Programming Wcf Services 4th Edition Juval Lwy Michael Montgomery
Programming Wcf Services 4th Edition Juval Lwy Michael Montgomery

Similar to Microservice Apis Using Python Flask Fastapi Openapi And More 1st Edition Jos Haro Peralta (20)

PDF
Blockchain in Action 1st Edition Bina Ramamurthy
PDF
Building Microservices With Net Core Converted Soumya Mukherjee
PDF
Kubernetes Operators 1st Edition Jason Dobies
PDF
Erlang and OTP in Action 1st Edition Martin Logan
PDF
Mastering Javascript Design Patterns 2nd Edition Timms Simon
PDF
Complete Download (Ebook) Software Telemetry by Jamie Riedesel ISBN 978161729...
PDF
Aurelia In Action 1 Converted Sean Hunter
PDF
Embedded Networking with CAN and CANopen Pfeiffer
PDF
Kubernetes Operators 1st Edition Jason Dobies
PDF
Windows Phone 7 Developer Guide Building Connected Mobile Applications With M...
PDF
ASP NET Professional Projects 1st Edition Hersh Bhasin
PDF
Containerizing Continuous Delivery in Java 1st Edition Daniel Bryant
PDF
Download Full Ajax in Action 1st Edition Dave Crane PDF All Chapters
PDF
Web Mapping Illustrated Using Open Source Gis Toolkits 1st Edition Tyler Mitc...
PDF
Azure Storage Streaming And Batch Analytics A Guide For Data Engineers 1st Ed...
PDF
Angularjs Up And Running Enhanced Productivity With Structured Web Apps 1st E...
PDF
WPF in Action with Visual Studio 2008 1st Edition Arlen Feldman
PDF
Test Driven Practical TDD and Acceptance TDD for Java Developers 1st Edition ...
PDF
Civic Apps Competition Handbook 1st Edition Kate Eyler-Werve
PDF
Professional Sql Server 2008 Administration With Windows Powershell 1st Editi...
Blockchain in Action 1st Edition Bina Ramamurthy
Building Microservices With Net Core Converted Soumya Mukherjee
Kubernetes Operators 1st Edition Jason Dobies
Erlang and OTP in Action 1st Edition Martin Logan
Mastering Javascript Design Patterns 2nd Edition Timms Simon
Complete Download (Ebook) Software Telemetry by Jamie Riedesel ISBN 978161729...
Aurelia In Action 1 Converted Sean Hunter
Embedded Networking with CAN and CANopen Pfeiffer
Kubernetes Operators 1st Edition Jason Dobies
Windows Phone 7 Developer Guide Building Connected Mobile Applications With M...
ASP NET Professional Projects 1st Edition Hersh Bhasin
Containerizing Continuous Delivery in Java 1st Edition Daniel Bryant
Download Full Ajax in Action 1st Edition Dave Crane PDF All Chapters
Web Mapping Illustrated Using Open Source Gis Toolkits 1st Edition Tyler Mitc...
Azure Storage Streaming And Batch Analytics A Guide For Data Engineers 1st Ed...
Angularjs Up And Running Enhanced Productivity With Structured Web Apps 1st E...
WPF in Action with Visual Studio 2008 1st Edition Arlen Feldman
Test Driven Practical TDD and Acceptance TDD for Java Developers 1st Edition ...
Civic Apps Competition Handbook 1st Edition Kate Eyler-Werve
Professional Sql Server 2008 Administration With Windows Powershell 1st Editi...
Ad

Microservice Apis Using Python Flask Fastapi Openapi And More 1st Edition Jos Haro Peralta

  • 1. Microservice Apis Using Python Flask Fastapi Openapi And More 1st Edition Jos Haro Peralta download https://ebookbell.com/product/microservice-apis-using-python- flask-fastapi-openapi-and-more-1st-edition-jos-haro- peralta-47399612 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Microservices In Sap Hana Xsa A Guide To Rest Apis Using Nodejs 1st Edition Sergio Guerrero https://ebookbell.com/product/microservices-in-sap-hana-xsa-a-guide- to-rest-apis-using-nodejs-1st-edition-sergio-guerrero-11396532 Go Programming Cookbook Over 75 Recipes To Program Microservices Networking Database And Apis Using Golang Ian Taylor https://ebookbell.com/product/go-programming-cookbook-over-75-recipes- to-program-microservices-networking-database-and-apis-using-golang- ian-taylor-55484320 Effortless Cloudnative Apps Development Using Skaffold Simplify The Development And Deployment Of Cloudnative Spring Boot Microservices On Kubernetes With Skaffold Ashish Choudhary https://ebookbell.com/product/effortless-cloudnative-apps-development- using-skaffold-simplify-the-development-and-deployment-of-cloudnative- spring-boot-microservices-on-kubernetes-with-skaffold-ashish- choudhary-57415862 Microservices Communication In Net Using Grpc A Practical Guide For Net Developers To Build Efficient Communication Mechanism For Distributed Apps Fiodar Sazanavets https://ebookbell.com/product/microservices-communication-in-net- using-grpc-a-practical-guide-for-net-developers-to-build-efficient- communication-mechanism-for-distributed-apps-fiodar- sazanavets-38379570
  • 3. Implementing Eventdriven Microservices Architecture In Net 7 Develop Eventbased Distributed Apps That Can Scale With Everchanging Business Demands Using C 11 And Net 7 1st Edition Joshua Garverick https://ebookbell.com/product/implementing-eventdriven-microservices- architecture-in-net-7-develop-eventbased-distributed-apps-that-can- scale-with-everchanging-business-demands-using-c-11-and-net-7-1st- edition-joshua-garverick-48224172 Principles Of Web Api Design Delivering Value With Apis And Microservices Final Release 1st Edition James Higginbotham https://ebookbell.com/product/principles-of-web-api-design-delivering- value-with-apis-and-microservices-final-release-1st-edition-james- higginbotham-36338630 Pro Restful Apis With Micronaut Build Javabased Microservices With Rest Json And Xml 2nd Edition 2nd Sanjay Patni https://ebookbell.com/product/pro-restful-apis-with-micronaut-build- javabased-microservices-with-rest-json-and-xml-2nd-edition-2nd-sanjay- patni-48103874 Pro Restful Apis With Micronaut Build Javabased Microservices With Rest Json And Xml 2 Converted Sanjay Patni https://ebookbell.com/product/pro-restful-apis-with-micronaut-build- javabased-microservices-with-rest-json-and-xml-2-converted-sanjay- patni-53591534 Pro Restful Apis With Micronaut Build Javabased Microservices With Rest Json And Xml Sanjay Patni https://ebookbell.com/product/pro-restful-apis-with-micronaut-build- javabased-microservices-with-rest-json-and-xml-sanjay-patni-232237072
  • 5. M A N N I N G José Haro Peralta Using Python, Flask, FastAPI, OpenAPI and more
  • 6. Documentation-driven development is an API-first development method in which you design and document the API first; then, you build the API server and the API client against the documentation; and finally, you use the API documentation to validate the server and client implementations. Documentation-driven development helps you reduce the chances of API integration failure, and it gives you more control and visibility of integration errors. 3. Test the implementation against the specification. API specification API server developers API client developers 1. API design and documentation 2. Build the client and the server against the API documentation. REST APIs are structured around endpoints. We distinguish between singleton endpoints, such as GET /orders/8, and collection endpoints, such as GET /orders. REST APIs leverage the semantics of HTTP methods to indicate actions (such as POST to create resources), and they use HTTP status codes that signal the result of processing the request (such as 200 for successful responses). Singleton endpoints PUT /orders/8 {payload} DELETE /orders/8 Update an order Delete an order Status code: 200 {payload} Status code: 204 HTTP equests r HTTP esponses r POST /orders/8/pay {payload} POST /orders/8/cancel {payload} Pay for an order Cancel an order Status code: 200 {payload} Status code: 200 {payload} Collection endpoints POST /orders {payload} Place an order Status code: 201 {payload} GET /orders Get a collection of orders Status code: 200 {payload} GET /orders/8 Retrieve an order Status code: 200 {payload} Singleton endpoints Orders service API lient c
  • 9. Microservice APIs USING PYTHON, FLASK, FASTAPI, OPENAPI AND MORE JOSÉ HARO PERALTA M A N N I N G SHELTER ISLAND
  • 10. For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2023 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Marina Michaels 20 Baldwin Road Technical development editor: Nick Watts PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Andy Marinkovich Copy editor: Michele Mitchell Proofreader: Katie Tennant Technical proofreader: Al Krinker Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617298417 Printed in the United States of America
  • 11. To Jiwon, without whose constant support and encouragement I wouldn’t have been able to write this book, and to Ivy, that boundless spark of joy that makes everything I do worth it.
  • 13. vii brief contents PART 1 INTRODUCING MICROSERVICE APIS...............................1 1 ■ What are microservice APIs? 3 2 ■ A basic API implementation 20 3 ■ Designing microservices 45 PART 2 DESIGNING AND BUILDING REST APIS ........................59 4 ■ Principles of REST API design 61 5 ■ Documenting REST APIs with OpenAPI 90 6 ■ Building REST APIs with Python 110 7 ■ Service implementation patterns for microservices 144 PART 3 DESIGNING AND BUILDING GRAPHQL APIS ...............183 8 ■ Designing GraphQL APIs 185 9 ■ Consuming GraphQL APIs 210 10 ■ Building GraphQL APIs with Python 233
  • 14. BRIEF CONTENTS viii PART 4 SECURING, TESTING, AND DEPLOYING MICROSERVICE APIS ..................................................267 11 ■ API authorization and authentication 269 12 ■ Testing and validating APIs 302 13 ■ Dockerizing microservice APIs 331 14 ■ Deploying microservice APIs with Kubernetes 342
  • 15. ix contents preface xvi acknowledgments xviii about this book xx about the author xxv about the cover illustration xxvi PART 1 INTRODUCING MICROSERVICE APIS.....................1 1 What are microservice APIs? 3 1.1 What are microservices? 4 Defining microservices 4 ■ Microservices vs. monoliths 5 Microservices today and how we got here 7 1.2 What are web APIs? 8 What is an API? 8 ■ What is a web API? 9 ■ How do APIs help us drive microservices integrations? 9 1.3 Challenges of microservices architecture 11 Effective service decomposition 11 ■ Microservices integration tests 12 ■ Handling service unavailability 12 ■ Tracing distributed transactions 13 ■ Increased operational complexity and infrastructure overhead 14 1.4 Introducing documentation-driven development 15
  • 16. CONTENTS x 1.5 Introducing the CoffeeMesh application 17 1.6 Who this book is for and what you will learn 17 2 A basic API implementation 20 2.1 Introducing the orders API specification 21 2.2 High-level architecture of the orders application 22 2.3 Implementing the API endpoints 23 2.4 Implementing data validation models with pydantic 30 2.5 Validating request payloads with pydantic 34 2.6 Marshalling and validating response payloads with pydantic 38 2.7 Adding an in-memory list of orders to the API 41 3 Designing microservices 45 3.1 Introducing CoffeeMesh 46 3.2 Microservices design principles 46 Database-per-service principle 46 ■ Loose coupling principle 48 Single Responsibility Principle 49 3.3 Service decomposition by business capability 49 Analyzing the business structure of CoffeeMesh 49 ■ Decomposing microservices by business capabilities 50 3.4 Service decomposition by subdomains 52 What is domain-driven design? 52 ■ Applying strategic analysis to CoffeeMesh 53 3.5 Decomposition by business capability vs. decomposition by subdomain 57 PART 2 DESIGNING AND BUILDING REST APIS ..............59 4 Principles of REST API design 61 4.1 What is REST? 62 4.2 Architectural constraints of REST applications 63 Separation of concerns: The client-server architecture principle 64 Make it scalable: The statelessness principle 64 ■ Optimize for performance: The cacheability principle 65 ■ Make it simple for the client: The layered system principle 66 ■ Extendable interfaces: The code-on-demand principle 66 ■ Keep it consistent: The uniform interface principle 67
  • 17. CONTENTS xi 4.3 Hypermedia as the engine of application state 67 4.4 Analyzing the maturity of an API with the Richardson maturity model 70 Level 0: Web APIs à la RPC 71 ■ Level 1: Introducing the concept of resource 71 ■ Level 2: Using HTTP methods and status codes 72 ■ Level 3: API discoverability 72 4.5 Structured resource URLs with HTTP methods 73 4.6 Using HTTP status codes to create expressive HTTP responses 77 What are HTTP status codes? 77 ■ Using HTTP status codes to report client errors in the request 78 ■ Using HTTP status codes to report errors in the server 82 4.7 Designing API payloads 83 What are HTTP payloads, and when do we use them? 83 ■ HTTP payload design patterns 84 4.8 Designing URL query parameters 87 5 Documenting REST APIs with OpenAPI 90 5.1 Using JSON Schema to model data 91 5.2 Anatomy of an OpenAPI specification 95 5.3 Documenting the API endpoints 96 5.4 Documenting URL query parameters 97 5.5 Documenting request payloads 98 5.6 Refactoring schema definitions to avoid repetition 100 5.7 Documenting API responses 102 5.8 Creating generic responses 105 5.9 Defining the authentication scheme of the API 107 6 Building REST APIs with Python 110 6.1 Overview of the orders API 111 6.2 URL query parameters for the orders API 112 6.3 Validating payloads with unknown fields 115 6.4 Overriding FastAPI’s dynamically generated specification 118 6.5 Overview of the kitchen API 120 6.6 Introducing flask-smorest 122
  • 18. CONTENTS xii 6.7 Initializing the web application for the API 123 6.8 Implementing the API endpoints 125 6.9 Implementing payload validation models with marshmallow 129 6.10 Validating URL query parameters 133 6.11 Validating data before serializing the response 136 6.12 Implementing an in-memory list of schedules 140 6.13 Overriding flask-smorest’s dynamically generated API specification 142 7 Service implementation patterns for microservices 144 7.1 Hexagonal architectures for microservices 145 7.2 Setting up the environment and the project structure 148 7.3 Implementing the database models 149 7.4 Implementing the repository pattern for data access 155 The case for the repository pattern: What is it, and why is it useful? 155 ■ Implementing the repository pattern 157 7.5 Implementing the business layer 162 7.6 Implementing the unit of work pattern 172 7.7 Integrating the API layer and the service layer 177 PART 3 DESIGNING AND BUILDING GRAPHQL APIS......183 8 Designing GraphQL APIs 185 8.1 Introducing GraphQL 186 8.2 Introducing the products API 189 8.3 Introducing GraphQL’s type system 192 Creating property definitions with scalars 192 ■ Modeling resources with object types 193 ■ Creating custom scalars 194 8.4 Representing collections of items with lists 195 8.5 Think graphs: Building meaningful connections between object types 196 Connecting types through edge properties 196 ■ Creating connections with through types 198
  • 19. CONTENTS xiii 8.6 Combining different types through unions and interfaces 200 8.7 Constraining property values with enumerations 202 8.8 Defining queries to serve data from the API 203 8.9 Altering the state of the server with mutations 206 9 Consuming GraphQL APIs 210 9.1 Running a GraphQL mock server 211 9.2 Introducing GraphQL queries 214 Running simple queries 214 ■ Running queries with parameters 215 ■ Understanding query errors 215 9.3 Using fragments in queries 217 9.4 Running queries with input parameters 219 9.5 Navigating the API graph 219 9.6 Running multiple queries and query aliasing 221 Running multiple queries in the same request 221 ■ Aliasing our queries 222 9.7 Running GraphQL mutations 225 9.8 Running parameterized queries and mutations 226 9.9 Demystifying GraphQL queries 229 9.10 Calling a GraphQL API with Python code 230 10 Building GraphQL APIs with Python 233 10.1 Analyzing the API requirements 234 10.2 Introducing the tech stack 234 10.3 Introducing Ariadne 235 10.4 Implementing the products API 241 Laying out the project structure 241 ■ Creating an entry point for the GraphQL server 242 ■ Implementing query resolvers 243 Implementing type resolvers 246 ■ Handling query parameters 252 Implementing mutation resolvers 256 ■ Building resolvers for custom scalar types 258 ■ Implementing field resolvers 262
  • 20. CONTENTS xiv PART 4 SECURING, TESTING, AND DEPLOYING MICROSERVICE APIS ........................................267 11 API authorization and authentication 269 11.1 Setting up the environment for this chapter 270 11.2 Understanding authentication and authorization protocols 271 Understanding Open Authorization 271 ■ Understanding OpenID Connect 276 11.3 Working with JSON Web Tokens 278 Understanding the JWT header 279 ■ Understanding JWT claims 280 ■ Producing JWTs 282 ■ Inspecting JWTs 284 Validating JWTs 286 11.4 Adding authorization to the API server 287 Creating an authorization module 287 ■ Creating an authorization middleware 289 ■ Adding CORS middleware 292 11.5 Authorizing resource access 293 Updating the database to link users and orders 294 Restricting user access to their own resources 297 12 Testing and validating APIs 302 12.1 Setting up the environment for API testing 303 12.2 Testing REST APIs with Dredd 304 What is Dredd? 304 ■ Installing and running Dredd’s default test suite 305 ■ Customizing Dredd’s test suite with hooks 307 Using Dredd in your API testing strategy 315 12.3 Introduction to property-based testing 315 What is property-based testing? 315 ■ The traditional approach to API testing 316 ■ Property-based testing with Hypothesis 318 Using Hypothesis to test a REST API endpoint 319 12.4 Testing REST APIs with Schemathesis 322 Running Schemathesis’s default test suite 322 ■ Using links to enhance Schemathesis’ test suite 323 12.5 Testing GraphQL APIs 327 Testing GraphQL APIs with Schemathesis 327 12.6 Designing your API testing strategy 329
  • 21. CONTENTS xv 13 Dockerizing microservice APIs 331 13.1 Setting up the environment for this chapter 332 13.2 Dockerizing a microservice 333 13.3 Running applications with Docker Compose 338 13.4 Publishing Docker builds to a container registry 340 14 Deploying microservice APIs with Kubernetes 342 14.1 Setting up the environment for this chapter 343 14.2 How Kubernetes works: The “CliffsNotes” version 344 14.3 Creating a Kubernetes cluster with EKS 346 14.4 Using IAM roles for Kubernetes service accounts 350 14.5 Deploying a Kubernetes load balancer 351 14.6 Deploying microservices to the Kubernetes cluster 353 Creating a deployment object 354 ■ Creating a service object 357 Exposing services with ingress objects 359 14.7 Setting up a serverless database with AWS Aurora 361 Creating an Aurora Serverless database 361 ■ Managing secrets in Kubernetes 364 ■ Running the database migrations and connecting our service to the database 367 14.8 Updating the OpenAPI specification with the ALB’s hostname 370 14.9 Deleting the Kubernetes cluster 372 appendix A Types of web APIs and protocols 376 appendix B Managing an API’s life cycle 387 appendix C API authorization using an identity provider 391 index 403
  • 22. xvi preface APIs and microservices have taken the software industry by storm. Under the pressure of increasing software complexity and the need to scale, more and more organizations are migrating from monolithic to microservices architecture. O’Reilly’s “Microservices Adoption in 2020” report found that 77% of respondents had adopted microservices, a trend that is expected to continue growing in the coming years. Using microservices poses the challenge of driving service integrations through APIs. According to Nordic APIs, 90% of developers work with APIs and they spend 30% of their time building APIs.1 The growth of the API economy has transformed the way we build applications. Today, it’s more and more common to build products and services that are delivered entirely over APIs, such as Twilio and Stripe. Even tradi- tional sectors like banking and insurance are finding new lines of business by opening their APIs and integrating within the Open Banking ecosystem. The wide availability of API-first products means that we can focus on our core business capabilities when building our own applications, while using external APIs to handle common tasks such as authenticating users and sending emails. It’s exciting to be part of this growing ecosystem. However, before we embrace microservices and APIs, we need to know how to architect microservices, how to design APIs, how to define an API strategy, how to make sure we deliver reliable inte- grations, how to choose a deployment model, and how to protect our systems. In my 1 J. Simpson, “20 Impressive API Economy Statistics” (https://nordicapis.com/20-impressive-api-economy-statistics/ [accessed May 26, 2022]).
  • 23. PREFACE xvii experience, most organizations struggle with one or more of these questions, and a recent report by IBM found that 31% of businesses haven’t adopted microservices due to lack of internal expertise.2 Equally, Postman’s 2022 State of the API Report found that 14% of respondents experience API integration failures 11%–25% of the time (http:/ /mng.bz/Xa9v), and according to Salt Security, 94% of organizations experi- enced API security incidents in 2022.3 Many books address the problems mentioned in the previous paragraph, but they typically do it from a highly specific point of view: some focus on architecture, others on APIs, and yet others on security. I felt there’s a gap for a book that brings all these questions together and addresses them with a practical approach: essentially, a book that can get an average developer up and running quickly with the best practices, principles, and patterns for designing and building microservice APIs. I wrote this book with that goal in mind. Over the past years, I’ve had the opportunity to work with different clients helping them to architect microservices and deliver API integrations. Working on those proj- ects gave me a vantage view into the major hurdles that development teams face when working with microservices and APIs. As it turns out, both technologies are deceivingly simple. A well-designed API is easy to navigate and consume, while well-architected microservices boost developer productivity and are easily scalable. On the other side of the spectrum, badly designed APIs are error prone and difficult to use, and badly architected microservices result in so-called distributed monoliths. The obvious questions arise: How do you design good APIs? And how do you archi- tect loosely coupled microservices? This book will help you answer these questions and more. You’ll also get your hands dirty building APIs and services, and you’ll learn how to secure them, test them, and deploy them. The methods, patterns, and principles that I teach in this book are the outcome of many years of trials and experimentation, and I’m very excited about sharing them with you. I hope you find this book a valuable resource in your journey towards becoming a better software developer and architect. 2 “Microservices in the enterprise, 2021: Real benefits, worth the challenges,” (https://www.ibm.com/downloads/ cas/OQG4AJAM [accessed 26th May 2022]). 3 Salt Security, “State of API Security Q3 2022”, p. 4 (https://content.salt.security/state-api-report.html).
  • 24. xviii acknowledgments Writing this book has been one of the most fascinating journeys in my career, and I couldn’t have done it without the help and support of my family and an amazing team of colleagues. The book is dedicated to my wonderful wife, Jiwon, without whose constant encouragement and understanding I wouldn’t have been able to complete this book, and to our daughter, Ivy, who made sure I never had a dull moment in my schedule. I have benefited enormously from the people who contributed ideas for the book, helped me better understand the tools and protocols I use in it, and provided feedback on various chapters and drafts. Special thanks go to Dmitry Dygalo, Kelvin Meeks, Sebastián Ramírez Montaño, Chris Richardson, Jean Yang, Gajendra Deshpande, Oscar Islas, Mehdi Medjaoui, Ben Hutton, Andrej Baranovskij, Alex Mystridis, Roope Hakulinen, Steve Ardagh-Walter, Kathrin Björkelund, Thomas Dean, Marco Antonio Sanz, Vincent Vandenborne, and the amazing maintainers of Ariadne at Mirumee. Since 2020, I’ve presented drafts and ideas from the book at various conferences, including EuroPython, PyCon India, API World, API Specifications Conference, and various podcasts and meetups. I want to thank everyone who attended my presenta- tions and gave me valuable feedback. I also want to thank the attendants to my work- shops at microapis.io for their thoughtful comments on the book. I want to thank my acquisitions editor, Andy Waldron. Andy did a brilliant job helping me get my book proposal in good shape and keeping the book focused on rel- evant topics. He also supported me tirelessly to promote the book and helped me to reach a wider audience.
  • 25. ACKNOWLEDGMENTS xix The book you now have in your hands is readable and understandable thanks to the invaluable work of my editor, Marina Michaels, who went far and beyond to help me write a better book. She did an outstanding job helping me improve my writing style, and keeping me on track and motivated. I want to thank my technical editor, Nick Watts, who rightly pointed out many inac- curacies and always challenged me to provide better explanations and illustrations, and my technical proofreader, Al Krinker, who diligently checked all the code listings and the GitHub repository for this book, making sure the code is correct and executes without issues. I also want to thank the rest of the Manning team who was involved in the produc- tion of this book, including Candace Gillhoolley, Gloria Lukos, Stjepan Jureković, Christopher Kaufmann, Radmila Ercegovac, Mihaela Batinić, Ana Romac, Aira Dučić, Melissa Ice, Eleonor Gardner, Breckyn Ely, Paul Wells, Andy Marinkovich, Katie Tennant, Michele Mitchell, Sam Wood, Paul Spratley, Nick Nason, and Rebecca Rinehart. Thanks also go to Marjan Bace for betting on me and giving this book a chance. While working on this book, I had the opportunity to receive detailed and out- standing feedback from the most amazing group of reviewers, including Alain Lompo, Björn Neuhaus, Bryan Miller, Clifford Thurber, David Paccoud, Debmalya Jash, Gaurav Sood, George Haines, Glenn Leo Swonk, Hartmut Palm, Ikechukwu Okonkwo, Jan Pieter Herweijer, Joey Smith, Juan Jimenez, Justin Baur, Krzysztof Kamyczek, Manish Jain, Marcus Young, Mathijs Affourtit, Matthieu Evrin, Michael Bright, Michael Rybintsev, Michal Rutka, Miguel Montalvo, Ninoslav Cerkez, Pierre- Michel Ansel, Rafael Aiquel, Robert Kulagowski, Rodney Weis, Sambasiva Andaluri, Satej Kumar Sahu, Simeon Leyzerzon, Steven K Makunzva, Stuart Woodward, Stuti Verma, and William Jamir Silva. I credit them all with much of the good content that made its way into the book. Since the book went into MEAP, I’ve been blessed by the words of encouragement and feedback that many of my readers sent me through various channels, such as LinkedIn and Twitter. I was also lucky to converse with a brilliant community of read- ers who actively participated in the book’s forum in Manning’s liveBook platform. I’m heartily grateful to all of you. This book wouldn’t have been possible without the tireless work of thousands of open source contributors who created and maintain the amazing libraries that I use in this book. I’m very thankful to all of you, and I hope my book helps to make your amazing work more visible. Finally, thank you, the reader, for acquiring a copy of my book. I can only hope that you find this book useful and informative and that you enjoy reading it as much as I enjoyed writing it. I love to hear from my readers, and I’d be delighted if you share your thoughts on the book with me.
  • 26. xx about this book The goal of this book is to teach you how to build microservices and drive their inte- grations using APIs. You’ll learn to design a microservices platform and to build REST and GraphQL APIs to enable communication between microservices. You’ll also learn to test and validate your microservice APIs, to secure them, and to deploy and operate them in the cloud. Who should read this book? This book is helpful for software developers who work with microservices and APIs. The book uses a very practical approach, and nearly every chapter illustrates the explanations with full coding examples. Therefore, hands-on developers who work directly with microservice APIs will find the book’s contents valuable. The coding examples are in Python; however, knowledge of the language isn’t nec- essary to be able to follow along with them. Before introducing new code, every con- cept is explained thoroughly. The book contains a lot of emphasis on design strategies, best practices, and devel- opment workflows, and therefore it’s also useful for CTOs, architects, and VPs of engi- neering who need to decide whether microservices are the right architectural solution for them, or who need to choose between different API strategies and how to make the integrations work.
  • 27. ABOUT THIS BOOK xxi How this book is organized: A roadmap The book is divided into four sections with a total of 14 chapters. Part 1 introduces the concepts of microservices and APIs, shows how to build a simple API, and explains how to design a microservices platform:  Chapter 1 introduces the main concepts of the book: microservices and APIs. It explains how microservices differ from monolithic architecture, and when it makes sense to use monoliths versus microservices. It also explains what APIs are and how they help us drive integrations between microservices.  Chapter 2 offers a step-by-step guide for implementing APIs using Python’s pop- ular FastAPI framework. You’ll learn to read an API specification and under- stand its requirements. You’ll also learn to build APIs in gradual steps, and how to test your data validation models.  Chapter 3 explains how to design a microservices platform. It introduces three fundamental microservice design principles, and it explains how to decompose a system into microservices, using decomposition by business capability and decomposition by subdomains. Part 2 explains how to design, document, and build REST APIs, and how to build a microservice:  Chapter 4 explains the design principles of REST APIs. It introduces the six constraints of REST architecture and the Richardson Maturity Model, and then moves on to explain how we leverage the HTTP protocol to design well- structured and highly expressive REST APIs.  Chapter 5 explains how to document a REST API using the OpenAPI specifica- tion standard. You’ll learn the basics of JSON Schema syntax, how to define endpoints, how to model your data, and how to refactor your documentation with reusable schemas.  Chapter 6 explains how to build REST APIs using two popular Python frame- works: FastAPI and Flask. You’ll learn about the differences between the two frameworks, but you’ll also learn how the principles and patterns for building APIs remain the same and transcend the implementation details of any techni- cal stack.  Chapter 7 explains fundamental principles and patterns for building microser- vices. It introduces the concept of hexagonal architecture, and it explains how to enforce loose coupling between the layers of an application. It also explains how to implement database models using SQLAlchemy and how to manage database migrations using Alembic. Part 3 explains how to design, consume, and build GraphQL APIs:  Chapter 8 explains how to design GraphQL APIs and how the Schema Defini- tion Language works. It introduces GraphQL’s built-in types, and it explains
  • 28. ABOUT THIS BOOK xxii how to define custom types. You’ll learn how to create relationships between types, and how to define queries and mutations.  Chapter 9 explains how to consume GraphQL APIs. You’ll learn to run a mock server and how to explore GraphQL documentation using GraphiQL. You’ll learn to run queries and mutations against a GraphQL server and how to parametrize your operations.  Chapter 10 explains how to build GraphQL APIs using Python’s Ariadne frame- work. You’ll learn to leverage the API documentation to automatically load data validation models, and also to implement resolvers for custom types, queries, and mutations. Part 4 explains how to test, secure, and deploy your microservice APIs:  Chapter 11 explains how to add authentication and authorization to your APIs using standard protocols such as OpenID Connect (OIDC) and Open Authori- zation (OAuth) 2.1. You’ll learn how to produce and validate JSON Web Tokens (JWTs) and how to create an authorization middleware for your APIs.  Chapter 12 explains how to test and validate your APIs. You’ll learn what property- based testing is and how to use it to test your APIs, and you’ll also learn to use API testing automation frameworks like Dredd and schemathesis.  Chapter 13 explains how to Dockerize your microservice APIs, how to run them locally using Docker Compose, and how to publish your Docker builds to AWS Elastic Container Registry (ECR).  Chapter 14 explains how to deploy your microservice APIs to AWS using Kuber- netes. You’ll learn to create and operate a Kubernetes cluster using AWS EKS, how to launch an Aurora serverless database into a secure network, how to inject application configuration securely using envelope encryption, and how to set up your services to operate at scale. All chapters have a common theme: building components of a fictitious, on-demand coffee delivery platform called CoffeeMesh. We introduce CoffeeMesh in chapter 1, and in chapter 3, we break the platform down into microservices. Therefore, I recom- mend reading chapters 1 and 3 to get a better understanding of the examples intro- duced in later chapters. Otherwise, every part of the book is fairly independent, and each chapter is pretty self-contained. For example, if you want to learn how to design and build REST APIs, you can jump straight to part 2, and if your interest lies with GraphQL APIs, you can focus on part 3. Equally, if you want to learn to add authenti- cation and authorization to your APIs, you can jump straight into chapter 11, or if you want to learn how to test APIs, you can go directly to chapter 12. There’re some cross-references between chapters: for example, chapter 12 refer- ences the API implementations from parts 2 and 3, but if you’re comfortable building APIs, you should be able to skip directly to chapter 12. The same is true for the other chapters in part 4.
  • 29. ABOUT THIS BOOK xxiii About the code This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to high- light code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In some cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. Except for chapters 1, 3, and 4, every chapter of the book is full of coding exam- ples that illustrate every new concept and pattern introduced to the reader. Most of the coding examples are in Python, except in chapters 5, 8, and 9, which focus on API design, and therefore contain examples in OpenAPI/JSON Schema (chapter 5) and the Schema Definition Language (chapters 8 and 9). All the code is thoroughly explained, and therefore it should be accessible to all readers, including those who don’t know Python. You can get executable snippets of code from the liveBook (online) version of this book at https:/ /livebook.manning.com/book/microservice-apis. The complete code for the examples in the book is available for download from the Manning website at www.manning.com, and from a GitHub repository dedicated to this book at: https:// github.com/abunuwas/microservice-apis. Every chapter has a corresponding folder in the GitHub repo, such as ch02 for chapter 2. Unless otherwise specified, all file references in each chapter are relative to their corresponding folder in GitHub. For example, in chapter 2, orders/app.py refers to the ch02/orders/app.py file in GitHub. The GitHub repository for this book shows the final state of the code in every chapter. Some chapters show how to build features progressively, in iterative steps. In those cases, the version of the code you’ll find on GitHub matches the final version of the code in the chapter. The Python code examples in the book have been tested with Python 3.10, although any version of Python upwards of 3.7 should work just the same. The code and the com- mands that I use throughout the book have been tested on a Mac machine, but they should work without problems on Windows and Linux as well. If you work on Windows, I recommend you use a POSIX-compatible terminal, such as Cygwin. I’ve used Pipenv to manage dependencies in every chapter. In each chapter’s folder, you’ll find Pipfile and Pipfile.lock files that describe the exact dependencies that I used to run the code examples. To avoid problems running the code, I recom- mend you download those files at the start of every chapter, and install the dependen- cies from them.
  • 30. ABOUT THIS BOOK xxiv liveBook discussion forum Purchase of Microservice APIs includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for your- self, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https:/ /livebook.manning.com/book/microservice -apis/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking him some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website for as long as the book is in print. Other online resources If you want to learn more about microservice APIs, you can check out my blog, https:// microapis.io/blog, which contains additional resources that complement the lessons of this book. On the same website, I also keep an up-to-date list of workshops and sem- inars that I organize frequently, which also complement this book.
  • 31. xxv about the author JOSÉ HARO PERALTA is a software and architecture consultant. With over 10 years of experience, José has helped organizations big and small to build complex systems, architect microservice platforms, and deliver API integrations. He’s also the founder of microapis.io, a company that provides software consulting and training services. Recognized as a thought leader in the fields of cloud computing, DevOps, and software automation, José speaks regularly at international conferences and frequently organizes public workshops and seminars.
  • 32. xxvi about the cover illustration The figure on the cover of Microservice APIs is captioned “L’invalide,” or “The Dis- abled,” and depicts a wounded French soldier who was a resident at the Hôtel national des Invalides, or National House of the Disabled. This image is taken from a collection by Jacques Grasset de Saint-Sauveur, published in 1797. Each illustration is finely drawn and colored by hand. In those days, it was easy to identify where people lived and what their trade or sta- tion in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional cul- ture centuries ago, brought back to life by pictures from collections such as this one.
  • 33. Part 1 Introducing Microservice APIs Microservices are an architectural style in which components of a system are designed as standalone and independently deployable applications. The concept of microservices has been around since the early 2000s, and since the 2010s it has gained in popularity. Nowadays, microservices are a popular choice for building modern websites. As you’ll learn in chapter 1, microservices allow you to leverage the power of distributed applications, scale components more easily, and release faster. However, for all their benefits, microservices also come with challenges of their own. They bring a substantial infrastructure overhead, and they’re more difficult to monitor, operate, and trace. When working with microservices, the first challenge is to get their design right, and in chapter 3 you’ll learn several principles and strategies that will help you build robust microservices. Microservices collaborate through APIs, and in this book, you’ll learn to design and build REST and GraphQL APIs for your microservices. Chapter 2 gives you a taste of building a REST API, and in the second part of this book, you’ll learn additional patterns and principles to build robust REST APIs. The most challenging aspect of working with APIs is ensuring that both the API cli- ent and the API server follow the API specification, and in chapter 1 you’ll learn about documentation-driven development and the importance of starting the API journey with a good and well-documented design.
  • 34. 2 PART 1 Introducing Microservice APIs The first part of this book teaches you foundational patterns and principles for building microservices and driving their integrations with APIs. In the rest of this book, we build on top of the concepts introduced here, and you’ll learn how to build robust APIs, how to test them, how to protect them, and how to deploy your microser- vice APIs to the cloud. Our intrepid journey is just about to begin!
  • 35. 3 What are microservice APIs? This chapter defines the most important concepts in this book: microservices and APIs. Microservices are an architectural style in which components of a system are designed as independently deployable services, and APIs are the interfaces that allow us to interact with those services. We will see the defining features of microservices architecture and how they compare with monolithic applications. Monolithic appli- cations are structured around a single code base and deployed in a single build. We’ll discuss the benefits and the disadvantages of microservices architecture. The last part of this chapter talks about the most important challenges that we face when designing, implementing, and operating microservices. This discussion is not to deter you from embracing microservices, but so that you can make an informed decision about whether microservices are the right choice of architecture for you. This chapter covers  What microservices are and how they compare with monolithic applications  What web APIs are and how they help us drive integrations between microservices  The most important challenges of developing and operating microservices
  • 36. 4 CHAPTER 1 What are microservice APIs? 1.1 What are microservices? In this section, we define what microservices architecture is, and we analyze how microservices compare with monolithic applications. We’ll look into the benefits and challenges of each architectural pattern. Finally, we’ll also take a brief look at the his- torical developments that led to the emergence of modern microservices architecture. 1.1.1 Defining microservices So, what are microservices? Microservices can be defined in different ways, and, depending on which aspect of microservices architecture we want to emphasize, authors provide slightly different yet related definitions of the term. Sam Newman, one of the most influential authors in the field of microservices, provides a minimal definition: “Microservices are small, autonomous services that work together.”1 This definition emphasizes the fact that microservices are applications that run independently of each other yet can collaborate in the performance of their tasks. The definition also emphasizes that microservices are “small.” In this context, “small” doesn’t refer to the size of the microservices’ code base, but to the idea that micro- services are applications with a narrow and well-defined scope, following the Single Responsibility Principle of doing one thing and doing it well. A seminal article written by James Lewis and Martin Fowler provides a more detailed definition. They define microservices as an architectural style with “an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API” (https://martinfowler.com/articles/microservices.html). This definition empha- sizes the autonomy of the services by stating that they run in independent processes. Lewis and Fowler also highlight that microservices have a narrow scope of responsibil- ities by saying that they are “small,” and they explicitly describe how microservices communicate through lightweight protocols, such as HTTP. DEFINITION A microservice is an architectural style in which components of a system are designed as independently deployable services. Microservices are designed around well-defined business subdomains, and they talk to each other using lightweight protocols, such as HTTP. From the previous definitions, we can see that microservices can be defined as an architectural style in which services are components that perform a small and clearly defined set of related functions. As you can see in figure 1.1, this definition means that a microservice is designed and built around a specific business subdomain, for example, processing payments, sending emails, or handling orders from a customer. Microservices are deployed as independent processes, typically running in indepen- dent environments, and expose their capabilities through well-defined interfaces. In this book, you will learn to design and build microservices that expose their capabilities 1 Sam Newman, Building Microservices (O’Reilly, 2015), p. 2.
  • 37. 5 1.1 What are microservices? through web APIs, though other types of interfaces are also possible, such as messag- ing queues.2 1.1.2 Microservices vs. monoliths Now that we know what microservices are, let’s see how they compare with the mono- lithic application pattern. In contrast with microservices, a monolith is a system where all functionality is deployed together as a single build and runs in the same process. For example, figure 1.2 shows a food delivery application with four services: a pay- ments service, an orders service, a delivery service, and a customer support service. Since the application is implemented as a monolith, all functionality is deployed together. We can run multiple instances of a monolithic application and have them run in parallel for redundancy and scalability purposes, but it’s still the whole applica- tion running in each process. DEFINITION A monolith is an architectural pattern in which the whole applica- tion is deployed as a single build. In some situations, the monolith is the right choice of architecture. For example, we’d use a monolith when our code base is small and it isn’t expected to grow very large.3 Monoliths also come with advantages. First, having the whole implementation in the same code base makes it easier to access data and logic from different subdomains. And because everything runs within the same process, it is easy to trace errors through the application: you only need to place a few breakpoints in different parts of your code, and you will get a detailed picture of what happens when something goes wrong. Besides, because all the code falls within the scope of the same project, you 2 For a comprehensive view of the different interfaces that can be used to enable communication between microservices, see Chris Richardson, Microservices Patterns (Manning, 2019). 3 For a thorough analysis of strategic architectural decisions around monoliths and microservices, see Vernon, Vaughn and Tomasz Jaskula, Strategic Monoliths and Microservices (Addison-Wesley, 2021). Payments service Orders service Email service Food elivery pp d a Figure 1.1 In microservices architecture, every service implements a specific business subdomain and is deployed as an independent component that runs in its own process.
  • 38. 6 CHAPTER 1 What are microservice APIs? can leverage the productivity features of your favorite development editor when con- suming functionality from a different subdomain. However, as the application grows and becomes more complex, this type of architec- ture shows limitations. This happens when the code base grows to a point where it becomes difficult to manage, and when finding your way through the code becomes arduous. Additionally, being able to reuse code from other subdomains within the same project often leads to tight coupling among components. Tight coupling happens when a component depends on the implementation details of another piece of code. The bigger the monolith, the longer it takes to test it. Every part of the monolith must be tested, and as we add new features to it, the test suite grows larger. Conse- quently, deployments become slower and encourage developers to pile up changes within the same release, which makes releases more challenging. Because many changes are released together, if a new bug is introduced in the release, it is often dif- ficult to spot the specific change that caused the bug and roll it back. And because the whole application runs within the same process, when you scale the resources for one component, you are scaling for the whole application. Long story short, code changes become increasingly risky and deployments become more difficult to manage. How can microservices help us address these issues? Microservices address some of the issues associated with monolithic applications by enforcing strict boundaries separating components. When you implement an Food delivery app Payments service Orders service Delivery service Customer support service Food delivery app Payments service Orders service Delivery service Customer support service Food delivery app Payments service Orders service Delivery service Customer support service Figure 1.2 In a monolithic application, all functionality is deployed together as a single build to each server.
  • 39. 7 1.1 What are microservices? application using microservices, each microservice runs in a different process, often in different servers or virtual machines, and can have a completely different deploy- ment model. As a matter of fact, they can be written in completely different program- ming languages (that does not mean they should!). Because microservices contain smaller code bases than a monolith, and because their logic is self-contained and defined within the scope of a specific business subdo- main, it is easier to test them, and their test suites run faster. Because they do not have dependencies with other components of the platform at the code level (except per- haps for some shared libraries), their code is clearer, and it is easier to refactor them. This means the code can get better over time and become more maintainable. Con- sequently, we can make small changes to the code and release more often. Smaller releases are more controllable, and if we spot a bug, the releases are easier to roll back. I’d like to emphasize that microservices are not a panacea. As we will see in section 1.3, microservices also have limitations and bring challenges of their own. Now that we know what microservices are and how they compare with monolithic applications, let’s take a step back and see what developments led to the emergence of this type of architecture. 1.1.3 Microservices today and how we got here In many ways, microservices are not new.4 Companies were implementing and deploy- ing components as independent applications well before the concept of microser- vices became popular. They just did not call it microservices. Werner Vogels, CTO of Amazon, explains how Amazon started to experiment with this type of architecture in the early 2000s. By that time, the code base for the Amazon website had grown into a complex system without a clear architectural pattern, where making new releases and scaling the system had become serious pain points. To combat these issues, they decided to look for independent pieces of logic within the code and separate them out into independently deployable components, with an API in front of them. As part of this process, they also identified the data that belongs to those components and made sure that other parts of the system could not access the data except through an API. They called this new type of architecture service-oriented architecture (https:/ /vimeo .com/29719577). Netflix also pioneered this type of architectural style at scale, and they referred to it as “fine-grained Service Oriented Architecture.”5 4 For a more comprehensive analysis of the history of microservices architecture and its precursors, see Nicola Dragoni et al, “Microservices: Yesterday, Today, and Tomorrow,” Present and Ulterior Software Engineering (Springer, 2017), pp. 195–216. 5 Allen Wang and Sudhir Tonse, “Announcing Ribbon: Tying the Netflix Mid-Tier Services Together,” Netflix Technology Blog, January 18, 2013, https://netflixtechblog.com/announcing-ribbon-tying-the-netflix-mid-tier -services-together-a89346910a62. For an excellent discussion of the difference between service-oriented archi- tecture (SOA) and microservices architecture, see Richardson, Microservices Patterns, pp. 13–14.
  • 40. 8 CHAPTER 1 What are microservice APIs? The term microservice grew in popularity in the early 2010s to describe this type of architecture. For example, James Lewis used this concept in a presentation at the 33rd Degree conference in Krakow in 2012, under the title “Micro-Services—Java, the Unix way” (https:/ /vimeo.com/74452550). In 2014 the concept was consolidated with a paper written by Martin Fowler and James Lewis about the architectural features of microservices (https://martinfowler.com/articles/microservices.html), as well as the publication of Newman’s influential book Building Microservices. Today, microservices are a widely used architectural style. Most companies in which technology plays an important role are already using microservices or moving toward its adoption. It is also common for startups to begin implementing their platform using a microservices approach. However, microservices are not for everyone, and although they bring substantial benefits, as we have shown, they also carry consider- able challenges, as we will see in section 1.3. 1.2 What are web APIs? In this section, we will explain web APIs. You will learn that a web API is a specific instance of the more general concept of an application programming interface (API). It is important to understand that an API is just a layer on top of an application, and that there are different types of interfaces. For this reason, we will begin this section by defining what an API is, and then we will move on to explaining how APIs help us drive integrations between microservices. 1.2.1 What is an API? An API is an interface that allows us to programmatically interact with an application. Programmatic interfaces are those we can use from our code or from the terminal, as opposed to graphic interfaces, in which we use a user interface to interact with the application. There are multiple types of application interfaces, such as command-line interfaces (CLIs; interfaces that allow you to use an application from a terminal), desktop UI interfaces, web UI interfaces, or web API interfaces. As you can see in fig- ure 1.3, an application can have one or more of these interfaces. To illustrate this idea, think of the popular client URL (cURL). cURL is a CLI to the libcurl library. libcurl implements functionality that allows us to interact with URLs, Web application programming interface Command- ine l interface Web user interface Desktop user interface Application logic Figure 1.3 An application can have multiple interfaces, such as a web API, a CLI, a web UI, and a desktop UI.
  • 41. 9 1.2 What are web APIs? while cURL exposes those capabilities through a CLI. For example, we can use cURL to send a GET request to a URL: $ curl -L http://www.google.com We can also use cURL with the -O option in order to download the contents of a URL to a file: $ curl -O http://www.gnu.org/software/gettext/manual/gettext.html The libcurl library sits behind the cURL CLI, and nothing prevents us from access- ing it directly through the source code (if you are curious, you can pull it from Github: https://github.com/curl/curl) and building additional types of interfaces for this application. 1.2.2 What is a web API? Now that we understand what an API is, we will explain the defining features of a web API. A web API is an API that uses the Hypertext Transfer Protocol (HTTP) protocol to transport data. HTTP is the communication protocol that underpins the internet, and it allows us to exchange different kinds of media types, such as text, images, video, and JSON, over a network. HTTP uses the concept of a Uniform Resource Locator (i.e., URL) to locate resources on the internet, and it has features that can be lever- aged by API technologies to enhance the interaction with the server, such as request methods (e.g., GET, POST, PUT) and HTTP headers. Web APIs are implemented using technologies such as SOAP, REST, GraphQL, gRPC, and others that are dis- cussed in more detail in appendix A. 1.2.3 How do APIs help us drive microservices integrations? Microservices communicate with each other using APIs, and therefore APIs represent the interfaces to our microservices. APIs are documented using standard protocols. The API documentation tells us exactly what we need to do to interact with the micro- service and what kind of responses we can expect from it. The better the API docu- mentation, the clearer it is for the API consumer how the API works. In that sense, as you can see in figure 1.4, API documentation represents a contract between services: Figure 1.4 API specifications represent a contract between the API server and the API client. As long as both the client and the server follow the specification, the API integration will work.
  • 42. 10 CHAPTER 1 What are microservice APIs? as long as both the client and the server follow the API documentation, communica- tion will work as expected. Fowler and Lewis popularized the idea that the best strategy for integrating micro- services is by exposing smart endpoints and communicating through dumb pipes (https:// martinfowler.com/articles/microservices.html). This idea is inspired by the design principles of Unix systems, which establish that  A system should be made up of small, independent components that do only one thing.  The output for every component should be designed in such a way that it can easily become the input for another component. Unix programs communicate with each other using pipelines, which are simple mech- anisms for passing messages from one application to another. To illustrate this pro- cess, think of the following chain of commands, which you can run from the terminal of a Unix-based machine (e.g., a Mac or Linux computer): $ history | less The history command shows you the list of all commands you have run using your Bash profile. The list of commands can be long, so you may want to paginate history’s output using the less command. To pass data from one command to the another, use the pipe character (|), which instructs the shell to capture the output from the history command and pipe it as the input of the less command. We say that this type of pipe is “dumb” because its only job is passing messages from one process to another. As you can see in figure 1.5, web APIs exchange data through HTTP. The data trans- port layer knows nothing about the specific API protocol we are using, and therefore it represents our “dumb pipe,” while the API itself contains all the necessary logic to process the data. GET /orders Host: Coffeemesh.com Connection: Keep-alive Content-type: Application/json Content-length: 345 GET /orders Orders API Transport layer: TCP / UDP (packets) API request HTTP protocol Transport layer Figure 1.5 Microservices communicate over APIs using a data transport layer, such as HTTP over TCP.
  • 43. 11 1.3 Challenges of microservices architecture APIs must be stable, and behind them you can change the internal implementations of any service provided they comply with the API documentation. This means that the consumer of an API must be able to continue calling the API in the exact way as before, and it must get the same responses. This leads to another important concept in microservices architecture: replaceability.6 The idea is that you should be able to completely replace the code base that lies behind an endpoint, yet the endpoint, and therefore communication across services, will still work. Now that we understand what APIs are and how they help us drive integrations between services, let’s look at the most important challenges posed by microservices. 1.3 Challenges of microservices architecture As we saw in section 1.1.2, microservices bring substantial benefits. However, they also come with significant challenges. In this section, we discuss the most important chal- lenges that microservices pose, which we classify into five main categories:  Effective service decomposition  Microservices integration tests  Handling service unavailability  Tracing distributed transactions  Increased operational complexity and infrastructure overhead All the problems and difficulties that we discuss in this section can be addressed with specific patterns and strategies, some of which we detail over the course of this book. You’ll also find references to other resources that deal with these issues in depth. The idea here is to make you aware that microservices are not a magical cure for all the problems that monolithic applications present. 1.3.1 Effective service decomposition One of the most important challenges when designing microservices is service decom- position. We must break down a platform into loosely coupled yet sufficiently inde- pendent components with clearly defined boundaries. You can tell whether you have unreasonable coupling between your services if you find yourself changing one service whenever you change another service. In such situations, either the contract between services is not resilient, or there are enough dependencies between both compo- nents to justify merging them. Failing to break down a system into independent microservices can result in what Chris Richardson, author of Microservices Patterns, calls a distributed monolith, a situation where you combine all the problems of mono- lithic architectures with all the problems of microservices, without enjoying the bene- fits of any of them. In chapter 3, you’ll learn useful design patterns and service decomposition strategies that will help you break down a system into microservices. 6 Newman, Building Microservices, pp. 7–8.
  • 44. 12 CHAPTER 1 What are microservice APIs? 1.3.2 Microservices integration tests In section 1.1.2, we said that microservices are usually easier to test, and that their test suites generally run faster. Microservices integration tests, however, can be signifi- cantly more difficult to run, especially in cases where a single transaction involves col- laboration among several microservices. When your whole application runs within the same process, it is fairly easy to test the integration between different components, and most of it will simply require well-written unit tests. In a microservices context, to test the integration among multiple services you need to be able to run all of them with a setup similar to your production environment. You can use different strategies to test microservices integrations. The first step is making sure that each service has a well-documented and correctly implemented API. You can test the API implementation against the API specification using tools like Dredd and Schemathesis, as you’ll learn in chapter 12. You must also ensure that the API client is consuming the API exactly as dictated by the API documenta- tion. You can write unit tests for the API client using the API documentation to gener- ate mocked responses from the service.7 Finally, none of these tests will be sufficient without a full-blown end-to-end test that runs the actual microservices making calls to each other. 1.3.3 Handling service unavailability We have to make sure that our applications are resilient in the face of service unavail- ability, connections and request timeouts, erroring requests, and so on. For example, when we place an order through a food delivery application such as Uber Eats, Deliv- ery Hero, or Deliveroo, a chain of requests between services unfolds to process and deliver the order, and any of those requests can fail at any point. Let’s take a high-level view of the process that takes place when a user places an order (see figure 1.6 for an illustration of the chain of requests): 1 A customer places an order and pays for it. The order is placed using the orders service, and to process the payment, the orders service works together with the payments service. 2 If payment is successful, the orders service makes a request to the kitchen ser- vice to schedule the order for production. 3 Once the order has been produced, the kitchen service makes a request to the delivery service to schedule the delivery. In this complex chain of requests, if one of the services involved fails to respond as expected, it can trigger a cascading error through the platform that leaves the order unprocessed or in an inconsistent state. For this reason, it is important to design 7 To learn more about API development workflows and how to use API mock servers to build the client, check out my presentation “API Development Workflows for Successful Integrations,” Manning API Conference, August 3, 2021, https://youtu.be/SUKqmEX_uwg.
  • 45. 13 1.3 Challenges of microservices architecture microservices so that they can deal reliably with failing endpoints. Our end-to-end tests should consider these scenarios and test the behavior of our services in those situations. 1.3.4 Tracing distributed transactions Collaborating services must sometimes handle distributed transactions. Distributed transactions are those that require the collaboration of two or more services. For example, in a food delivery application, we want to keep track of the existing stock of ingredients so that our catalogue can accurately reflect product availability. When a user places an order, we want to update the stock of ingredients to reflect the new availability. Specifically, we want to update the stock of ingredients once the payment has been successfully processed. As you can see in figure 1.7, the successful processing of an order involves the following actions: 1 Process the payment. 2 If payment is successful, update the order’s status to indicate that it’s in progress. 3 Interface with the kitchen service to schedule the order for production. 4 Update the stock of ingredients to reflect their current availability. Orders service Kitchen service 2. Upon successful payment, the orders service schedules the order. Handle error Orders service Payments service 1. The customer places an order and pays for it. Handle error Kitchen service Delivery service 3. Once the order is ready, the kitchen arranges its delivery. Handle error Figure 1.6 Microservices must be resilient to events such as service unavailability, request timeouts, and processing errors from other services and either retry the requests or come back to the user with a meaningful response.
  • 46. 14 CHAPTER 1 What are microservice APIs? All of these operations are related, and they must be orchestrated so that they either all succeed or fail together. We can’t have an order successfully paid without correctly updating its status, and we shouldn’t schedule its production if payment fails. We may want to update the availability of the ingredients at the time of making the order, and if payment fails later on, we want to make sure we rollback the update. If all these actions happen within the same process, managing the flow is straightforward, but with microservices we must manage the outcomes of various processes. When using microservices, the challenge is ensuring that we have a robust communication process among services so that we know exactly what kind of error happens when it does, and we take appropriate measures in response to it. In the case of services that work collaboratively to serve certain requests, you also must be able to trace the cycle of the request as it goes across the different services to be able to spot errors during the transaction. To gain visibility of distributed transac- tions, you’ll need to set up distributed logging and tracing for your microservices. You can learn more about this topic from Jamie Riedesel’s Software Telemetry (Man- ning, 2021). 1.3.5 Increased operational complexity and infrastructure overhead Another important challenge that comes with microservices is the increased opera- tional complexity and operational overhead they add to your platform. When the whole backend of your website runs within a single application build, you only need to deploy and monitor one process. When you have a dozen microservices, every service must be configured, deployed, and managed. And this includes not only the provi- sioning of servers to deploy the services, but also log aggregation streams, monitoring Products and ingredients service Kitchen service Orders service Payments service Customer Payment successful Payment failed Process the payment. Update the order’s state. Notify the customer. Schedule the order for production. Update the stock of ingredients. Figure 1.7 A distributed transaction involves collaboration among multiple services. If any of these services fails, we must be able to handle the failure and provide a meaningful response to the user.
  • 47. 15 1.4 Introducing documentation-driven development systems, alerts, self-recovery mechanisms, and so on. As you’ll learn in chapter 3, every service owns its own database, which means they also require multiple database setups with all the features needed to operate at scale. And it is not unusual that a new deploy- ment changes the endpoint for a microservice, whether it’s the IP, the base URL, or a specific path within a generic URL, which means its consumers must be notified of the changes. When Amazon first started their journey toward a microservices architecture, they discovered that development teams would spend about 70% of their time managing infrastructure (https://vimeo.com/29719577 at 07:53). This is a very real risk that you face if you do not adopt best practices for infrastructure automation from the begin- ning. And even if you do, you are likely to spend a significant amount of time develop- ing custom tooling to manage your services effectively and efficiently. 1.4 Introducing documentation-driven development As we explained in section 1.2.3, the success of an API integration depends on good API documentation, and in this section, we introduce an API development workflow that puts documentation at the forefront of API development. As you can see in fig- ure 1.8, documentation-driven development is an approach to building APIs that works in three stages: 1 You design and document the API. 2 You build the API client and the API server following the documentation. 3 You test both the API client and the API server against the documentation. Let’s dive into each of these points. The first step involves designing and documenting the specification. We build APIs for others to consume, so before we build the API, we must produce an API design that meets the needs of our API clients. Just as we involve users when we design an application’s user interface (UI), we must also engage with our API consumers when we design the API. Good API design delivers good developer experience, while good API documenta- tion helps to deliver successful API integrations. What is API documentation? API doc- umentation is a description of the API following a standard interface description language (IDL), such as OpenAPI for REST APIs and the Schema Definition Lan- guage (SDL) for GraphQL APIs. Standard IDLs have ecosystems of tools and frame- works that make it easier to build, test, and visualize our APIs, and therefore it’s worth investing time in studying them. In this book, you’ll learn to document your APIs with OpenAPI (chapter 5) and the SDL (chapter 8). Once we have produced a documented API design, we move on to the second stage, which consists of building the API server and the API client against the API documentation. In chapters 2 and 6, you’ll learn to analyze the requirements of an OpenAPI specification and to build an API application against them, and in chap- ter 10, we’ll apply the same approach to GraphQL APIs. API client developers can
  • 48. 16 CHAPTER 1 What are microservice APIs? also leverage the API documentation to run API mock servers and test their code against them.8 The final stage involves testing our implementation against the API documenta- tion. In chapter 12, you’ll learn to use automated API testing tools such as Dredd and Schemathesis, which can generate a solid battery of tests for your API. Running Dredd and Schemathesis in combination with your application unit test suite will give you confidence that your API implementation works as it should. You should run these tests in your continuous integration server to make sure you don’t release any code that breaks the contract with the API documentation. 8 To learn how API server and client developers can leverage API documentation in their software development process, check out my talk “Leveraging API Documentation to Deliver Reliable API Integrations,” API Specifi- cations Conference, September 28–29, 2021, https:/ /youtu.be/kAWvM-CVcnw. 1. API design and documentation 2. Build the client and the server against the API documentation. 3. Test the implementation against the specification. Figure 1.8 Documentation-driven development works in three stages: design and document, implement, and validate.
  • 49. 17 1.5 Who this book is for and what you will learn By putting API documentation at the forefront of the development process, documentation-driven development helps you avoid one of the most common problems API developers face: disagreements between the client and the server development teams about how the API should work. In the absence of robust API documentation, developers often need to guess on implementation details of the API. In such cases, the API rarely succeeds its first integration test. Although documentation-driven devel- opment won’t give a 100% guarantee that your API integrations will work, it will sig- nificantly reduce the risk of API integration failure. 1.5 Introducing the CoffeeMesh application To illustrate the concepts and ideas that we explain throughout this book, we’ll build components of an application called CoffeeMesh. CoffeeMesh is a fictitious applica- tion that allows customers to order coffee in any location, at any time. The Cof- feeMesh platform consists of a collection of microservices that implement different capabilities, such as processing orders and scheduling deliveries. We’ll undertake a formal analysis and design of the CoffeeMesh platform in chapter 3. To give you a taste of the kinds of things you’ll learn in this book, we’ll begin implementing the API of CoffeeMesh’s orders service in chapter 2. Before we close this chapter, I’d like to dedicate a section to explaining what you’ll learn from this book. 1.6 Who this book is for and what you will learn To make the most out of this book, you should be familiar with the basics of web devel- opment. The code examples in the book are in Python, so a basic understanding of Python is beneficial but not necessary to be able to follow along with them. You do not need to have knowledge of web APIs or microservices, as we will explain these technol- ogies in depth. It is useful if you are familiar with the model-view-controller (MVC) pattern for web development or its variants, such as the model-template-view (MTV) pattern implemented by Python’s popular Django framework. We will draw compari- sons with these patterns from time to time to illustrate certain concepts. Basic familiar- ity with Docker and cloud computing will be useful to get through the chapters about deployments, but I’ll do my best to explain every concept in detail. This book shows you how to develop API-driven microservices with Python through a hands-on approach. You will learn  Service decomposition strategies for designing microservice architectures  How to design REST APIs and how to document them using the OpenAPI spec- ification  How to build REST APIs in Python using popular frameworks like FastAPI and Flask  How to design and consume GraphQL APIs and how to build them using Python’s Ariadne framework  How to test your APIs using property-based testing and API testing frameworks such as Dredd and Schemathesis
  • 50. 18 CHAPTER 1 What are microservice APIs?  Useful design patterns to achieve loose coupling in your microservices  How to add authentication and authorization to your APIs using Open Authori- zation (OAuth) and OpenID Connect (OIDC)  How to deploy your microservices using Docker and Kubernetes to AWS By the end of this book, you will be familiar with the benefits that microservices archi- tectures bring for web applications as well as the challenges and difficulties that come with them. You will know how to integrate microservices using APIs, you will know how to build and document those APIs using standards and best practices, and you will be prepared to define the domain of an API with clear application boundaries. Finally, you’ll also know how to test, deploy, and secure your microservice APIs. Summary  Microservices are an architectural pattern in which components of a system are designed and built as independently deployed services. This results in smaller and more maintainable code bases and allows services to be optimized and scaled independently of each other.  Monoliths are an architectural pattern in which whole applications are deployed in a single build and run in the same process. This makes the application easier to deploy and monitor, but it also makes deployments more challenging when the code base grows large.  Applications can have multiple types of interfaces, such as UIs, CLIs, and APIs. An API is an interface that allows us to interact with an application program- matically from our code or terminal.  A web API is an API that runs on a web server and uses HTTP for data trans- port. We use web APIs to expose service capabilities through the internet.  Microservices talk to each other using smart endpoints and “dumb pipes.” A dumb pipe is a pipe that simply transfers data from one component to another. A great example of a dumb pipe for microservices is HTTP, which exchanges data between the API client and the API server without knowing anything about the API protocol being used. Therefore, web APIs are a great technology for driving integrations between microservices.  Despite their benefits, microservices also bring the following challenges: – Effective service decomposition—We must design services with clear boundar- ies around specific subdomains; otherwise, we risk building a “distributed monolith.” – Microservice integration tests—Running integration tests for all microservices is challenging, but we can reduce the risk of integration failures by ensuring APIs are correctly implemented. – Handling service unavailability—Collaborating services are vulnerable to service unavailability, request timeouts, and processing errors, and therefore must be able to handle those scenarios.
  • 51. 19 Summary – Tracing distributed transactions—Tracing errors across multiple services is chal- lenging and requires software telemetry tools that allow you to centralize logs, enable API visibility, and trace requests across services. – Increased operational complexity and infrastructure overhead—Each microservice requires its own infrastructure provisioning, including servers, monitoring systems, and alerts, so you need to invest additional efforts in infrastructure automation.  Documentation-driven development is an API development workflow that works in three stages: – Design and document the API. – Build the API against the documentation. – Test the API against the documentation. By putting API documentation at the forefront of the development process, documentation-driven development helps you avoid many common problems that API developers face and therefore reduce the chances of API integration failure.
  • 52. 20 A basic API implementation In this chapter, we implement the API for the orders service, which is one of the microservices of the CoffeeMesh website, the project we introduced in section 1.5. CoffeeMesh is an application that makes and delivers coffee on demand at any time, wherever you are. The orders service allows customers to place orders with CoffeeMesh. As we implement the orders API, you will get an early look into the concepts and processes that we dissect in more detail throughout this book. The code for this chapter is available under the ch02 folder of the GitHub repository provided with this book. This chapter covers  Reading and understanding the requirements of an API specification  Structuring our application into a data layer, an application layer, and an interface layer  Implementing API endpoints using FastAPI  Implementing data validation models (schemas) using pydantic  Testing the API using a Swagger UI
  • 53. 21 2.1 Introducing the orders API specification 2.1 Introducing the orders API specification Let’s begin by analyzing the requirements of the orders API. Using the orders API, we can place orders, update them, retrieve their details, or cancel them. The orders API specification is available in a file named ch02/oas.yaml in the GitHub repository for this book. OAS stands for OpenAPI specification, which is a standard format for docu- menting REST APIs. In chapter 5, you’ll learn to document your APIs using OpenAPI. As you can see in figure 2.1, the API specification describes a REST API with four main URL paths:  /orders—Allows us to retrieve lists of orders (GET) and create orders (POST).  /orders/{order_id}—Allows us to retrieve the details of a specific order (GET), to update an order (PUT), and to delete an order (DELETE).  /orders/{order_id}/cancel—Allows us to cancel an order (POST).  /orders/{order_id}/pay—Allows us to pay for an order (POST). In addition to documenting the API endpoints, the specification also includes data models that tell us what the data exchanged over those endpoints looks like. In OpenAPI, we call those models schemas, and you can find them within the compo- nents section of the orders API specification. Schemas tell us what properties must be included in a payload and what their types are. For example, the OrderItemSchema schema specifies that the product and the size properties are required, but the quantity property is optional. When the quantity property is missing from the payload, the default value is 1. Our API implementation must therefore enforce the presence of the product and the size properties in the payload before we try to create the order. /orders/{order_id} /cancel /orders/{order_id} /pay GET Returns an order PUT Updates an order DELETE Deletes an order POST Cancels an order POST Pays for an order /orders/{order_id} /orders GET Returns a list of orders POST Places an order Figure 2.1 The orders API exposes seven endpoints structured around four URL paths. Each endpoint implements different capabilities, such as placing and cancelling an order.
  • 54. 22 CHAPTER 2 A basic API implementation # file: oas.yaml OrderItemSchema: type: object required: - product - size properties: product: type: string size: type: string enum: - small - medium - big quantity: type: integer default: 1 minimum: 1 Now that we understand the requirements for building the orders API, let’s look at the architectural layout we will use for the implementation. 2.2 High-level architecture of the orders application This section offers a high-level overview of the orders API’s architectural layout. Our goal is to identify the layers of the application and to enforce clear boundaries and separation of concerns between all layers. As you can see in figure 2.2, we organize into three layers: the API layer, the busi- ness layer, and the data layer. This way of structuring the application is an adaptation of the three-tier architecture pattern, which structures applications into a data layer, a business layer, and a presen- tation layer. As you can see in figure 2.3, the data layer is the part of the application Listing 2.1 Specification for OrderItemSchema API Exposes the capabilities of the service and controls interactions with the user Business layer Implements the capabilities of the service Data layer Interfaces with the source of data Figure 2.2 To enforce separation of concerns among the different components of our service, we structure our code around three layers: the data layer knows how to interface with the source of data; the business layer implements the service’s capabilities; and the interface layer implements the service’s API.
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. hänellä ase varana. Mutta käsipä hänellä vapisee, tärähtää pyssy käsissä; niin on kiihtynyt veren kulku saanut suonet ja sydämmen sykkimään, ett'eivät jäsenet pysy vakavina. Isäntäkin on kuullut risahdukset ja päättää niistä, että karhu on tulossa, mutta risahdusten ääni kuuluu toisen haaskan läheltä ja varmaankin on metsän vilja sinne menossa. Kunhan vaan Lauri pysyisi vakavana, liikahtamatta, jott'ei pelästyisi, ja tähtäisi tarkkaan, niin kävisi kaikki hyvin. Todella nyt liikkuu tiheikössä metsän mahtava kuningas. Se on menossa sille haaskalle, missä Lauri vahtia pitää. Kun se vielä on etempänä, liikkuu se sukkelammin, ja sen vuoksi kuuluukin joskus risahdus, kun risut sen jalkojen alla katkeilevat, mutta, kuta lähemmäs haaskaa se ehtii, sitä enemmän se vauhtiaan hiljentää ja astuu sitten hyvin keveästi, varovasti, kuono maata vasten, tarkan vainunsa avulla helposti osaten kulkea haaskaa kohti. Se astuu askeleen pari kerralla ja sitten se pysähtyy, tarkkaa eteensä ja sivulleen, ikäänkuin ajatellen, ett'eihän vaan mikään mahtane havaita sen tuloa. Sitten se taas ottaa askeleen ja taas pysähtyy, kääntää keveästi pyöreätä päätänsä, katselee ja kuuntelee. Niin se kulkee hyvin varovasti ja pysähtyy melkein joka askeleella ja usein se näyttää hyvin epäilevän, ett'ei olekaan hyvä mennä ikäänkuin aikoen takaisin palata. Mutta kuitenkin se vähitellen lähenee haaskaa, kunnes se tulee niin lähelle, että se on ainoastaan muutaman sylen päässä siitä. Lauri voipi nyt hämärästi huomata, että musta esine esiintyy kuusten lomasta. Se on nyt se metsän kuningas; sen hän tietää varmaan. Tuossa se nyt seisoo haaskan lähellä ihan liikahtamatta. Johan sitä siihen saattaisi ampua, vaan pimeäpä on vielä haitaksi.
  • 57. Antaahan likemmäksi tulla. Nyt se taas astuu askeleen, mutta seisahtuu heti. Kyllä taitaa olla paras jo ampua; kenties se ei enää lähenekään. Lauri pitää pyssynsä karhua kohti ojennuttuna ja tähtää, käsi hanassa kiinni. Mutta ei ota pyssy vakaantuakseen hänen käsissään. Niin kädet vapisevat, kun hän ajattelee, että nyt se on ratkaiseva hetki. Kaiken pahan lisäksi on niin pimeä, ett'ei hän voi nähdä, mihinkä kohtaan olisi paras ampua. Hän yhä tähtäelee ja koettaa saada pyssynsä vakaantumaan; mutta se vaan yhä tärisee; ja hän miettii, että jos ei satu käymään, niin kyllä pahat asiat saattaa hänelle tulla. Mutta ei jouda hän kauan miettimään; hän vaan tähtää, ja melkein vahingossa pyssy laukeaa; ja hän samalla itse kovasti kiljahtaa pelosta, että nyt taisi käydä huonosti. Isäntä, heti laukauksen kuultuaan, ajattelee että kuinkahan on mahtanut käydä, mutta samassa Laurin huudon kuullessaan hän arvelee, että nyt taitavat asiat olla huonosti; ja lähtee heti Laurin vahtuupaikalle astumaan. Mutta karhu, pyssyn lauettua, ei kaadukaan paikalleen, eikä se karkaa ampujan kimppuun, vaan säikähtyneenä, kuitenkin aivan vahingoittumatonna, se heti kääntyy takaisin ja lähtee kiireimmän kautta pakoon pötkimään, laukkaa yli risujen ja kantojen, ja on pian kaukana kuulumattomissa. Lauri jääpi kummissaan miettimään, että näinkö se nyt kävi, ja ajattelee sitten, että olipa se paha, kun ei pyssy ruvennut käsissä vakaantumaan. Kun isäntä ehtii haaskalle, kysyy hän heti: "No, mitenkä kävi?" "Eipä käynyt hyvin", vastaa Lauri nolona. "Ei tainnut sattua, kun minä ammuin."
  • 58. "No, mitenkä sinä niin huonosti ammuit? Eikö se otus tullut aivan lähelle." "Ka, tulihan se kyllä. Mutta miten lie niin huonosti käynyt; minulla ei ruvennut pyssy vakaantumaan käsissä." "Pelottiko sinua?" "Eipä kovin pelottanut, vaan ne kädet minulla niin vapisivat, niin se tunnusti oudolta metsää ampua, jott'en saanut pyssyä vakaantumaan, vaikka kuinka koetin, ja melkeinpä vahingossa minulla pyssy laukesikin." "Kyllä taisi pelko vaivata. Mutta mitä sinä rupesit kiljumaan?" "No, minä kun ajattelin, että jos ei satukaan käymään, niin pääsi minulta semmoinen huuto tulemaan." "No, jopa tämä nyt oli! Meni hyvä saalis käsistä." "Kyllähän tämä on paha asia. Mutta eihän sille enää voi mitään." "Eihän sille enää voi mitään. Tottapa se niin oli sallittu. Mutta kyllä nyt metsä saattaa olla kauan haaskalle tulematta." Päivä alkaa nyt vähäsen kajastaa, ja isäntä ja Lauri lähtevät nyt, huonosti onnistuneen yövahtuunsa perästä, aamuhämärässä Mäntyvaaraan astumaan.
  • 59. X. Aamulla nukkuvat Mäntyvaaran miehet tavallista pitempään, he kun ovat koko yön valvoneet, ja sillä aikaa ovat Anni ja Tiina lypsyllä. Mutta vähemmin karttuu nyt maitoa kuin ennen, sillä paraimmat lypsylehmäthän on karhu kaatanut ja jälillä olevat lypsävät huonommin kuin ennen, ne kun ovat metsän tuloa säikähtäneet eivätkä sen vuoksi uskalla kulkea paremmilla laiduinpaikoilla. Kun oli ollut puhe, että joku vaimosista lähtisi karjalle paimeneksi, niin oli syntynyt keskustelu siitä, kuka se lähtee, mutta kun Anni ja Tiina olivat sanoneet pelkäävänsä, että mörkö paimenen hävittää, niin oli Kaisu lausunut, jotta hän ei pelkää ja hän kyllä uskaltaa lähteä, eikä möröstä välitä. Kun siis lehmät ovat lypsetyt, lähtee Kaisu, eväskontti selässään, karjan muassa metsään. Karjan polkua hän lähtee astumaan ja karja pysyy koossa hänen ympärillään, ei yritäkään erota hänestä, sillä niin se seuraa häntä kuin suojeliata ainakin. Se näyttää tietävän, että sillä on vaarallinen vihollinen metsässä. Sen vuoksi se nyt ei etsi ruohokkopaikkoja, ei pyri etäisemmille ruokaseuduille, vaan seuraa paimenta minne tämä menee. Mutta sitä suuntaa, missäpäin Kellokkaan ja Halunan raadot makaavat, se välttää ja rupeaa
  • 60. ammoilemaan, kun paimen sinnepäin sattuu kääntymään. Kaisu rientää iloisena karjan seurassa ja usein hän aikansa huviksi kajahuttaa ilmoille laulun ja silloin metsä kai'ullaan vastaa hänen laulusäkeihinsä. Milloin istahtaa hän pehmeälle mättäälle tai sileälle kivelle levähtämään, kun karja on sattunut löytämään ruohokkopaikan, milloin hän taas rientää kanervaisia kankaita ja hakee tiensä mäntymetsän kautta, missä ei näy heinän korttakaan. Kun hän metsässä kulkiessaan sattuu syrjään karjan näkyvistä, silloin rupeaa karja kovasti mylvimään, ammoilee surkeasti, ikäänkuin suurikin hätä olisi tarjona, mutta kun Kaisun lauluääni kajahtaa, silloin karja taas lähtee hänen luokseen rientämään ja vasikat oikein ilosta hyppelevät. Kilajaa nyt entinen Kellokkaan vaskikello toisen lehmän, Kirjon, kaulassa, kilajaa, kun Kirjo laukata vilistää Kaisun lähelle, ja rämisee läppä, lyöpi tiheään vasten laitoja, ja tiheään lenkkasee kello puolelta toiseen. Niin kuuluu metsässä monenlaisia ääniä: tuulen hiljainen humina korkeiden kuusten ja petäjäin latvoissa, Kaisun heleästi kaikuva laulu, kellojen kilinä, lehmäin ja vasikkain ammonta ja härän karhea mylvinä. Mutta ei mikään häiritse paimenen ja karjan kulkua; ei kuulu metsän pedon ääntä samoin kuin ei ihmisääntäkään muuta kuin Kaisun laulua. Metsän kuningas ei näytä itseään, ei hätyytä karjaa, vaan makaa jossain piilopaikassa, jossain mättään kolossa kuusen oksain peitossa. Lämpimiinsä asti astuu Kaisu karjaa paimentaessaan ja hänen punoittavat poskensa rupeavat tavallista enemmin hohtamaan, mutta metsälle ne nyt saavat hohtaa, taivaalle punoittaa, sillä ei kukaan ole niitä ihmettelemässä. Vihdoin Kaisu, koko päivän oltuaan paimenessa, illan tultua paimentaa karjan kotiin tarhalle, missä se pian pääsee suittusavun ääreen märehtimään ja Anni sekä Tiina tulevat lehmiä lypsämään.
  • 61. Ennen Kaisun kotiatuloa, ovat isäntä ja Lauri koteutuneet, he kun ovat olleet talaitten teossa. Kummankin haaskan lähelle ovat he läheisiin kuusiin istumasijat laittaneet, jotta siellä voisivat karhua väijyä. Mäntyvaaran isäntä kuvaellen mielessään, kuinka kunniakas teko olisi saada metsän kuningas kaadetuksi, on päättänyt, että ainakin monioita öitä on vahtuussa kulkeminen ja odottaminen, eikö sattuisi mörkö vielä jommallekummalle haaskalle tulemaan. Vastakohtana sille vahingolle, jonka karhu on talolle tuottanut, ovat kaikki Mäntyvaaralaiset elähtyneet toivosta saada kenties vielä mesikämmenen peijaita pitää, ja sen vuoksi kaikki vaan ajattelevat, kuinka olisi hyvä asia, jos sattuisi karhu kaatumaan. Mutta kun isäntä ja Lauri seuraavaksi yöksi vahtuuseen lähtevät, ajattelevat he kuitenkin ett'ei mahtane mörkö sinä yönä näyttäytyä, se kun oli viime yönä käynyt, ja luultavasti on se pahastunut päivällisestä paukkeesta, sillä syntyihän sitä vähän möykettä, kun talaita tehtiin. No, eihän kuitenkaan ennakolta voida tietää, mitä on tapahtuva, ja sen vuoksi miehet lähtevät vahtaamaan karhua, kun talaat vahtuuta varten ovat laitetut; ja kaksi jälkien palauttajaa saattaa heitä nytkin niinkuin edellisellä kerralla. Kun jälkien paluuttajat ovat kotia tulleet, jäävät naiset odottamaan eikö sattuisi kuulumaan laukausta metsästä. Ammunta kyllä selvästi kuuluisi taloon asti haaskoilta; ovat ne haaskat siksi lähellä. Mutta ei kuulu mitään pyssyn laukausta, ei sittenkään kun päivä on mailleen mennyt ja pimeys tullut. Odottajat paneutuvat vihdoin levolle ja nukahtavat; ja yhä ovat vahtaajat poissa. Häiritsemättöminä nukkuvat naiset ja lapset yönsä; ei heiltä unta riistä mikään outo ääni tai liike, paikoillaan pysyvät talaillaan vahtaajat koko yön, ja
  • 62. seinäkellon tasaiseen käyntiin he jo ovat niin tottuneet, että se ei voi heitä häiritä. Aamulla heidän noustessaan tulevat miehet kotia yölliseltä vahtuultaan. "No, kuinka kävi?" kysyy heti Kaisu. "Arvaahan tuon, mitenkä on käynyt", vastaa Lauri. "Elossa on vielä metsän kuningas." "No, eikö sitä ole näkynytkään." "Ka, eihän se näyttäynyt." "Jopa tuota saatettiin jo ennakolta arvata", sanoo isäntä, "että mörkö oli tulematta jäävä viime yöksi. Vaan kyllä se vielä käypi, kunhan jaksetaan monioita öitä odottaa." "Kukapa tuon tiennee, mitä se tekee!" puuttuu puheeseen emäntä. "Se saattaa sitä ennen taas jonkun lehmän kaataa." "No, ei tiedä mitenkä on sallittu." "Eiköhän tuo mahtane tyytyä ennen kaatamiinsa", arvelee Lauri, "niin kauan kuin niitä piisaa." "Kyllä se karja säilyy, kun vaan aina on joku paimenessa", vakuuttaa Kaisu. "Eipä kannata joka päiväksi paimenta panna", sanoo isäntä. "Leikkuuseen tarvittaisiin väkeä, vaan eihän sinne jää paljon ketään
  • 63. niin kauan kuin me miehet kuljemme vahtuussa ja joku nainen joka päivä paimenessa." "Pitää karjalla kuitenkin paimen olla niin kauan kuin mörkö näillä seuduilla liikkuu." "Lieneeköpä tuosta kovin isoa apua!" sanoo isäntä ja paneutuu penkille levähtämään samoinkuin Lauri. Levoltaan noustuaan lähtevät miehet pellolle — sitä ennen on Kaisu mennyt lehmiä paimentamaan — ja illalla taas ennen pimeää haaskoille. Isäntä on karhunpyyntihommassaan saanut tavallista enemmän vireyttä ja elää toivossa vielä saada metsän kuningas kaadetuksi. Lauriakin elähyttää sama toivo; hänkin odottaa vaan sen päivän koittavan, jolloin mesikämmenen kunniaksi kemut pidetään. Sen vuoksi he alusta pitäen joka yö käyvät vahtuussa. Mutta metsän kuningas ei nyt näyttäydykään pitkään aikaan. Useat aamut peräkkäin palaavat vahtaajat tyhjin toimin takaisin, mutta tyynimielisenä ajattelee kuitenkin isäntä karhusta, että tottapahan se vielä joskus tulee, kun lie tullakseen. Niin kuluu päivä päivän perästä, ja peltotyö jääpi melkein kokonaan vaimosten varaan, jotka kulkevat leikkuussa milloin vaan muilta töiltään joutavat; mutta miehet kulkevat yöt vahtuussa ja nukkuvat sitten päivillä niin kauan, ett'ei heiltä monta tuntia liikene leikkuuta varten. Vähäksi avuksi on siis talolle, kun sinne muuanna päivänä sattuu tulemaan kylästä kylään kuljeksiva Mikko niminen kiertolainen, jonka isäntä heti laittaa pellolle leikkaamaan. Mutta Mikko on vanha ja vaivainen ja muutenkin hidasliikkeinen, eikä hänellä siis paljon valmista tule; hitaasti edistyy hänellä leikkuu.
  • 64. Joka päivä kulkee karja laitumella, milloin Kaisu milloin Anni tai Tiina paimenena, joskus paimenettakin, mutta aina kun se illalla palaa kotia, antavat lehmät aina vähemmän maitoa; ne ehtyvät ehtymistään. Karhu ei ole vielä toista kertaa käynyt haaskoilla, vaan ei se ole lehmiäkään hätyyttänyt siitä hetkestä asti kuin se kaatoi Kellokkaan ja Halunan. Muutamana iltana taas ovat isäntä ja Lauri menneet vahtuuseen ja kiivenneet kumpikin talailleen. On erittäin tyyni ilta. Päivä on ollut lämmin ja poutainen, ja poudassa aurinko nyt laskee. Kyllähän heti päivän mailleen mentyä alkaa hämärtää ja ilta pimenee; mutta yö ei tule kuitenkaan aivan pilkko pimeä, sillä taivas on pilvetön ja siellä vilkkuu nyt useita tähtiä. Aukealla kyllä näkisi vaikka linnunkin ampua. Sitä vastoin täällä tiheässä metsässä tiheäoksaiset kuuset niin varjostavat seudut, että pimeys tekisi isoa haittaa ampuessa. Kuitenkin olisi nyt paljon helpompi huomata karhun tuloa kuin esimerkiksi ensimmäisenä vahtuuyönä. Vahtaajat istuvat talaillaan, odottavat odottamistaan ja ajattelevat, että jopa se nyt saisi mörkö alkaa tulla, koska se ei taas moneen yöhön ole näyttäynyt; alkaa se vahtuu lopulta ikäväksi käydä, kun he joka yö saavat tyhjin toimin aina aamuun asti istua kököttää, jäsentä liikuttamatta. He vuottavat vuottamistaan, kun yö tekee tuloaan, vaan vielä ei kuulu mitään ääntä, ei näy liikettä missään. Näyttää jo siltä, että tulisi yö yhtä pitkä ja ikävä kuin edellisilläkin kerroilla. Mutta yhtäkkiä isäntä kuulee metsässä risuja rasahtelevan. "No, nyt!" miettii hän iloisena ja kääntää jo pyssynsä valmiiksi ääntä kohti. "Joko nyt viimein sinä armas metsän vilja tuloa teet! Joko tuot turkkisi katsottavaksi! Tule pois vaan! En minä sinua pahoin pitele. Kunnialla sinä kotiin saatetaan."
  • 65. Piilopaikastaan oli todella metsän kuningas lähtenyt liikkeelle ja kulkenut korpien läpi, soiden yli. Nyt se lähenee haaskaa varovin askelin, astuu hiljaa ja aina väliin pysähtyy tarkataksensa, huomaako kukaan sen tuloa. Tuolta astuu se nyt kuusten välistä näkyviin, astuu varovasti ja pysähtyy joka askeleen päästä katsomaan, kuuntelemaan. Se ei ole enää kaukana raadosta. Isäntä kiihtynein mielin katselee, jott'eikö se tule vielä likemmäksi, mutta ei hän luule malttavansa odottaa niin kauan että se käypi käsiksi raatoon. Nyt se taas askeleen astuttuaan pysähtyy. Kaikki on hiljaista; ei kuulu vähintäkään ääntä. Tuli ja leimaus! Kuuluu kova pyssyn pamaus, ja kovasti kajahtaa metsä. Mäntyvaaran isäntä on laukaissut pyssynsä. "No, mitenkähän nyt, armas mesikämmen —" miettii hän ja rupeaa katsomaan, kellistyykö maahan metsän kuningas. Mutta karhu heti pyssyn lau'ettua katsahtaa ääntä kohti ja huomaa miehen. Sitä kovin suututtaa, että se on tullut häirityksi juuri kun se on ollut aikeessa käydä käsiksi makeaan ateriaan, suututtaa niin, että, kun se ei voi ampujalle mitään tehdä, se, väkevyytensä ja vihansa näytteeksi, voimakkailla käpälillään kiskasee viereltään puun kannon juurineen maasta irti ja paiskaa sen sitten voimakkaasti maata vasten, jotta koko kanto hajoaa pirstaleiksi ja pauke kaikuu kauas metsässä. "Tyhjää siinä voimiasi näytät", arvelee isäntä, luullen karhun kohta henkensä heittävän.
  • 66. Mutta eipä uuvukaan metsän vilja, ei kaadu siihen paikkaan, vaan heti, kannon käsistään paiskattuaan, se kiireimmän kautta lähtee takaisin laukkaamaan samoja jälkiä kuin oli tullutkin, laukkaa yli risujen ja mättäiden kauas kuulumattomiin. "Voi ihmettä! Nyt kumma tuli", miettii isäntä, korvallistaan kynsien. "Tämäpä nyt — No, mikähän nyt tuli, kun ei kaatunutkaan mörkö!" Ja hän laskeupi hitaasti alas puusta. Hän menee sille paikalle seisomaan, jossa karhu vast'ikään oli ollut, ja siinä hän katselee ja kuuntelee, jotta eikö kuulu metsän kuningasta missään; siinä hän siunaelee ja päivittelee ja kynsii päätään ja ajattelee, että ihan todellako se saalis pääsi käsistä. Niin — kyllä se nyt on mennyt. "Voi kuitenkin! Kuinka tämä on mahdollista!" miettii hän pahoillaan ja huutaa Lauria. Lauri tuleekin vähän ajan perästä ja kysyy heti: "No, joko nyt kaatui?" "Kaatui! Eikö!" vastaa isäntä. "Minkälainen se lie eläjä! Ei siihen pyssy tehonnut." "Tosiaanko! Sepä nyt! No, ammuittehan te tarkkaan?" "Ka, minä ammuin niin tarkkaan, jott'ei kyllä ammunnassa vikaa ollut, ja kyllä sattui." "Mutta jos ei sattunutkaan?" "Sattunutko! Ihan vissiin sattui ja hyvään paikkaan. Minä ammuin ihan sydäntä kohti."
  • 67. "Mutta eihän kuitenkaan ole sanottu, että te osasitte sydämmeen. Kuinka tuli likelle mörkö?" "Tässä näin, juuri tällä kohdalla, jossa minä nyt olen, seisoi se. Ja olisi se tullut likeimnäksikin, vaan minä en malttanut odottaa." "Siinäpä se! On saattanut, kun kuitenkaan ei otus ollut tämän likempänä, ja pimeäkinhän on tehnyt haittaa, — on saattanut kuitenkin teillä käsi pettää." "Eipä pettänytkään, totta vie. Niin totta kuin minä olen minä, niin minä ammuin ihan tarkkaan ja luoti kyllä kävi oikeaan paikkaan." "No, sitten kai on mörkö kaatunut. Jos se vaan on saanut luodin rintaansa, niin ei se kaukana olekaan täältä." "Niin sen luulisi; vaan mikä lie ollut pyssyssäni vikana, kun se ei tehonnut. Metsä vaan, heti kun olin ampunut, ikäänkuin ei olisi käynytkään, tempasi maasta irti kannon, — tuossahan tuo vielä kolo näkyy — ja lyödä läjähytti sen sitten pirstaleiksi maata vasten semmoisella jytäkällä, jotta se vasta jytäkkää oli." "Niin, kuulinhan minäkin jotain sen tapaista." "Ja sitten se heti kääntyi poispäin, sinnepäin, mistä oli tullutkin, otti laukan semmoisen, jotta se vasta kyytiä oli. Nyt se jo saattaa hyvinkin kaukana olla." "Entäpä, jos ei olisikaan!" "Voi, kyllä se ei tämän seudun likellä ole."
  • 68. "Kukapa sen vielä tietää! Jos siihen vaan on luoti käynyt, niin se ei ole hyvin kauas mahtanut päästä. Eiköhän mahtane tässä verijälkiä olla näkyvissä! Katsotaanpa! Piti kai minulla tikkuja olla — minne lienevät painuneet — no, eikö niitä — luulisippa — jopa löytyi." Lauri kun on saanut tulitikkuunsa valkean, niin sen valossa hän ja isäntä katselevat, jotta näkyykö mitään; ja todella onkin kannon sijan vieressä muutamia veritilkkoja. Siinä on yhdessä kohti sammalikko punertunut verestä, mutta muualla siinä lähellä ei näy yhtään verijälkeä, vaikka Lauri uudestaan virittää tulen toiseen tikkuun. "Onpahan käynyt", sanoo Lauri. "No, tiesinhän minä, että kävi se", sanoo vastuuksi isäntä, "ihan sydämmeen kävi." "Tokkopahan lie sydämmeen käynyt! Sittenhän olisi peto tähän paikkaan kaatunut." "Ka, niinhän minäkin luulin ampuessani, jotta kyllä se nyt tähän paikkaan kaatuu. Mutta älähän! Hyvin kummiini menin, kun se lähti täältä pois laukkaamaan. Siihen ei minun pyssyni tehonnut; ja minä alan luulla, että kunhan ei liene minun pyssyni pilattu." "Pilattuko!" "No, niinpä minusta tunnustaa, että pilattu se mahtaa olla, koskapahan ei tappanut." "Mikäpä sen olisi pilannut?" "Ka, Kuuselainen sen on mahtanut pilata."
  • 69. "Mitenhän lienee! Mutta emmehän vielä tiedä, onko mörkö kaatunut vai ei. Entäpä jos ei luoti sattunutkaan ihan sydämmeen." "Kylläpä sen piti sattua." "Mikäpä sen niin tarkkaan tietää! On saattanut sattua semmoiseen paikkaan, ett'ei ole heti tehonnut, vaan on se kuitenkin saattanut jälestäpäin vaikuttaa, ja olisihan mahdollista, että metsän kuningas jossain mättään kolossa kuolleena maata mätköttää." "Eipä mahtane kuolleena olla minun luullakseni. Semmoiseltapa sen lähtö näytti, että ihan terveenä se oli." "On siihen kuitenkin vika tullut, koskapahan on verta vuotanut. Saamme tulla aamulla vielä katsomaan, jotta eikö sattuisi sitä löytymään missään." "Ka saisihan tuota tulla. Jos siltä on verta muualle vuotanut kuin tähän, niin sittenhän tuota voitaisiin sen jälille päästä. Mutta jos vaan minun pyssyni on pilattu, niinkuin pelkään, niin kyllä silloin on turha vaiva hakea. Mutta olkoonpa miten tahansa, niin niinhän kuitenkin on tapahtunut kuin on sallittu." "Ka niin. Eihän se tämä asia enää muutu. Mutta eipä tässä vielä varmuudella tiedetä, kuinka on käynytkään. Sittenpähän huomenna nähdään." Vihdoin keskustelunsa lopetettuaan lähtevät vahtaajat kotiapäin astumaan, kun kuitenkin pitävät varmana, ett'ei metsä sinä yönä enää haaskoille tule. Ja kotia tultuaan he heti käyvät levolle, kerran taas yönsä rauhassa nukkumaan monien valvomisien perästä.
  • 70. XI. Seuraavana päivänä Mäntyvaaran miehet, kerrottuaan koko talon väelle, kuinka vahtuu ja ammunta oli huonosti onnistunut, käyvät vielä metsässä katsomassa, eikö sattuisi karhu jostain löytymään. Mutta verijälkiä näkyy ainoastaan siinä paikassa, jossa karhu oli seisonut isännän sitä ampuessa ja monioita vähempiä jälkiä siitä pikkusen matkaa sitä suuntaa kohti, minne karhu oli kadonnut, vaan sittenpä ne jäljet loppuvatkin, katoavat kerrassaan, eikä metsän kuningasta löydetä mistään, ei elävänä eikä kuolleena; ja tyhjin toimin täytyy miesten kotia palata, kun eivät kuitenkaan voi osata karhun olopaikalle. Nyt on isäntä yhä enemmän vakuutettu siinä luulossa, että hänen pyssynsä on pilattu eli lumottu, eikä se siis voi tehota, vaikka kuinka hyvään paikkaan sattuisi käymään. Sen vuoksi hän jo on kyllästynyt koko vahtuuhommaan ja miettii, että toinen tuuma on keksittävä metsän kuninkaan tappamiseksi. Senkin vuoksi on joku muutos tarpeen, koska kovin paljon aikaa menee kahdessa eri paikassa joka yö vahtia pitää. Siinähän menee kahdelta mieheltä aika melkein kokonaan, niin että peltotyöt hyvin huonosti edistyvät. Mutta mikähän tuuma se keksittäisiin? Kun vaan olisi hyvä karhukoira, niin
  • 71. sittenhän ei olisi muuta ajattelemista kuin heti ruveta karhua metsästämään. Vaan mistäpä se semmoinen koira saadaan! Mietteissään istuu isäntä penkillä akkunan kohdalla, polttaen pitkiä lehtiä. Vasta on hän, samoin kuin muu talonväki, einepöydän äärestä noussut, mutta Tiina on kuitenkin aamusta asti karjan paimenena metsää kierrellyt. "Minä tässä ajattelen", sanoo isäntä, hetken äänettömyyden kuluttua, kun Mäntyvaaran väestä kaikki muut paitsi Tiina istuvat koolla pirtissä, pitäen loma-aikaa, ennenkuin leikkuutyöhön lähtevät. "Minä ajattelen, että kyllä jo heitän sikseen kaikki yövahtuut minun osaltani." "No, joko rupeaa kyllästyttämään?" kysyy Kaisu. "Eipä paljon muutenkaan. Ei se teho kuitenkaan minun pyssyni." "Vai ei teho. Niinkö siis todella luulette, että se on pilattu?" "No, niinpä uskon. Olisihan se muuten tappanut, kun viime yönä metsän kuningasta ammuin, ell'ei se olisi ollut pilattu." "Mitenpä se olisi tappanut, kun ei sattunut hyvään paikkaan!" "Sattunut! Ihan vissiin sattui, vaan eihän se tappanut, kun pyssyssä oli vika. — Mutta minä rupean tässä toista tuumaa miettimään." "Mikähän sinulla nyt on mielessä?" huudahtaa emäntä. "Mitenkähän olisi loukas laittaa!"
  • 72. "Loukas!" puuttuu puheeseen Lauri. "Eihän se aivan hullu tuuma ole." "Pistipä isällä hyvä ajatus päähän!" naurahtaa Kaisu. "Metsän petoa ruvetaan pyytämään samalla lailla kuin hiirtä ansalla. Mutta eiköhän mörkö paremmin osaa itseään varoa kuin hiiri!" "Kyllä se sekin joskus saattaa erehtyä, vaikka sillä on miehen mieli", vastaa isäntä. "Ja erehtyyhän se ihminenkin. — Tietävätpähän vanhat ihmiset mainita semmoisista tapauksista, että metsän kuningas on loukkaassa surmansa saanut. Muistanpa minäkin, että minun lapsena ollessani täällä kotonani — juuri tässä talossa — vietettiin mesikämmenen peijaita, ja se oli loukkaassa kuollut." "Tuohan Vanhalan Matti", saapi sanoakseen Mikko, joka äänetönnä on istunut lavitsalla, muista vähän syrjällä, "joka on tunnettu karhun tappaja, kuuluu saaneen joskus loukkaallakin metsän pedon hengiltä." "Onhan se saanut", sanoo Lauri, "puheitten mukaan. Ja kyllä on meidän tehtävä se loukas. Tulisihan se ansaksi sekin ja saattaisi kyllä metsän kuninkaalta hengen ottaa, kun se vaan sattuisi sinne menemään." "Siinäpä se", sanoo Kaisu. "Mutta kyllä se ei sinne mene niin kauan kuin sillä on vielä ne lehmäin raadot syömättä." "Kyllä se silti saattaa mennä", väittää Lauri, "kun pannaan sille oikein hyvä syötti; enkä minä vielä vahtuuta heitä." "Tehkäähän loukas!" kehoittaa Anni. "Ehkäpä sattuisi sitten pyynti paremmin onnistumaan."
  • 73. "Mutta oletteko isä koskaan loukasta nähnyt?" kysyy Lauri. "En minä kyllä nähnyt ole", vastaa isäntä, "vaan olen minä siitä siksi paljon kuullut puhuttavan, jotta tiedän, minkälainen se on. Vivusta en varmaan voisi sanoa, minkälainen se on. Mutta minä ajattelen, että me otamme Vanhalan Matin neuvojaksi ja vivun laittajaksi." "Se kyllä käypi laatuun. Mutta milloinka me rupeamme siihen loukkaan tekoon." "No, laitetaan heti sana Vanhalaan, niin pääsemme työhön käsiksi niin pian kuin Matti tänne ehtii, ehkä huomenna. — Mutta nyt lähtekäämme leikkuuta jatkamaan!" Anni lähtee Vanhalaan sanaa viemään ja toiset hankkiutuvat pellolle lähtemään. Lauri ja isäntä sekä Kaisu lähtevät edeltä, vaan Mikko jo heidän mentyään rupeaa hitaasti pellolle päin astumaan. Emännällä on nyt muuta tekemistä, jottei hän jouda leikkuutyöhön. Tuskin ovat leikkuumiehet saaneet ohraa leikatuksi yhdeksi kuhilaaksi asti, ja Mikko vasta saanut sirpin käteensä, kun Tiina hengästyneenä saapuu pellolle ja jo kaukaa huutaa: "Joutukaa apuun! Mörkö viepi vasikan." "Mitä ihmettä!" kurmnailee isäntä ja heittää leikkuun. "Mitä sinä puhut!" ihmettelee Laurikin. "Onko se tosi?" "No, tosi se on", vastaa Tiina läähättäen ja jo likelle ehdittyään. "Tuolla vaaran rinteellä kun karja oli, niin yht'äkkiä, aivan aavistamattani, mörkö sieppasi vasikan."
  • 74. "Miks'et säikytellyt sitä petoa?" kysyy Kaisu. "Enhän minä kerennyt ja minkäpä olisin sille tehnyt! — Mutta joutukaa pian apuun. Mörkö syöpi Mielikin! Eikö lie jo syönytkin!" Mutta Lauri lähtee heti pirttiin juoksemaan ja hänen jälissään isäntä, ja sieltä he heti sieppaavat pyssynsä ja pikimmältään sanoen emännälle, että mörkö vei vasikan, he ryntäävät taas ulos, Lauri edellä, isäntä jälessä, ja emäntä jääpi kummissaan seisomaan ja toisten kiirettä lähtöä katselemaan. Tiina viittaa miehille suunnan, missä vasikka oli ollut ja sinne rientävät nyt miehet ja heidän jälessään juosta hilkkasee Kaisu ja takimmaisena Tiina, vielä läähättäen äskösestä juoksustaan. Mikko astuu hiljokselleen heidän jälissään pyörtänöä pitkin pellon aidalle asti, ja sinne hän jääpi seisomaan, katsellen, kuinka kauas ne juoksevat. Kartanolla seisoo emäntä katselemassa hänkin ja hän pahoilee mielessään, kun taas vahinko tapahtui karjalle. Kun miehet ja Kaisu sekä Tiina, jotka yhä vaan juoksevat heidän perässään, ehtivät mäkirinteelle sille paikalle, josta vasikka oli kadonnut, niin siellä likellä karja ammoilee kovasti ja näyttää peloissaan olevan. Sen joukossa ei tosiaan enää näy kadonnutta vasikka. Tiina selittää, missä kohti se oli ollut ja minnekkä päin hän luulee mörön sen vieneen. Miehet ajatellen, jotta katosikohan tuo nyt koppinaan, lähtevät metsään rientämään. Siellä he juoksentelevat ja katselevat, jotta eikö satu näkymään joko mörköä tai vasikkaa. Vaimoset eivät lähde heitä hyvin kauas seuraamaan, vaan katseltuaan ja kuunneltuaan likitienoilta, he palaavat takaisin. Lauri ja isäntä sillä aikaa koettavat löytää karhun jälille, vaan turhaan. Karhusta ei näy jälkeäkään missään, eikä vasikan ammontaa kuulu missään. Hetken aikaa haettuaan, haettavaansa
  • 75. löytämättä, he palaavat takaisin ja asettavat pyssynsä paikoilleen pirtin seinälle. Pirtissä ovat nyt kaikki Mäntyvaaran asujat, paitsi Anni, koolla. Vähää ennen miesten tuloa olivat Kaisu ja Tiina sinne tulleet ja emäntä heiltä tarkkaan kyseli siitä vasikan katoamisesta. Nyt ei malta Mikkokaan olla poissa muitten joukosta, vaan lähtee hänkin kuulemaan toisten puheita. "No, eikö löytynyt?" kysyy emäntä heti miesten sisään astuttua. "Eipä", vastaa isäntä ja istahtaa penkille. "Se katosi, se vasikka, kerrassaan, nahkoineen kaikkineen." "No, katosi se", vakuuttaa Lauri, hänkin istumapaikan itselleen valiten. "Ei kuulunut siitä niin ääntäkään, ja metsän kuningas oli siksi viisas, ett'ei pannut puumerkkiään siihen, mistä oli kulkenut." "No, kyllä se pahuus oli sukkela menemään. Kumma oli, mitenkä se pääsi jättämään, vaikka sillä oli elukka kannettavana. Miten tuo lieneekin sitä kantanut, vaan ei siltä kulku kuitenkaan hidastunut, koskapahan emme tavottaneet." "No, oli se tapausta!" lausuu kummissaan emäntä. "Kyllä se oli soma tapaus", päivittelee Tiina. "En tuota ennakolta osannut aavistaa." "Kukapa sitä osasi aavistaa!" sanoo isäntäkin. "Se vasta kummaa oli minusta", puuttuu keskusteluun Mikko, "että se uskalsi ihan paimenen nähden vasikkaan kajota. Enpä ole sattunut kuulemaan, että se koskaan ennen olisi niin tehnyt."
  • 76. "Kyllä oli tapausta tämä", pahoilee yhä emäntä. "Ja kovinhan se tuntuu ikävältä, kun ei karja enää säily paimenenkaan turvissa." "Olihan se ikävä asia", myöntää isäntä, "että joutui Mielikki metsän saaliiksi, ja kyllä mörkö on sen jo niin hyvään paikkaan kätkenyt tai jo syönyt sen suuhunsa nahkoilleen kaikkineen, ett'ei sitä voida enää löytää mistään. Mutta ei tälle asialle enää voida mitään. Se oli niin sallittu ja sen vuoksi se tapahtui. — Näet nyt Kaisu", sanoo hän sitten Kaisun puoleen kääntyen, "ett'ei ole paimenestakaan apua karjalle." "Kyllä siitä on apua", puolustelee Kaisu itseään. "Mutta Tiina ei ollut oikein valpas ja tarkkaavainen." "Minäkö!" huudahtaa Tiina. "Teinhän minä kaikkea mitä voin." "Olisit huutanut ja säikytellyt sitä petoa, kun se rupesi karjaa hätyyttämään." "Enhän minä kerennyt havaitakaan sitä ennenkuin sillä jo oli vasikka kynsissä. Enhän silloin voinut sille mitään eikä olisi toinenkaan minun sijassani mitään saattanut tehdä." "Eihän tämä asia ole Tiinan syy", sanoo isäntä. "Se kun oli kerta määrätty tapahtuvaksi, niin sen täytyi tapahtua, eikä siihen paimen mitään voinut. Eihän kukaan voi sallimukselle mitään." "No, en tiedä", väittää Kaisu. "Mutta kyllä en minä Tiinan sijassa olisi yhtään elukkaa karjasta päästänyt metsän kynsiin." "Oleppa sanomatta!" vastustaa Tiina, "Kun olisit ollut minun sijassani, niin et olisi kerennyt mitään ajatellakaan, ennenkuin jo metsä vasikan kanssa olisi ollut kaukana näkymättömissä."
  • 77. "Älähän! Ei olisi metsä tullut likellenikään, kun minä olisin aina huutanut tai laulellut." "No, mitä tuossa tyhjää intätte!" virkkoo isäntä. "Tämä asia ei kuitenkaan muutu. Se tapahtui niinkuin oli sallittu." "Niin", myöntää emäntä. "Tulihan tosin vahinko, vaan minkäpä sille tekee! Se oli sallittu. Mutta, Tiina, saat sinä vielä mennä paimeneksi; sillä karja peloissaan ammoilee tuolla vaaran rinteellä, eikä uskalla mihinkään liikkua paimenetta." "Tosiaan", sanoo isäntäkin, "saapi karjalla olla paimen sen vuoksi, että karja paremmin uskaltaisi kulkea ruokaisemmilla paikoilla, mutta ei suinkaan sen vuoksi, että paimenesta olisi mitään apua karjalle mörköä vastaan." "Saisihan tuonne mennä paimeneksi", sanoo Tiina, "mutta jos se mörkö vielä päälle tulee." "Siitä ei ole pelkoa", keskeyttää isäntä Tiinan puhetta. "Harvoinpa se ihmisen päälle tulee." "Entäpä jos nyt tulisi, koska se on jo niin rohkeaksi tullut, että uskaltaa karjaan kajota paimenen nähden." "Ole huoleti! Sinun päällesi se ei tule, kun et sinä voi sitä millään aseella uhata. Menehän nyt! Me muut täältä lähdemme taas leikkaamaan, — ja huomenna rupeamme loukkaan tekoon, jotta eikö sattuisi mörkö sinne menemään ja siellä surmansa saamaan." Niin poistuu kukin töihinsä, mielessään usein ajatellen karhujuttua. Pienokaiset vaan, mistään huolehtimatta, leikkivät iloisina kartanon hietikolla.
  • 78. XII. Seuraavan päivän aamulla Mäntyvaaran isäntä, Lauri sekä Vanhalan Matti lähtevät loukkaan tekoon. He astuvat karhun vahtuun vuoksi jo usein kulettuja seutuja, ensin rantatietä myöten ja kääntyvät sitten vasemmalle ja kulkevat tiheän metsikön kautta sitä suuntaa kohti, missä haaskat ovat. Etummaisena astuu Lauri, sitten isäntä ja takimmaisena Matti. Enimmästä keskustelutta kuluu matka ja varsinkin Matti, joka on harvapuheinen, jäykkäluontoinen vanhus, ei monta sanaa sano. Miehet valitsevat metsässä paikan likelle niitä seutuja, missä lehmäin raadot ovat, vaan vähän ylemmäksi, kuivemmalle maalle. Siellä he rupeavat puita jystämään ja hakkaavat sylen pituisia hirtten tapaisia palkkeja joko kasvavista puista tai osaksi myös siellä täällä olevista kaatuneista hongista. Isännän ja Laurin kirveet enite jälkeä tekevät ja Matti vaan tekee pienempiä veistotöitä sekä antaa toisille tarvittaessa neuvoja ja auttaa heitä isompia puita kuljetettaessa. Kuuluu nyt kirveitten kalketta ja puitten pauketta palkkeja tehdessä; sillä semmoisessa työssä ei jyskettä saateta välttää; ja metsän kuningas, jos vaan mailla lienee, saapi kummissaan kuunnella ja ajatella, jotta mikä se nyt semmoista jytäkkää pitää sen ennen rauhaisan ruokapaikan läheisyydessä. Kuluu aikaa melkonen palkkeja
  • 79. tehdessä, niitä kun tarvitaan koko joukko, vaan kun arvellaan niiden riittävän, ruvetaan niistä loukkaalle seiniä tekemään. Ne ladotaan pystyyn maata vasten ihan toistensa viereen kolmeksi seinäksi eli sivuksi, niin että kaksi seinää tulee yhtäsuuntaisiksi toistensa kanssa ja kolmas yhdistää niiden päät toisiinsa, vaan yksi sivu jääpi siis avoimeksi. Tälle neljännelle sivulle vedetään iso kokonainen hirsi ja asetetaan maata pitkin ikäänkuin kynnykseksi loukkaalle, niin että tyvipuoli koskettaa molempia yhtäsuuntaisia seiniä, vaan latvapuoli ulottuu kauas niiden ulkopuolelle. Vielä tarvitaan tätä loukkaan etusivua varten hirsi tai kaksi; mutta, ennenkuin ne hakataan ja tuodaan määräpaikkoihinsa, on Matti ukko ruvennut vivun tekoon. Hän veistelee kaikenlaisia palukoita, jotka tarvitaan vipua varten, ja on työhönsä niin kiintynyt, ett'ei paljon jouda ympärilleen silmäellä eikä sekaantua isännän ja Laurin puheisiin. Nämä kun tuumaavat ja miettivät, mitenkä mikin on tehtävä, niin ukko vaan äänetönnä työtään toimittaa, eikä hän muulloin kuin toisten jotain kysyessä lyhyesti jonkun sanan vastaukseksi ärähtää, ja vaikka hän näkee, ett'eivät aina älyä, mitä varten hän mitäkin tekee, niin ei hän kuitenkaan ennen aikojaan selityksiin rupea; hän olla jöröttää vaan vakavana ja totisena ja tekee työnsä varmana kuin kokenut mestari ainakin. Matin veistäessä ja vuollessa vipulaitokseen tarvittavia kaluja, ovat isäntä ja Lauri puuhassa isoa hirttä valmistaessaan. Kun se on valmis kuljetettavaksi, tuumaa isäntä Laurille, hirttä kohottaessaan: "Tuskin tämä kahden miehen saadaankaan paikoilleen." "Näkyy tässä painoa olevan", vastaa Lauri, hänkin hirttä kohottaessaan.
  • 80. "Raskas tämä raato on", huutaa isäntä Matille. "Etköhän Matti tulisi avustamaan!" "Vai raskaalta tuntuu", vastaa Matti. "No, minä tulen täältä heti." Kolmen miehen vedetään sitten hirsi loukkaan eteen ja siinä kantajat eli vetäjät heittävät taakan käsistään ja niin pudota romahtaa hirsi maahan toisen viereen. Siihen se sitten jätetään vähäksi aikaa, ennenkuin se nostetaan siihen paikkaan, mihin se on pantava. Ennenkuin nyt isäntä ja Lauri muihin töihin rupeavat, käyvät he toisen haaskan purkamassa ja tuovat sitten koko haisevan lehmänraadon loukkaan lähelle, jotta Matti saisi siitä syöttiä ottaa loukkaaseen karhua varten pantavaksi. Matilla alkaa nyt vipulaitos olla lopulleen valmis. Loukkaan sisälle peräseinään on hän kiinnittänyt puukoukun, johon syötti tulee pantavaksi, ja siitä johtuu vipu etusivulle, siinä olevan hirren tyvipuolen kohdalle. Kun lehmän raato on tuotu siihen likelle, niin Matti leikkaa raadosta pään erilleen, jonka hän vielä halkaisee ja panee sitten toisen puoliskon, johon myös kieli on jäänyt, puukoukkuun. Isännälle ja Laurille, jotka katselevat hänen hommaansa, sanoo hän: "Päällystäkäähän loukas kokonaan havuilla ja katsokaa, että joka paikka tulee niin hyvin peitetyksi, ett'ei vieras katsoja voi ollenkaan tietää niiden peitossa minkään rakennuksen olevan!" Niin ruvetaankin loukasta havuilla peittämään ja sillä aikaa Matti lehmän raatoa silpoilee sekä syytää siitä palan palan perästä loukkaan sisälle ja etupuolellekin. Ne ovat sitä varten, että karhu, jos se kerta sille mieluisesta hajusta vieteltynä tulisi loukkaalle, rupeaisi
  • 81. nuuskimaan ja syömään siellä täällä olevia paloja, joista se pääsisi hyvään makuun, eikä sitten malttaisi olla syömättä syöttiä puukoukusta. Vihdoin, kun loukas on kokonaan havuilla peitetty, niin että se on aivan kuin havumaja, viritetään vipu. Se hirsi, joka äsken tuotiin, nostetaan toisen hirren päälle, joka oli pantu loukkaalle kynnykseksi, siten että latvat tulevat päällekkäin, vaan ylemmäisen hirren tyvipuoli kohotetaan, joten aukko tulee hirtten väliin, ja tähän väliin asettaa nyt Matti kepin oli palukan pystyyn päällimmäistä hirttä kannattamaan. Tämä palukka on yhteydessä vipulaitoksen kanssa, joka on sillä lailla laitettu, että, jos se sattuu liikahtamaan, silloin heti hirttä kannattava palukka kaatuu ja samalla hirsi alas romahtaa. Kun nyt loukas on valmis ja vipu viritetty, tuumaa isäntä, loukasta ja vipua katsellen: "Tämmöinen se nyt tuli ansa metsän kuninkaalle. Nyt ei puutu muuta kuin että se metsän peto tulisi tähän ansaan, niin sittenhän ne tulisivat jo vaivat palkituiksi." "Ka, sehän tässä on toivottava", vastaa Lauri, hänkin vipulaitosta tarkkaan katsoen. "On tämä somanen laitos, ja tässä se salojen eläjä pian saattaa surmansa saada." "Hetihän sen täytyy henkensä heittää, kun se tulee tuohon syöttiin koskemaan." "Niin, ensin se tästä ulkopuolelta syöpi mitä löytää ja tuolta sisältä se tietysti myöskin rupeaa lihapalasia maistelemaan, pistäen turpansa tästä välistä tuonne sille. No, sitten sillä tekee mieli tuota pään puoliskoa tuolta puukoukusta. Mutta sinne ei sen kuono uletukaan."
  • 82. "Silloin se toisella jalallaan astuu tästä alushirren yli ja nyt se saattaa suullaan koskettaa syöttiä." "Vaan kun syötti on lujasti kiinni sidottu, niin se rupeaa sitä retuuttamaan, irti saadakseen." "Mutta eipä irtaukaan syötti helposti; se näkyy hyvin lujaan olevan nuoralla sidottu." "Ja kun se sitä retuuttaa, niin silloin puukoukku liikahtaa ja vipu laukeaa. Tämä palukka tässä paikoiltaan solahtaa ja samalla tämä vankka hirsi mörön niskaan pudota romahtaa." "No, se vasta rymäystä on!" "Ka, siinä tulee semmoinen paino mörkö paran päälle, jotta —" "Heh! Paikallahan se kuoliaaksi litistyy." "Ei auta sillä voimain ponnistukset enää." "Ka, hetihän tuommoinen paino siltä hengen viepi." "Se on tietty", puuttuu puheeseen Matti. "Sen päälle tulee niin raskas paino, ett'ei se ennätä parahtaakaan. — Mutta hyvä on kuitenkin, että pannaan paljon painoa. Otetaanpa tuolta viellä tuo vanha hirsiremu, joka tuossa likellä näkyy, ja pannaan se lisäpainoksi!" "No, so kun vielä pannaan", sanoo isäntä, "niin kyllä sitten —." "Kyllä sitten jo tulee painoa", lausuu Lauri.
  • 83. Tuodaan sitten se vanha jo melkein lahonnut hirsi ja nostetaan sekä kiinnitetään lisäpainoksi painohirren päälle. Sittenpä se loukas vihdoin saadaan semmoisekseen jättää. Mutta Matin palasiksi silpoma lehmän raato on johonkin korjattava. "Mihinkä ne nämä pannaan?" kyselee Lauri raadon paloja kosketellen. "Eihän näitä metsälle suinkaan syötäviksi jätetä?" "Ei toki", vastaa Matti. "Kyllä ne pois korjataan." "Poishan ne ovat korjattavat", sanoo isäntäkin. "Maahan niitä olisi hyvä kätkeä, mutta sanotaanpa metsän niitä ylös kaivavan." "Ei niitä maahan panna", sanoo Matti. "Sieltä kyllä metsä ne pian ylös kaivaa." "No, puuhun ne vissiin pannaan", sanoo Lauri. "Mutta kyllähän se mörkö ne sieltäkin saattaa saada." "Pääseehän se puuhun kyllä vähän matkaa", myöntää Matti. "Vaan kun ne viedään korkealle ylemmille oksille, niin kyllä pysyvät siellä." "Niinpä luulisi", arvelee isäntäkin. Kun sitten lehmän raadon palaset ovat ripustetut läheisten puitten oksille niin korkealle kuin mahdollista sekä loukkaan teossa syntyneet lastut huolellisesti havuilla peitetyt, niin miehet, tyytyväisinä työnsä päättymisestä, lähtevät kotia päin astumaan. Peräkkäin he astuvat taas, samassa järjestyksessä kuin olivat tulleetkin, mutta nyt he ovat iloisemmalla mielellä, isäntä varsinkin,
  • 84. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com