Chapter 9. Service Layer

What was that middle thing?

Otto West, A Fish Called Wanda

Preview

This chapter expands on the Service layer—the middle thing. A leaky roof can cost a lot of money. Leaky software isn’t as obvious but can cost a lot of time and effort. How can you structure your application so that the layers don’t leak? In particular, what should and should not go into the Service layer in the middle?

Defining a Service

The Service layer is the heart of the website, its reason for being. It takes requests from multiple sources, accesses the data that is the DNA of the site, and returns responses.

Common service patterns include a combination of the following:

  • Create / retrieve / change (partially or completely) / delete

  • One thing / multiple things

At the RESTful router layer, the nouns are resources. In this book, our resources will initially include cryptids (imaginary creatures) and people (cryptid explorers).

Later, it will be possible to define related resources like these:

  • Places

  • Events (e.g., expeditions, sightings)

Layout

Here’s the current file and directory layout:

main.py
web
├── __init__.py
├── creature.py
├── explorer.py
service
├── __init__.py
├── creature.py
├── explorer.py
data
├── __init__.py
├── creature.py
├── explorer.py
model
├── __init__.py
├── creature.py
├── explorer.py
fake
├── __init__.py
├── creature.py
├── explorer.py
└── test

In this chapter, you’ll fiddle with files in the service directory.

Protection

One nice thing about ...

Get FastAPI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.