On this page

FastAPI Service Layer: Separating Business Logic from Routes

Published on August 10, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A service layer is the architectural boundary between HTTP routing and business logic. Route handlers deal with HTTP concerns — status codes, request parsing, response serialization. Service functions deal with domain concerns — database queries, business rules, data transformation. Keeping these two responsibilities apart produces code that's easier to test, easier to reuse across routes, and easier to extend without breaking behavior elsewhere.

This article builds a complete service layer for the Task Manager API and explains the design principles behind it.


Why the Separation Matters​

Without a service layer, route handlers accumulate responsibility until a single endpoint function ends up parsing the request, validating business rules, querying the database, handling errors, and formatting the response — all in one place. As an application grows, this becomes difficult to test, since exercising any of that logic means the full HTTP stack has to be running, and impossible to reuse, since the same query logic ends up duplicated across every route that needs it.

A service layer enforces two established software design principles. The Single Responsibility Principle says each module has one reason to change: a route changes when the HTTP contract changes, a service changes when the business rules change, and keeping them apart means changing one never forces touching the other. The Dependency Inversion Principle says high-level modules — routes — should depend on abstractions, not low-level detail: a route doesn't need to know or care how list_tasks fetches its data, only that calling it returns a list.


What Belongs Where​

ConcernWhere it livesHTTP status codesRouterRequest body parsingRouter (FastAPI handles this automatically)Response serializationRouter (response_model)HTTPException (404, 400, 403)RouterDatabase queriesServiceBusiness rules and validationServiceData transformationServiceRaising Python exceptions on domain errorsService

The rule that matters most here: services must never import or raise HTTPException. HTTPException is an HTTP-layer concern — it carries an HTTP status code and a response body, and a service function has no business knowing it's being called from an HTTP API at all. It might be called from a CLI tool, a background job, or a test just as easily. Raising HTTPException from inside a service permanently couples it to FastAPI's HTTP protocol, making it impossible to reuse or test independently of a running API. Services raise standard Python exceptions instead, and the router is where those get translated into the right HTTPException.


Project Structure​


project/

├── main.py

├── db.py

├── models/

│   └── task.py

├── routers/

│   └── tasks.py     ← HTTP concerns only

└── services/

    └── task_service.py  ← Business logic only

The Task Model and Patch Schema​


from sqlmodel import SQLModel, Field

from pydantic import BaseModel



class Task(SQLModel, table=True):

    id: int | None = Field(default=None, primary_key=True)

    title: str

    description: str | None = Field(default=None)

    completed: bool = Field(default=False)



class TaskPatch(BaseModel):

    title: str | None = None

    description: str | None = None

    completed: bool | None = None

TaskPatch is a plain Pydantic model with every field optional, used by the PATCH endpoint to accept partial updates — model_dump(exclude_unset=True) on an instance of it returns only whichever fields the client actually sent.


The Service Layer​


from sqlmodel import Session, select

from models.task import Task, TaskPatch



# Service functions raise standard Python exceptions, never HTTPException.

# The router is responsible for translating these into HTTP responses.



def get_task_by_id(task_id: int, session: Session) -> Task:

    task = session.get(Task, task_id)

    if not task:

        raise ValueError(f"Task with id {task_id} not found")

    return task



def list_tasks(

    session: Session,

    completed: bool | None = None,

    limit: int = 20,

    offset: int = 0,

) -> list[Task]:

    query = select(Task)

    if completed is not None:

        query = query.where(Task.completed == completed)

    query = query.offset(offset).limit(limit)

    return session.exec(query).all()



def create_task(task: Task, session: Session) -> Task:

    session.add(task)

    session.commit()

    session.refresh(task)

    return task



def update_task(task_id: int, updated: Task, session: Session) -> Task:

    task = get_task_by_id(task_id, session)

    task.title = updated.title

    task.description = updated.description

    task.completed = updated.completed

    session.commit()

    session.refresh(task)

    return task



