Skip to content

08 · The Service Layer

In the previous lesson, Pydantic turned untrusted browser JSON into a validated DocumentCreate object.

Our route still performed the actual document-creation work:

document_id = max(documents_by_id) + 1
document = {
"id": document_id,
"firm_id": current_user["firm_id"],
"title": payload.title,
...
}
documents_by_id[document_id] = document

Today we move that work into a service layer.

The lifecycle becomes:

Browser
→ middleware
→ router
→ authentication dependency
→ Pydantic validation
→ route
→ service
→ temporary storage
→ service
→ route
→ response
→ browser

The route will handle HTTP. The service will handle the business operation.


We’ll add another package:

app/
├── main.py
├── data.py
├── dependencies.py
├── security.py
├── schemas/
│ └── documents.py
├── services/
│ ├── __init__.py
│ └── documents.py
└── routers/
└── documents.py

The main responsibilities are now:

schemas/documents.py
└── What data may enter or leave
routers/documents.py
└── How HTTP requests and responses are handled
services/documents.py
└── What creating a document means to the application
data.py
└── Where data is temporarily stored

The service layer is not a FastAPI feature. It is an architectural boundary made from ordinary Python code.

FastAPI does not require it. We introduce it because real business operations eventually become too important and complicated to bury inside route functions.


Here is app/services/documents.py:

from ..data import documents_by_id
class DuplicateDocumentTitleError(Exception):
def __init__(self, title: str):
self.title = title
super().__init__(
f'A document named "{title}" already exists'
)
def create_document(
*,
firm_id: int,
created_by_user_id: int,
title: str,
document_type: str,
priority: int,
) -> dict:
normalized_title = title.casefold()
for existing_document in documents_by_id.values():
belongs_to_firm = (
existing_document["firm_id"] == firm_id
)
has_same_title = (
existing_document["title"].casefold()
== normalized_title
)
if belongs_to_firm and has_same_title:
raise DuplicateDocumentTitleError(title)
document_id = max(
documents_by_id,
default=100,
) + 1
document = {
"id": document_id,
"firm_id": firm_id,
"created_by_user_id": created_by_user_id,
"title": title,
"document_type": document_type,
"priority": priority,
"status": "not_started",
}
documents_by_id[document_id] = document
return document

This function represents one application use case:

Create a document for review.

It does more than insert arbitrary values into a dictionary.

It:

  1. Checks a business rule.
  2. Assigns the record to the correct firm.
  3. Records who created it.
  4. Chooses its initial status.
  5. Generates an identifier.
  6. Stores the record.
  7. Returns the created document.

The route does not need to know how those decisions are made.


The function begins:

