The first command in the template for my SQL query service was rye sync. My terminal replied Command 'rye' not found. Rye was a Python project manager. On its first sync it could create an environment for the project and use another tool, uv, to resolve compatible package versions and install them. My shell had failed to find Rye on its command search path (PATH). It hadn't even read the project configuration yet.12
📓 Note: By June 2025, uv could also manage Python projects on its own. With uv installed,
uv syncin the project directory can create the environment and install the dependencies declared inpyproject.toml.3
My requests were “i don't want to install rye, modify the toml for me” and “i dont need asyncpg , i need mysql...”. The template's asyncpg driver talks to PostgreSQL. I wanted MySQL, and I already had Python and pip. Here's one service you can build on those terms. A client submits a report name, receives its database ID, and uses that ID to read the name back. The service uses MySQL. The automated test gets a temporary database of its own.
What belongs in the project directory?
Create report-service/ and run the commands below from there. Create these files, leaving __init__.py empty. That file makes report_service an importable Python package.
report-service/
├── pyproject.toml
├── src/
│ └── report_service/
│ ├── __init__.py
│ ├── db.py
│ └── main.py
└── tests/
└── test_endpoints.py
main.py handles HTTP requests. db.py describes a database table. The tests live outside the installed package. The distribution name used by packaging tools is report-service. The name in from report_service.db import Report is the import name and uses an underscore. Two modules are enough for this example. If one file eventually holds dozens of routes, you can group them by resource then.
How do I install the dependencies with pip?
Python's venv module creates an isolated environment for the service. pip installs the project and its dependencies into that environment. Save this as pyproject.toml. TOML is the configuration file format. Under [project], dependencies lists the packages the running service needs. Under [project.optional-dependencies], the dev extra adds tools for testing and linting. The example uses Python 3.12 and direct dependency versions available in June 2025.4
📓 Note: Running
pip install .also installs the service itself. A wheel is an installable Python distribution, a.whlfile containing the project's code and metadata, including its version and dependency declarations. Hatchling is the build backend selected in[build-system]. For a regular installation, pip asks Hatchling to build a wheel containingsrc/report_service/and then installs it.56
[project]
name = "report-service"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"fastapi==0.111.1",
"uvicorn==0.30.6",
"pydantic==2.7.4",
"SQLAlchemy[asyncio]==2.0.41",
"aiomysql==0.2.0",
"PyMySQL[rsa]==1.1.1",
]
[project.optional-dependencies]
dev = [
"pytest==8.4.1",
"httpx==0.28.1",
"aiosqlite==0.21.0",
"ruff==0.11.13",
]
[build-system]
requires = ["hatchling==1.27.0"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/report_service"]
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]
Python already includes asyncio. The square brackets in SQLAlchemy[asyncio] ask pip for the dependencies SQLAlchemy needs for its asynchronous support.7
On macOS or Linux, run the following two commands. On Windows, create the environment with py -3.12 -m venv .venv and use .venv\Scripts\python.exe in place of .venv/bin/python. Naming the interpreter explicitly also tells you exactly which environment pip will update.4
python3.12 -m venv .venv
.venv/bin/python -m pip install -e ".[dev]"
The dot means the current project, [dev] selects the extra declared above, and -e requests an editable install. Subsequent imports use the files under src/report_service/. Edit main.py and restart the service to load your change. Saving a source file doesn't trigger a wheel build. For a regular installation with only the runtime dependencies, use .venv/bin/python -m pip install .. The TOML pins the packages listed explicitly. Reproducing every package in an environment also requires recording the resolved versions of their dependencies.
I had asked “setup.py requirements.txt or toml? what are differernce”. Once I knew how pip found the project, I could read the rest of the template by asking which tool would actually use each setting.
| Setting in the template | What it controls here |
|---|---|
[tool.rye] with managed, virtual and dev-dependencies | The first two settings tell Rye whether it manages the project and whether to install dependencies while skipping the project itself. With pip, remove the Rye section and put the development tools you want in the dev extra.8 |
setup.py, requirements.txt and [tool.setuptools] | setup.py can describe a setuptools build. A requirements file lists things pip should install. This TOML already declares the project's dependencies and selects Hatchling. Hatchling reads its own package selection, so setuptools' packages = {find = …} serves no purpose here.46 |
Ruff's line-length, select and ignore | Ruff is a linter and formatter. These settings choose the target width, the checks to run and exceptions to those checks. Here E4, E7 and E9 select specific pycodestyle checks, F selects Pyflakes and I selects import sorting. Old ANN101 and ANN102 rules asked for annotations on instance-method self and class-method cls. Ruff 0.11.13 has removed both, so the old ignore line can go.9 |
pytest's pythonpath and asyncio_mode | pythonpath = ["src"] adds that directory to the test import path. An editable install already makes the package importable. asyncio_mode = "auto" tells the pytest-asyncio plugin how to handle async tests. The test below is a regular def function using a client that runs the app, so it needs neither setting.10 |
If you keep more of the old Ruff settings, E and W cover pycodestyle checks, F can catch an undefined name or unused import, and N and ANN cover naming and annotations. B flags error-prone patterns, UP suggests newer Python syntax, SIM suggests simplifications and PL selects checks derived from Pylint. For McCabe complexity, which measures independent paths through a function, select C90 explicitly.9
I had also asked, “why a web app need to build a wheel, idon't think it exports anythong reusable”. You can deploy the source directly if the server has the dependencies and can import the app. A wheel becomes useful when several machines need the same tested copy. Building the query tool's historical configuration with Hatchling 1.27.0 produced sqlman-0.1.0-py3-none-any.whl with sqlman/main.py inside. The wheel declares its third-party dependencies. For an offline installation their installation files must be available separately.115
How does one JSON request become a row in MySQL?
I wanted an open-source database toolkit with connection pooling. SQLAlchemy is MIT-licensed. It can execute SQL directly or use an object-relational mapper (ORM), which maps Python objects to table rows. Both approaches can borrow connections from the same engine. Save the following as src/report_service/db.py. Each Report represents one row with a numeric ID and a name.7
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Report(Base):
__tablename__ = "reports"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
My next question was “why do need pydantic”. Look at the two different classes in this example: ReportInput says what the client can submit. Report says what the database stores, including an ID that the client never supplies. FastAPI uses Pydantic to validate the input. Because this module imports BaseModel and Field directly, I list Pydantic as a direct dependency. A route returning fixed data can work without a custom model. Save this as src/report_service/main.py.
import logging
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from report_service.db import Base, Report
logger = logging.getLogger(__name__)
class ReportInput(BaseModel):
name: str = Field(min_length=1, max_length=100)
def create_app(database_url: str | None = None) -> FastAPI:
url = database_url or os.environ["DATABASE_URL"]
engine = create_async_engine(url)
sessions = async_sessionmaker(engine, expire_on_commit=False)
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
finally:
await engine.dispose()
app = FastAPI(lifespan=lifespan)
@app.post("/reports", status_code=201)
async def add_report(data: ReportInput):
async with sessions.begin() as session:
row = Report(name=data.name)
session.add(row)
await session.flush()
logger.info("Created report %s", row.id)
return {"id": row.id, "name": row.name}
@app.get("/reports/{report_id}")
async def read_report(report_id: int):
async with sessions() as session:
row = await session.get(Report, report_id)
if row is None:
raise HTTPException(status_code=404, detail="Report not found")
return {"id": row.id, "name": row.name}
return app
create_app is an application factory, a function that constructs the app. Each app has an engine and a pool of reusable database connections. Each request opens its own session, through which it performs database operations. flush() sends the insert and obtains the generated ID. Leaving sessions.begin() commits the transaction on success or rolls it back if an exception occurs. The code before yield in lifespan runs at startup and creates missing tables. The finally block releases engine resources during shutdown. Changing columns on an existing table calls for a schema migration.7
“do i need toadd a depandency for logger for fast api?” Python already includes logging. The example logs success after the transaction commits. To see that application message on the terminal, you can configure the root logger with logging.basicConfig(level=logging.INFO) before creating the app.12
I need MySQL. What do I change?
The driver communicates with a particular database. Here aiomysql provides an asynchronous MySQL driver based on PyMySQL. Some MySQL 8 authentication methods need PyMySQL's rsa extra. The prefix mysql+aiomysql names both the database and the driver. This project has no use for the template's PostgreSQL driver asyncpg.13
For a fresh local MySQL 8.0 instance, use an administrator account in the MySQL client to create the sample database and a user allowed to connect over local TCP. The password below is for the local example.
CREATE DATABASE reports CHARACTER SET utf8mb4;
CREATE USER 'report_user'@'127.0.0.1' IDENTIFIED BY 'demo_password';
GRANT CREATE, SELECT, INSERT ON reports.* TO 'report_user'@'127.0.0.1';
Back in the terminal, export the connection URL and start the server. Substitute your credentials if you already have a database. Percent-encode special URL characters in the password.
export DATABASE_URL='mysql+aiomysql://report_user:[email protected]:3306/reports?charset=utf8mb4'
.venv/bin/python -m uvicorn report_service.main:create_app --factory
--factory tells Uvicorn to import and call create_app. From a second terminal send a report name, then fetch the ID the first request actually returns. A fresh database usually assigns 1. The example keeps the original Unicode test value 月报, meaning “monthly report”.
curl -i -H 'Content-Type: application/json' -d '{"name":"月报"}' http://127.0.0.1:8000/reports
curl -i http://127.0.0.1:8000/reports/1
With MySQL 8.0.42, my first request returned HTTP 201 and {"id":1,"name":"月报"}. The second returned HTTP 200 and the same ID and name. That round trip checks character handling as well as persistence.
“how to write test for web app in py”
Save the following as tests/test_endpoints.py. pytest's tmp_path provides a fresh directory for the test. Passing a temporary SQLite URL to the app factory gives the test its own tables. TestClient sends requests directly to the app. Using it in a with block runs startup and shutdown, so the test needs neither a listener on port 8000 nor the everyday MySQL credentials.10
from fastapi.testclient import TestClient
from report_service.main import create_app
def test_create_and_read_report(tmp_path):
app = create_app(f"sqlite+aiosqlite:///{tmp_path / 'test.db'}")
with TestClient(app) as client:
assert client.get("/reports/1").status_code == 404
assert client.post("/reports", json={"name": ""}).status_code == 422
created = client.post("/reports", json={"name": "月报"})
assert created.status_code == 201
saved = created.json()
fetched = client.get(f"/reports/{saved['id']}")
assert fetched.status_code == 200
assert fetched.json() == {"id": saved["id"], "name": "月报"}
Run .venv/bin/python -m pytest -q from the project root. The four requests exercise a missing record (404), invalid input (422), a successful insert (201), and a read in a new session (200). This SQLite test checks the application behavior independently. The two requests against MySQL above exercise the actual driver, authentication and character set.
Can I keep src and remove the extra package directory?
“i want to drop the my project name folder cause i think it is reduntdant how to modify” was the last layout change I considered. To keep src/ and use flat modules, move main.py and db.py directly under src/. Change the import in main.py to from db import Base, Report, change the test import to from main import create_app, and start Uvicorn with main:create_app --factory. The distribution can still be called report-service. Replace the old Hatchling wheel selection with the following settings. They tell Hatchling where editable imports live and which files to include in a regular wheel.6
[tool.hatch.build]
dev-mode-dirs = ["src"]
[tool.hatch.build.targets.wheel]
only-include = ["src/db.py", "src/main.py"]
sources = ["src"]
Run .venv/bin/python -m pip install -e ".[dev]" again, then rerun pytest. In the flat layout main and db are top-level names. Keeping a named package gives modules a shared namespace as the service grows. Why the project root, src and the import package are different paths.
The query management service I later committed kept src/sqlman/ and dependencies for several database drivers. Starting here with one MySQL service and one temporary test database makes it possible to trace each dependency to the line that needs it.11
Footnotes
-
Astral. (n.d.). Basics. Rye Documentation. First sync. ↩
-
Ronacher, A. (2024, August 21). Rye and uv: August is Harvest Season for Python Packaging. Armin Ronacher’s Thoughts and Writings. Opening paragraph on Rye using uv. ↩
-
Marsh, C. (2024, August 20). uv: Unified Python packaging. Astral. Independent project management in uv. ↩
-
The pip developers. (2025). Local project installs. pip 25.1.1. Regular and editable installs. ↩ ↩2 ↩3
-
Holth, D. (2012, September 20). PEP 427 – The Wheel Binary Package Format 1.0. Python Enhancement Proposals. Wheel format and purpose. ↩ ↩2
-
Hatch contributors. (2025). Build configuration. Hatchling 1.27.0. File selection, path rewriting and editable installs. ↩ ↩2 ↩3
-
SQLAlchemy authors. (2025). SQLAlchemy, rel_2_0_41. Project and MIT license · Async engines and sessions. ↩ ↩2 ↩3
-
Astral. (n.d.). pyproject.toml. Rye Documentation. Virtual projects. ↩
-
Astral. (2025). Ruff, v0.11.13. Rule selection · ANN101:self · ANN102:cls. ↩ ↩2
-
Starlette contributors. (2024). TestClient. Starlette 0.37.2. HTTPX client and lifespan. ↩ ↩2
-
CaiBorui [S2thend]. (2025, July 2). Add Python backend service [commit b088abf]. GitHub. Committed project configuration. ↩ ↩2
-
Python Software Foundation. (n.d.). Logging HOWTO. Python 3.12 Documentation. Log levels and basic configuration. ↩
-
aiomysql contributors. (2023). aiomysql, v0.2.0. Asynchronous MySQL driver · PyMySQL contributors. (2024). PyMySQL, v1.1.1. Authentication and the rsa extra. ↩