def patch_task(task_id: int, patch: TaskPatch, session: Session) -> Task:

    task = get_task_by_id(task_id, session)

    patch_data = patch.model_dump(exclude_unset=True)

    for field, value in patch_data.items():

        setattr(task, field, value)

    session.commit()

    session.refresh(task)

    return task



def delete_task(task_id: int, session: Session) -> None:

    task = get_task_by_id(task_id, session)

    session.delete(task)

    session.commit()

Why ValueError instead of HTTPException​

ValueError is a standard Python built-in. Any caller — a route handler, a CLI script, a background task, a test — can catch it with a plain try/except ValueError. If the service raised HTTPException instead, every single caller would need to import FastAPI and understand HTTP semantics just to handle a domain error, making the service impossible to use outside a FastAPI context and harder to test without spinning up an HTTP client. The router is where domain exceptions get mapped to HTTP responses — once, in one place, rather than scattered wherever a service function happens to be called.


The Router​

The router stays thin: it handles HTTP parsing, calls the service, catches domain exceptions, and returns the response — no database logic, no business rules.


from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query

from sqlmodel import Session

from db import get_session

from models.task import Task, TaskPatch

from services import task_service



router = APIRouter(prefix="/tasks", tags=["Tasks"])



SessionDep = Annotated[Session, Depends(get_session)]



@router.get("/", response_model=list[Task])

def get_all(

    session: SessionDep,

    completed: bool | None = Query(default=None),

    limit: int = Query(default=20, ge=1, le=100),

    offset: int = Query(default=0, ge=0),

):

    return task_service.list_tasks(session, completed, limit, offset)



@router.get("/{task_id}", response_model=Task)

def get_one(task_id: int, session: SessionDep):

    try:

        return task_service.get_task_by_id(task_id, session)

    except ValueError as e:

        raise HTTPException(status_code=404, detail=str(e))



@router.post("/", status_code=201, response_model=Task)

def create(task: Task, session: SessionDep):

    return task_service.create_task(task, session)



@router.put("/{task_id}", response_model=Task)

def update(task_id: int, updated: Task, session: SessionDep):

    try:

        return task_service.update_task(task_id, updated, session)

    except ValueError as e:

        raise HTTPException(status_code=404, detail=str(e))



@router.patch("/{task_id}", response_model=Task)

def patch(task_id: int, patch_data: TaskPatch, session: SessionDep):

    try:

        return task_service.patch_task(task_id, patch_data, session)

    except ValueError as e:

        raise HTTPException(status_code=404, detail=str(e))



@router.delete("/{task_id}", status_code=204)

def delete(task_id: int, session: SessionDep):

    try:

        task_service.delete_task(task_id, session)

    except ValueError as e:

        raise HTTPException(status_code=404, detail=str(e))

session: SessionDep is placed first in get_all's parameter list deliberately — Python requires parameters without a default to come before ones that do, and completed, limit, and offset all carry defaults through Query(...). Putting session first avoids needing to give it an artificial default value it will never actually use, since Depends always resolves it. The try/except ValueError blocks scattered through the rest of the router are the entire translation layer — domain errors become HTTP errors in exactly one place per route, keeping the service itself free of any HTTP awareness.


Class-Based Services as Injectable Dependencies​

For a service that needs to carry shared state — a session, a configuration object, another service — a class is the natural structure, and FastAPI can inject a class instance through Depends exactly the way it injects a function's return value.


from typing import Annotated

from fastapi import Depends

from sqlmodel import Session

from db import get_session

from models.task import Task, TaskPatch