def create_document(

There is no decorator:

@router.post(...)

There is no:

Request
Response
HTTPException
Depends

The service is not an HTTP endpoint.

A browser cannot request:

/services/documents/create_document

The function exists only inside the Python application. Something else—currently our route—must call it.

This is the same distinction we established with APIRouter:

Python file or function name
≠
public URL

The function signature contains a standalone asterisk:

def create_document(
*,
firm_id: int,
created_by_user_id: int,
title: str,
document_type: str,
priority: int,
) -> dict:

The * means every argument after it must be passed by name.

This works:

create_document(
firm_id=10,
created_by_user_id=1,
title="September Website Review",
document_type="website",
priority=4,
)

This does not:

create_document(
10,
1,
"September Website Review",
"website",
4,
)

Why require names?

Without them, this call is difficult to read:

create_document(
10,
1,
"September Website Review",
"website",
4,
)

You must remember what 10, 1, and 4 mean.

Keyword arguments make the data movement visible:

firm_id=10
created_by_user_id=1
priority=4

They also reduce the chance of accidentally reversing two integer arguments.


The service begins by normalizing the title for comparison:

normalized_title = title.casefold()

casefold() produces a case-insensitive comparison form.

For example:

"September Website Review".casefold()

becomes:

"september website review"

The service then examines the existing documents:

for existing_document in documents_by_id.values():

The dictionary contains document IDs as keys:

{
101: {...},
202: {...},
}

Calling:

documents_by_id.values()

gives us the document dictionaries without their keys.

For each existing document, the service calculates two Booleans:

belongs_to_firm = (
existing_document["firm_id"] == firm_id
)

and:

has_same_title = (
existing_document["title"].casefold()
== normalized_title
)

The service rejects the operation only when both are true:

if belongs_to_firm and has_same_title:

This expresses the business rule:

A firm may not have two documents with the same case-insensitive title.

Different firms may use the same title.

For example:

Firm 10: September Website Review
Firm 20: September Website Review

That is allowed because their firm_id values differ.

But within firm 10, these are treated as duplicates:

September Website Review
SEPTEMBER WEBSITE REVIEW
september website review

Pydantic could verify that a title is a valid string of an acceptable length. It could not decide whether the title conflicts with an existing document without examining application state.

That distinction is important:

Pydantic validation
└── Is this title structurally valid?
Service-layer rule
└── May this firm create this document now?

If the title conflicts, the service raises:

raise DuplicateDocumentTitleError(title)

The exception is defined above the service:

class DuplicateDocumentTitleError(Exception):

It inherits from Python’s built-in Exception.

Its initializer receives the conflicting title:

def __init__(self, title: str):

It stores that value:

self.title = title

Then it initializes the base exception:

super().__init__(
f'A document named "{title}" already exists'
)

This gives the exception a readable message.

Conceptually, the service is reporting:

I could not complete the requested business operation
because the firm already has this document title.

It does not report:

Return HTTP status 409.

That decision belongs to the HTTP layer.


Why the service does not raise HTTPException

Section titled “Why the service does not raise HTTPException”

We could write:

raise HTTPException(
status_code=409,
detail="Document title already exists",
)

But that would make the service aware of FastAPI and HTTP.

Imagine that document creation is later initiated by:

  • An HTTP route
  • A command-line import
  • A scheduled background job
  • A test
  • An administrative script

Only the route speaks HTTP.

A command-line importer has no meaningful use for:

409 Conflict

By raising an application-specific exception:

DuplicateDocumentTitleError

the service communicates what happened without deciding how every caller must present it.

Different callers can translate it differently:

FastAPI route
→ 409 response
Command-line script
→ Print an error and skip the row
Background job
→ Record a failed job result
Test
→ Assert that the exception was raised

That makes the service reusable without turning it into a vague collection of generic helper functions.


If no duplicate exists, execution continues:

document_id = max(
documents_by_id,
default=100,
) + 1

This generates our temporary identifier.

Then the service builds the record:

document = {
"id": document_id,
"firm_id": firm_id,
"created_by_user_id": created_by_user_id,
"title": title,
"document_type": document_type,
"priority": priority,
"status": "not_started",
}

Some values came indirectly from the browser:

title
document_type
priority

Those values passed through Pydantic first.

Other values are controlled by the server:

firm_id
created_by_user_id
status

The browser is not trusted to assign them.

In particular:

"status": "not_started"

is a business decision.

Every new document begins with status="not_started": no review has been requested yet. This business status is separate from the active waiting state introduced when we start background work. The browser does not get to submit:

{
"status": "approved"
}

Finally, the service saves and returns the record:

documents_by_id[document_id] = document
return document

Our dictionary is still standing in for the database. When SQLAlchemy arrives, this section will eventually look more like:

db.add(document)
db.commit()
db.refresh(document)
return document

The service’s purpose will remain the same even though its persistence mechanism changes.


Here is the revised route:

from fastapi import APIRouter, HTTPException, status
from ..dependencies import CurrentUserDep
from ..schemas.documents import (
DocumentCreate,
DocumentRead,
)
from ..services.documents import (
DuplicateDocumentTitleError,
create_document,
)
router = APIRouter(
prefix="/documents",
tags=["documents"],
)
@router.post(
"/",
response_model=DocumentRead,
status_code=status.HTTP_201_CREATED,
)
async def create_document_route(
payload: DocumentCreate,
current_user: CurrentUserDep,
):
try:
document = create_document(
firm_id=current_user["firm_id"],
created_by_user_id=current_user["id"],
title=payload.title,
document_type=payload.document_type,
priority=payload.priority,
)
except DuplicateDocumentTitleError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=str(exc),
) from exc
return document

