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] = documentToday 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→ browserThe route will handle HTTP. The service will handle the business operation.
Where the service sits
Section titled “Where the service sits”We’ll add another package:
app/├── main.py├── data.py├── dependencies.py├── security.py├── schemas/│ └── documents.py├── services/│ ├── __init__.py│ └── documents.py└── routers/ └── documents.pyThe 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 storedThe 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.
The service code
Section titled “The service code”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 documentThis function represents one application use case:
Create a document for review.It does more than insert arbitrary values into a dictionary.
It:
- Checks a business rule.
- Assigns the record to the correct firm.
- Records who created it.
- Chooses its initial status.
- Generates an identifier.
- Stores the record.
- Returns the created document.
The route does not need to know how those decisions are made.
The service is ordinary Python
Section titled “The service is ordinary Python”The function begins:
def create_document(There is no decorator:
@router.post(...)There is no:
RequestResponseHTTPExceptionDependsThe service is not an HTTP endpoint.
A browser cannot request:
/services/documents/create_documentThe 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 URLKeyword-only arguments
Section titled “Keyword-only arguments”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=10created_by_user_id=1priority=4They also reduce the chance of accidentally reversing two integer arguments.
A business rule belongs in the service
Section titled “A business rule belongs in the service”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 ReviewFirm 20: September Website ReviewThat is allowed because their firm_id values differ.
But within firm 10, these are treated as duplicates:
September Website ReviewSEPTEMBER WEBSITE REVIEWseptember website reviewPydantic 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?The custom service exception
Section titled “The custom service exception”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 = titleThen 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 operationbecause 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 ConflictBy raising an application-specific exception:
DuplicateDocumentTitleErrorthe 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 raisedThat makes the service reusable without turning it into a vague collection of generic helper functions.
Creating the document
Section titled “Creating the document”If no duplicate exists, execution continues:
document_id = max( documents_by_id, default=100,) + 1This 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:
titledocument_typepriorityThose values passed through Pydantic first.
Other values are controlled by the server:
firm_idcreated_by_user_idstatusThe 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 documentOur 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 documentThe service’s purpose will remain the same even though its persistence mechanism changes.
The route becomes an adapter
Section titled “The route becomes an adapter”Here is the revised route:
from fastapi import APIRouter, HTTPException, status
from ..dependencies import CurrentUserDepfrom ..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 documentThe route function is now named:
create_document_routeThat distinguishes it from the imported service function:
create_documentThe names reflect different responsibilities:
create_document_route()└── HTTP endpoint
create_document()└── Application operationThe route’s first responsibility: receive prepared inputs
Section titled “The route’s first responsibility: receive prepared inputs”FastAPI prepares:
payload: DocumentCreatefrom the JSON body.
It also prepares:
current_user: CurrentUserDepthrough dependency injection.
The route therefore begins with:
A validated document-creation request+An authenticated current userIf 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.
Mapping HTTP input into the service call
Section titled “Mapping HTTP input into the service call”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.titlepayload.document_typepayload.priorityThe route acts as an adapter:
FastAPI-shaped inputs→ ordinary Python argumentsThe 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.
Translating the service error into HTTP
Section titled “Translating the service error into HTTP”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:
DuplicateDocumentTitleErrorPython jumps into the matching except block:
except DuplicateDocumentTitleError as exc:The variable:
excrefers to the exception object.
The route translates it into an HTTP concept:
raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=str(exc),) from excA 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 ConflictContent-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.What from exc means
Section titled “What from exc means”The final portion is:
from excThe full statement is:
raise HTTPException(...) from excThis creates an explicit exception chain.
It records:
HTTPException was raisedbecause DuplicateDocumentTitleError occurredThe 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.
The successful response
Section titled “The successful response”If the service succeeds:
return documentThe 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=DocumentReadOur existing response schema contains:
class DocumentRead(BaseModel): id: int firm_id: int title: str document_type: DocumentType priority: intTherefore, the browser receives:
{ "id": 203, "firm_id": 10, "title": "September Website Review", "document_type": "website", "priority": 4}The internal field:
created_by_user_idis not exposed.
Neither is:
statusunless 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 dataThe complete successful lifecycle
Section titled “The complete successful lifecycle”Suppose the browser submits:
POST /documents/Content-Type: application/jsonCookie: app_session=...
{ "title": "September Website Review", "document_type": "website", "priority": 4}The full execution sequence is:
- The browser serializes its JavaScript data as JSON.
- The browser sends the JSON and session cookie.
- The server receives the HTTP request.
- Session middleware verifies the cookie.
- FastAPI’s router selects
create_document_route. - The authentication dependency retrieves the current user.
- FastAPI parses the request body.
- Pydantic validates and constructs
DocumentCreate. - FastAPI calls the route with both prepared objects.
- The route extracts authoritative user information.
- The route passes plain Python values into the service.
- The service checks for a duplicate title within the firm.
- The service chooses the document ID and initial status.
- The service stores the document in the temporary dictionary.
- The service returns the document.
- The route returns the service result.
- FastAPI filters and serializes it through
DocumentRead. - FastAPI creates a
201 Createdresponse. - The response travels outward through middleware.
- The server sends it to the browser.
- The browser parses the JSON response.
The route coordinates the request. The service performs the use case.
The duplicate-title lifecycle
Section titled “The duplicate-title lifecycle”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 responseThe 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 responseThat 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.
What a service layer should not become
Section titled “What a service layer should not become”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.”
The current tradeoff
Section titled “The current tradeoff”Our service imports:
from ..data import documents_by_idThat 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 ↓ serviceFor today, the important new boundary is already present:
Router└── HTTP translation and orchestration
Service└── Business operation and rulesThe central idea
Section titled “The central idea”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 resultThe 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.