class TaskService:

    def __init__(self, session: Annotated[Session, Depends(get_session)]):

        self.session = session



    def get_by_id(self, task_id: int) -> Task:

        task = self.session.get(Task, task_id)

        if not task:

            raise ValueError(f"Task with id {task_id} not found")

        return task



    def list(

        self,

        completed: bool | None = None,

        limit: int = 20,

        offset: int = 0,

    ) -> list[Task]:

        from sqlmodel import select

        query = select(Task)

        if completed is not None:

            query = query.where(Task.completed == completed)

        return self.session.exec(query.offset(offset).limit(limit)).all()



    def create(self, task: Task) -> Task:

        self.session.add(task)

        self.session.commit()

        self.session.refresh(task)

        return task



    def patch(self, task_id: int, patch: TaskPatch) -> Task:

        task = self.get_by_id(task_id)

        for field, value in patch.model_dump(exclude_unset=True).items():

            setattr(task, field, value)

        self.session.commit()

        self.session.refresh(task)

        return task



    def delete(self, task_id: int) -> None:

        task = self.get_by_id(task_id)

        self.session.delete(task)

        self.session.commit()



TaskServiceDep = Annotated[TaskService, Depends(TaskService)]

The router built on this class-based service is cleaner still — the session dependency resolves inside the service itself, not on every individual route:


@router.get("/", response_model=list[Task])

def get_all(

    service: TaskServiceDep,

    completed: bool | None = Query(default=None),

    limit: int = Query(default=20, ge=1, le=100),

    offset: int = Query(default=0, ge=0),

):

    return service.list(completed, limit, offset)



@router.get("/{task_id}", response_model=Task)

def get_one(task_id: int, service: TaskServiceDep):

    try:

        return service.get_by_id(task_id)

    except ValueError as e:

        raise HTTPException(status_code=404, detail=str(e))

FastAPI resolves TaskService.__init__'s session parameter exactly as it would for a route function's own parameter — the full dependency tree resolves automatically, with the router never needing to know a session is involved at all.


Testing the Service Layer Directly​

The central payoff of this architecture is testability. Service functions are plain Python — they take a Session and return a value, with no HTTP client, no TestClient, no route involved anywhere in the test:


# tests/test_task_service.py

from sqlmodel import Session, create_engine, SQLModel

from sqlalchemy.pool import StaticPool

from models.task import Task

from services import task_service

import pytest



@pytest.fixture

def session():

    engine = create_engine(

        "sqlite://",

        connect_args={"check_same_thread": False},

        poolclass=StaticPool,

    )

    SQLModel.metadata.create_all(engine)

    with Session(engine) as session:

        yield session



def test_create_task(session: Session):

    task = Task(title="Write docs")

    created = task_service.create_task(task, session)

    assert created.id is not None

    assert created.title == "Write docs"

    assert created.completed is False



def test_get_task_by_id_raises_for_missing(session: Session):

    with pytest.raises(ValueError, match="not found"):

        task_service.get_task_by_id(999, session)



def test_patch_task_updates_only_provided_fields(session: Session):

    task = task_service.create_task(Task(title="Original", completed=False), session)

    from models.task import TaskPatch

    patched = task_service.patch_task(task.id, TaskPatch(completed=True), session)

    assert patched.title == "Original"  # unchanged

    assert patched.completed is True    # updated



def test_delete_task(session: Session):

    task = task_service.create_task(Task(title="Delete me"), session)

    task_service.delete_task(task.id, session)

    with pytest.raises(ValueError):

        task_service.get_task_by_id(task.id, session)

poolclass=StaticPool is what keeps this in-memory SQLite database alive and shared across the test — without it, SQLite's default pooling would open a fresh, empty in-memory database for each new connection, which would make the table created by create_all invisible to the session used afterward. These tests run fast, entirely independent of the HTTP stack, and each one checks exactly one piece of business logic — a failure points straight at the service function itself, not at a route, a dependency chain, or a serialization layer.


The Complete Architecture​


HTTP Request

     │

     ▼

Router (tasks.py)

├── Parses request (FastAPI)

├── Injects session (Depends)

├── Calls service function

├── Catches ValueError → HTTPException

└── Returns response (response_model)

     │

     ▼

Service (task_service.py)

├── Executes database queries

├── Applies business rules

├── Raises ValueError on domain errors

└── Returns domain objects (Task)

     │

     ▼

Database (SQLite / PostgreSQL)