The route function is now named:

create_document_route

That distinguishes it from the imported service function:

create_document

The names reflect different responsibilities:

create_document_route()
└── HTTP endpoint
create_document()
└── Application operation

The route’s first responsibility: receive prepared inputs

Section titled “The route’s first responsibility: receive prepared inputs”

FastAPI prepares:

payload: DocumentCreate

from the JSON body.

It also prepares:

current_user: CurrentUserDep

through dependency injection.

The route therefore begins with:

A validated document-creation request
+
An authenticated current user

If Pydantic validation fails, the route does not run.

If authentication fails, the route does not run.

The service is only called after both prerequisites succeed.


The route calls:

document = create_document(
firm_id=current_user["firm_id"],
created_by_user_id=current_user["id"],
title=payload.title,
document_type=payload.document_type,
priority=payload.priority,
)

This is where two separately prepared objects are combined.

From the authenticated user:

current_user["firm_id"]
current_user["id"]

From the validated request body:

payload.title
payload.document_type
payload.priority

The route acts as an adapter:

FastAPI-shaped inputs
→ ordinary Python arguments

The service does not know that payload was constructed from JSON or that current_user was discovered through a cookie.

It receives the specific values it needs.


The service call is wrapped in:

try:
...
except DuplicateDocumentTitleError as exc:
...

Python first executes the code inside try.

If the service succeeds, the except block is skipped.

If the service raises:

DuplicateDocumentTitleError

Python jumps into the matching except block:

except DuplicateDocumentTitleError as exc:

The variable:

exc

refers to the exception object.

The route translates it into an HTTP concept:

raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=str(exc),
) from exc

A 409 Conflict communicates that the request was understandable and structurally valid, but it conflicted with the current application state.

The response resembles:

HTTP/1.1 409 Conflict
Content-Type: application/json
{
"detail": "A document named \"September Website Review\" already exists"
}

This is different from Pydantic’s 422 response:

422
→ The submitted data did not satisfy the input schema.
409
→ The data was valid, but the requested operation conflicted
with existing application state.

The final portion is:

from exc

The full statement is:

raise HTTPException(...) from exc

This creates an explicit exception chain.

It records:

HTTPException was raised
because DuplicateDocumentTitleError occurred

The browser does not receive the internal exception chain.

But logs and debugging tools can preserve the relationship between the service failure and its HTTP translation.

Without from exc, the route would still return the intended HTTP response. Including it provides clearer internal causality.


If the service succeeds:

return document

The dictionary may contain:

{
"id": 203,
"firm_id": 10,
"created_by_user_id": 1,
"title": "September Website Review",
"document_type": "website",
"priority": 4,
"status": "not_started",
}

But the route declares:

response_model=DocumentRead

Our existing response schema contains:

class DocumentRead(BaseModel):
id: int
firm_id: int
title: str
document_type: DocumentType
priority: int

Therefore, the browser receives:

{
"id": 203,
"firm_id": 10,
"title": "September Website Review",
"document_type": "website",
"priority": 4
}

The internal field:

created_by_user_id

is not exposed.

Neither is:

status

unless we deliberately add it to DocumentRead.

This gives us another clean boundary:

Service result
→ may contain internal application data
Response model
→ explicitly defines public response data

Suppose the browser submits:

POST /documents/
Content-Type: application/json
Cookie: app_session=...
{
"title": "September Website Review",
"document_type": "website",
"priority": 4
}

The full execution sequence is:

  1. The browser serializes its JavaScript data as JSON.
  2. The browser sends the JSON and session cookie.
  3. The server receives the HTTP request.
  4. Session middleware verifies the cookie.
  5. FastAPI’s router selects create_document_route.
  6. The authentication dependency retrieves the current user.
  7. FastAPI parses the request body.
  8. Pydantic validates and constructs DocumentCreate.
  9. FastAPI calls the route with both prepared objects.
  10. The route extracts authoritative user information.
  11. The route passes plain Python values into the service.
  12. The service checks for a duplicate title within the firm.
  13. The service chooses the document ID and initial status.
  14. The service stores the document in the temporary dictionary.
  15. The service returns the document.
  16. The route returns the service result.
  17. FastAPI filters and serializes it through DocumentRead.
  18. FastAPI creates a 201 Created response.
  19. The response travels outward through middleware.
  20. The server sends it to the browser.
  21. The browser parses the JSON response.

The route coordinates the request. The service performs the use case.


If a document with that title already exists:

Pydantic validation succeeds
↓
Authentication succeeds
↓
Route calls service
↓
Service examines application state
↓
Duplicate title found
↓
Service raises DuplicateDocumentTitleError
↓
Route catches it
↓
Route translates it into HTTP 409
↓
Browser receives the conflict response

The route entered because the input was structurally valid.

The operation failed later because business state made it unacceptable.

This is why Pydantic cannot replace the service layer.


Why not put the business rule in the route?

Section titled “Why not put the business rule in the route?”

We could keep everything together:

@router.post("/")
async def create_document_route(...):
# Authenticate
# Validate
# Search for duplicates
# Generate an ID
# Choose the initial status
# Store the document
# Format errors
# Build the response

That may be acceptable for a tiny prototype.

But routes tend to grow through accumulation. A real document-submission operation might eventually need to:

  • Confirm the firm’s subscription
  • Enforce document limits
  • Create an audit record
  • Save an uploaded file
  • Schedule an AI review
  • Record processing status
  • Notify a reviewer
  • Handle failures consistently

If all of that lives inside the route, the HTTP layer becomes the application.

Moving the use case into a service gives that workflow a clear home.


A services/ directory should not become a dumping ground for every function that does not fit elsewhere.

This is probably not a meaningful service:

def lowercase_title(title: str) -> str:
return title.lower()

That is merely a small utility.

A service generally represents an application action or workflow:

create_document()
submit_document_for_review()
approve_document()
archive_document()
invite_firm_user()

The name usually describes something the application does for a user or another system.

The service coordinates rules and state changes. It is not simply “a function stored in the services folder.”


Our service imports:

from ..data import documents_by_id

That means the service is still directly coupled to its storage mechanism.

For this stage, that keeps the example understandable.

Later we will replace the global dictionary with an explicit SQLAlchemy session:

def create_document(
*,
db: Session,
firm_id: int,
created_by_user_id: int,
...
):

The route will receive the database session through Depends and pass it into the service.

That will make the data dependency visible:

Route
├── validated payload
├── authenticated user
└── database session
↓
service

For today, the important new boundary is already present:

Router
└── HTTP translation and orchestration
Service
└── Business operation and rules

A route answers:

How should this HTTP request enter and leave the application?

A service answers:

What does the requested operation actually mean?

For document creation:

Route
→ Receive validated input
→ Identify the authenticated actor
→ Call the appropriate service
→ Translate results and failures into HTTP
Service
→ Enforce business rules
→ Add server-controlled values
→ Change application state
→ Return the result

The next layer is SQLAlchemy. We’ll replace the temporary dictionary with a real SQLite database and follow one request through a SQLAlchemy Session, an ORM model, generated SQL, a transaction, and durable storage.