Each layer has exactly one responsibility: the router doesn't know how tasks are stored, the service doesn't know HTTP exists, and the database doesn't know Python objects exist. This separation is what makes every layer independently testable, replaceable, and extensible.


Common Mistakes to Avoid​

Raising HTTPException from inside a service function couples it permanently to FastAPI's HTTP layer, makes it unusable outside an HTTP context, and forces every test of that logic to deal with HTTP concerns it has nothing to do with — raising a domain exception (ValueError, KeyError, or a custom exception class) and letting the router translate it is the fix. Putting database queries directly inside route handlers — a route body containing session.exec(select(Task).where(...)) — makes that logic unreusable and requires a full HTTP stack just to test it; all database access belongs in the service layer instead. Injecting a Request object into a service breaks the same boundary from the other direction — if a service genuinely needs data extracted from the request, that extraction happens in the router, with the result passed in as a plain value. One enormous service file becomes its own problem as an application grows; splitting by domain — task_service.py, user_service.py, auth_service.py — keeps each file to one coherent responsibility. And skipping unit tests for service functions defeats much of the reason this architecture exists in the first place — the service layer's main advantage is how easy it makes testing, and that advantage delivers nothing if the tests never get written.


Practice: Building the User Service​

services/user_service.py:


from pwdlib import PasswordHash

from sqlmodel import Session, select

from models.user import User



password_hash = PasswordHash.recommended()



def create_user(user: User, session: Session) -> User:

    existing = session.exec(

        select(User).where(User.username == user.username)

    ).first()

    if existing:

        raise ValueError(f"Username '{user.username}' already exists")

    user.hashed_password = password_hash.hash(user.hashed_password)

    session.add(user)

    session.commit()

    session.refresh(user)

    return user



def get_user_by_username(username: str, session: Session) -> User:

    user = session.exec(select(User).where(User.username == username)).first()

    if not user:

        raise ValueError(f"User '{username}' not found")

    return user



def list_users(session: Session) -> list[User]:

    return session.exec(select(User)).all()

pwdlib is the currently maintained library FastAPI's own documentation recommends for password hashing — PasswordHash.recommended() configures Argon2, the currently recommended algorithm, without needing to specify it manually. create_user checks for a duplicate username before hashing anything, since hashing a password that's about to be rejected wastes the (deliberately expensive) hashing work for nothing, and raises ValueError — never HTTPException — matching the service-layer boundary established throughout this article.

routers/users.py:


from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException

from sqlmodel import Session

from db import get_session

from models.user import User

from services import user_service



router = APIRouter(prefix="/users", tags=["Users"])



SessionDep = Annotated[Session, Depends(get_session)]



@router.post("/", status_code=201, response_model=User)

def create_user(user: User, session: SessionDep):

    try:

        return user_service.create_user(user, session)

    except ValueError as e:

        raise HTTPException(status_code=400, detail=str(e))



@router.get("/{username}", response_model=User)

def get_user(username: str, session: SessionDep):

    try:

        return user_service.get_user_by_username(username, session)

    except ValueError as e:

        raise HTTPException(status_code=404, detail=str(e))



@router.get("/", response_model=list[User])

def get_all_users(session: SessionDep):

    return user_service.list_users(session)

tests/test_user_service.py:


from sqlmodel import Session, create_engine, SQLModel

from sqlalchemy.pool import StaticPool

from models.user import User

from services import user_service

import pytest



@pytest.fixture

def session():

    engine = create_engine(

        "sqlite://",

        connect_args={"check_same_thread": False},

        poolclass=StaticPool,

    )

    SQLModel.metadata.create_all(engine)

    with Session(engine) as session:

        yield session



def test_create_user_hashes_password(session: Session):

    user = User(username="alice", email="[email protected]", hashed_password="plaintext")

    created = user_service.create_user(user, session)

    assert created.hashed_password != "plaintext"



def test_create_user_rejects_duplicate_username(session: Session):

    user_service.create_user(

        User(username="alice", email="[email protected]", hashed_password="pw1"), session

    )

    with pytest.raises(ValueError, match="already exists"):

        user_service.create_user(

            User(username="alice", email="[email protected]", hashed_password="pw2"), session

        )



def test_get_user_by_username_raises_for_missing(session: Session):

    with pytest.raises(ValueError, match="not found"):

        user_service.get_user_by_username("nobody", session)

Each test calls user_service directly, with a fresh in-memory session and no HTTP layer involved anywhere — test_create_user_hashes_password confirms the stored value is never the plaintext password, and test_create_user_rejects_duplicate_username confirms the uniqueness check happens before any duplicate reaches the database.

Key Takeaways​

A service layer draws one clean line through an application: routers handle HTTP — status codes, parsing, serialization — and services handle everything else, raising plain Python exceptions that routers translate into the right HTTPException in exactly one place per route. Class-based services extend this pattern for logic that needs shared state, letting FastAPI resolve a class's own dependencies through Depends the same way it resolves a function's. The real payoff shows up in testing: because a service function only ever needs a Session and returns a value, it can be tested directly against an in-memory database with no HTTP client, no running server, and no dependency chain to mock — a failure in a service test points to exactly one function, not to an entire request-handling stack.

Frequently Asked Questions​

What is a service layer in FastAPI?

A service layer is the architectural boundary between HTTP routing and business logic. Route handlers deal with HTTP concerns — status codes, request parsing, response serialisation, raising HTTPException. Service functions deal with domain concerns — database queries, business rules, and data transformation. Separating these two responsibilities produces code that is testable without an HTTP stack, reusable across multiple routes, and maintainable as the application grows.

Why should services not raise HTTPException in FastAPI?

HTTPException is an HTTP-layer concern — it carries an HTTP status code and a response body format specific to FastAPI. A service function does not know it is being called from an HTTP API. It might be called from a CLI tool, a background job, a WebSocket handler, or a test. Raising HTTPException from a service couples it permanently to FastAPI's HTTP protocol, makes it impossible to use outside that context, and forces every test to handle HTTP semantics. Services should raise standard Python exceptions like ValueError, and the router translates those into HTTPException.

What exception should a FastAPI service raise when a record is not found?

A standard Python exception such as ValueError. For example: raise ValueError(f'Task with id {task_id} not found'). The router catches this in a try/except block and translates it into HTTPException(status_code=404, detail=str(e)). This keeps the service decoupled from HTTP concerns while giving the router full control over the HTTP response.

What is the Single Responsibility Principle and how does it apply to FastAPI services?

The Single Responsibility Principle states that each module should have one reason to change. In a FastAPI application, a route handler should change only when the HTTP contract changes — a new status code, a new query parameter, a different response format. A service function should change only when the business rules change — a new validation, a different query, updated logic. Keeping them in separate files means changing one does not require touching the other.

What is the Dependency Inversion Principle and how does it relate to FastAPI service architecture?

The Dependency Inversion Principle states that high-level modules should depend on abstractions rather than low-level implementation details. In FastAPI, the router is the high-level module. It calls list_tasks() or create_task() without knowing or caring how tasks are stored. If the storage implementation changes from SQLite to PostgreSQL, or from a direct query to a caching layer, the router code is unchanged because it depends on the service interface, not on the database details.

How do I inject a service into a FastAPI route using Depends?

For function-based services, pass the session as a parameter resolved via Depends and call the service function directly from the route handler. For class-based services, declare the class in the route's Annotated type alias — TaskServiceDep = Annotated[TaskService, Depends(TaskService)] — and use it as the parameter type. FastAPI calls the class constructor, resolves its own dependencies declared in __init__, and injects the resulting instance into the route handler.

What is a class-based service in FastAPI and when should I use one?

A class-based service stores shared state — a database session, configuration, another service — as instance attributes set in __init__. FastAPI injects the class instance using Depends exactly as it does with function dependencies. Use a class-based service when the service needs to carry shared context across multiple methods, when the service itself has dependencies that should be resolved once per request, or when you want to group related operations into a cohesive object with a clean interface.

How do I test a FastAPI service function without using TestClient?

Call the service function directly with a Session connected to an in-memory SQLite test database. Create a test engine with create_engine('sqlite://', poolclass=StaticPool), call SQLModel.metadata.create_all(engine), open a Session, and pass it directly to the service function. Because the service has no HTTP dependency, the test does not need TestClient, a running server, or any HTTP infrastructure. The test verifies pure business logic in milliseconds.

Why is testing service functions faster and more precise than testing through routes?

Testing through a route requires the full HTTP stack: TestClient, request serialisation, dependency resolution, response deserialisation, and status code checking. A failure could be in any of those layers. Testing a service function directly requires only a database session. A failure points precisely to the service function. Service tests also run faster because there is no HTTP overhead, no middleware, and no serialisation involved.

How does the try/except pattern work in a FastAPI router that uses a service layer?

The service raises a standard Python exception such as ValueError when a domain error occurs. The router wraps the service call in a try/except block: try: return task_service.get_task_by_id(task_id, session) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)). The translation from domain error to HTTP error happens once in the router, keeping the service clean and the HTTP logic centralised.

What should a route handler contain when using a service layer?

A route handler should contain only HTTP concerns: declaring the route decorator with status code and response_model, injecting dependencies via Depends, passing extracted values to the service function, catching domain exceptions and translating them to HTTPException, and returning the result. It should contain no database queries, no business rules, and no data transformation logic. If a route handler is doing more than calling a service and handling exceptions, the excess logic belongs in the service.

How does patch_task differ from update_task in the service layer?

update_task performs a full replacement — it takes a complete Task object and overwrites all modifiable fields unconditionally. patch_task performs a partial update — it takes a TaskPatch object with all optional fields, calls model_dump(exclude_unset=True) to get only the fields the client actually sent, and applies only those fields using setattr. Fields the client did not include are not touched in the database.

What does model_dump(exclude_unset=True) do in a patch service function?

It returns a dictionary containing only the fields that were explicitly set in the request body, excluding fields that were absent from the request. In a patch operation, this means only the provided fields are updated in the database — everything else is left unchanged. Without exclude_unset=True, model_dump() would include all fields with their default values, which would overwrite database values with None for every field the client omitted.

Why should services not depend on the FastAPI Request object?

The Request object is an HTTP-layer concept. A service that depends on Request cannot be called from a background task, a CLI script, a WebSocket handler, or a unit test without constructing a fake HTTP request. If a service needs data that originates from the request — a user ID from a JWT, a query parameter value — the router should extract that value and pass it to the service as a plain Python value. The service receives a string, an integer, or a dataclass — never a Request object.

How should I organise service files as a FastAPI application grows?

Split services by domain, one file per concern: task_service.py for task operations, user_service.py for user operations, auth_service.py for authentication logic. Each file should have one coherent responsibility. Avoid a single large services.py that contains functions for every domain in the application — it becomes a maintenance burden and makes imports unclear. The file structure should mirror the domain model.

What is the correct architecture for a three-layer FastAPI application?

The three layers are: the router, which handles HTTP parsing, dependency injection, exception translation, and response serialisation; the service, which executes database queries, applies business rules, and raises domain exceptions; and the database, which stores and retrieves data. Each layer communicates only with the layer directly adjacent to it. The router does not query the database directly. The service does not handle HTTP status codes. This separation makes each layer independently testable, replaceable, and extensible.

How do I add filtering and pagination to a service function in FastAPI?

Declare filter and pagination parameters as regular function arguments with defaults — completed: bool | None = None, limit: int = 20, offset: int = 0. Inside the function, build the query conditionally: if completed is not None: query = query.where(Task.completed == completed). Then apply pagination: query = query.offset(offset).limit(limit). The router extracts these values from query parameters and passes them to the service as plain Python values.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Depends System

Next

Project: Build a Task Manager API (Part 2)