APIRouter و ساختار پروژه (Project structure): Layer در برابر Feature، prefix، tags، lifespan و settings
"If you are building an application or a web API, it's rarely the case that you can put everything in a single file. FastAPI provides a convenience tool to structure your application while keeping all the flexibility." — مستندات FastAPI، "Bigger Applications - Multiple Files"، fastapi.tiangolo.com/tutorial/bigger-applications
خلاصه (Summary): یک سرویس FastAPI خیلی زود از یک main.py بزرگتر میشود. APIRouter یک «FastAPI کوچک» است که عملیات مسیر (Path operation) یک بخش، مثل catalog، orders یا admin را کنار تنظیمات مشترک آن (prefix، tags، dependencies، responses، default_response_class) نگه میدارد. include_router نگاشتهای درخواست به تابع (Route) را در برنامه یا Router دیگر کپی میکند و prefix، tags، وابستگیها (Dependencies) و پاسخها را ترکیب میکند. دور Routerها کارخانهٔ برنامه (App factory) یعنی create_app() قرار دارد: تنظیمات نوعدار (Typed settings) را با pydantic-settings، BaseSettings، متغیر محیطی، .env و پوشهٔ اسرار (Secrets directory) یک بار میخواند، با lru_cache ذخیره و بهصورت Dependency تزریق میکند. منابع مشترک را در چرخهٔ عمر (Lifespan) باز میکند؛ یک asynccontextmanager که پیش از اولین درخواست و پس از آخرین درخواست اجرا میشود و منابع را روی app.state میگذارد. سپس میانافزار (Middleware)، فایلهای ایستا و زیربرنامهها (Sub-applications) را اضافه و درخت Router را include میکند. فایلها یکی از دو چیدمان (Layout) را دارند: بر اساس لایه (Layer) فنی، با routers/، schemas/، models/، services/، repositories/؛ یا بر اساس قابلیت (Feature)، با catalog/ و orders/ که هر کدام یک برش عمودی (Vertical slice) شامل Router، طرحواره (Schema)، مدل (Model)، Repository (الگوی دسترسی به داده) و سرویس (Service) خود هستند. تمرکز (Focus): تنظیم APIRouter و include_router برای ترکیب prefix، tags، dependencies، responses و include_in_schema، ساخت Router تودرتو و include دوبارهٔ یک Router؛ فهم ترتیب Route و تداخل Path؛ یکتایی operationId با generate_unique_id_function، تنظیم openapi_tags و پنهانکردن Route داخلی؛ App factory و نقطهٔ ورود (Entry point) با shop.asgi:app، uvicorn --factory و [tool.fastapi] entrypoint؛ مدیریت lifespan با asynccontextmanager، راهاندازی (Startup)، خاموشی (Shutdown)، app.state، request.app، lifespan مربوط به Router و برنامهٔ دارای Mount (نصب زیربرنامه)؛ settings با BaseSettings، SettingsConfigDict، env_prefix، env_file، secrets_dir، اولویت منابع، extra="forbid"، SecretStr، فایل هر محیط و Dependency دارای lru_cache؛ انتخاب Layout تخت، Layer یا Feature، تفکیک مسئولیت Router و Service و Repository، Import (واردکردن ماژول) نسبی، __init__.py و import دوری، مقایسهٔ src/ با Layout تخت و قواعد نامگذاری؛ نسخهبندی API با Router، app.mount و StaticFiles، ترتیب Middleware و درخت تست متناظر با بسته. هدف یادگیری (Learning goal): سرویس را به Router و بسته (Package) تقسیم کنید تا هر Feature در یک محل خوانده، تغییر داده و تست شود. برنامه را در Factory بسازید تا تستها و هر Worker (پردازهٔ کارگر) نمونهای تازه و کاملاً پیکربندیشده بگیرند. همهٔ مقدارهای پیکربندی را در یک شیء Settings نوعدار، اعتبارسنجیشده و ذخیرهشده در حافظهٔ نهان (Cache) جمع کنید؛ منابع مشترک را در lifespan باز و بسته کنید؛ Layout مناسب اندازهٔ کد و تیم را انتخاب کنید و زمان تغییرش را بشناسید.
موضوع این صفحه ساختار کد FastAPI است: Routerها، App factory، lifespan، settings و پوشهها. جزئیات همسایه در صفحههای خودشان آمدهاند: Route، پارامتر مسیر (Path parameter)، پارامتر پرسوجو (Query parameter) و کد وضعیت در مبانی FastAPI؛ بدنه، سرآیند (Header) و خطای اعتبارسنجی (Validation) در اعتبارسنجی درخواست؛ Depends، Dependency دارای yield و dependency_overrides در تزریق وابستگی؛ مدیریتکنندهٔ خطا (Exception handler) و Problem Details در خطاها و پاسخها؛ Engine (موتور پایگاه داده)، Session (نشست) و Modelهای SQLAlchemy در SQLAlchemy 2 و SQLModel؛ تنظیم Uvicorn و Gunicorn، ثبت رخداد و Imageهای Docker در FastAPI در محیط عملیاتی؛ وضعیت آمادهٔ تست (Fixture)، Client (کارخواه) ناهمگام و پایگاه دادهٔ تست در تست FastAPI؛ uv، Ruff و فایل قفل در ابزارهای پروژهٔ Python. مثال سرتاسری این ساختار پروژهٔ CRUD اتاق و رزرو است. طراحی نسخه، تغییر ناسازگار و مهلت منسوخشدن در نسخهبندی و تکامل API آمده؛ مرز ماژول (Module boundary) بهعنوان سبک معماری در یکپارچهٔ ماژولار، یعنی شکل ماژولار Monolith (برنامهٔ یکپارچه)، و معماری پاک و ششضلعی؛ همتای Go این فصل هم چیدمان، Lint و Build پروژهٔ Go است.
مبنای بررسی مطالب، مستندات FastAPI است: آموزش "Bigger Applications"، "Metadata and Docs URLs"، راهنمای پیشرفتهٔ lifespan، settings، Sub-application، پیکربندی Path operation، تولید Client و تست رویدادها، مرجع APIRouter و FastAPI و یادداشت انتشار تا 0.165.0 در ۲۰۲۶-۱۱-۱۸. کد FastAPI 0.128.8 در routing.py، utils.py و openapi/utils.py، مستندات Pydantic Settings، مستندات Starlette دربارهٔ برنامه، Routing، lifespan و Middleware، آموزش و مرجع Python برای ماژول و import، PEP 328 و PEP 420، راهنمای بستهبندی Python برای src و flat، راهنمای pytest برای Fixture و شیوههای تست، مستندات Laravel 13 دربارهٔ Routing، Controller، Service provider، ساختار پوشه و پیکربندی و راهنمای Go module نیز بررسی شدهاند. صفحه برای Python 3.12+ و FastAPI جاری نوشته شده است. قطعهکدهای (Snippet) صفحه روی تنها مفسر ماشین اجرا، CPython 3.9.6، اجرا شدهاند؛ پس پروژه جدیدترین نسخههای قابل نصب روی آن را ثابت کرده: FastAPI 0.128.8، Starlette 0.49.3، Pydantic 2.13.5، pydantic-settings 2.11.0؛ نسخهٔ 2.12.0 پشتیبانی Python 3.9 را حذف کرده و جدیدترین نسخه، 2.16.3، به 3.11+ نیاز دارد. بقیه Uvicorn 0.39.0، httpx 0.28.1، pytest 8.4.2 و eval-type-backport برای str | None روی 3.9 هستند؛ مجموعهٔ حلشده در requirements.lock ذخیره شده است. هر کد وضعیت، متن خطا، هشدار و خط Log با برچسب «واقعی» خروجی همان اجراست. دو تفاوت نسخهای در جای مربوط مشخص شدهاند: FastAPI 0.137.0 در ۲۰۲۶-۰۶-۱۴ کپی Route در زمان include_router را کنار گذاشت: "Adding routes (path operations) after a router is included now works, they are reflected as they are not copied". همچنین مستندات جاری Pydantic Settings گزینههایی دارد که 2.11.0 ندارد: env_file_depth، dotenv_filtering، env_prefix_target و PYDANTIC_SETTINGS_DEBUG؛ نبودشان با جستوجوی بستهٔ نصبشده بررسی شده است.
نقشهٔ صفحه (Page map)
| دنبال چه هستید؟ | کجا بروید؟ |
|---|---|
| جدولهایی که باید حفظ باشید | همهچیز در یک دقیقه |
| دلیل وجود Router، Factory و settings | چرا لازم است |
| سیر نسخهها از Blueprint تا Router زنده | از کجا آمده |
| برنامهٔ تکفایلی و دو شکل بستهبندیشدهٔ آن | Python |
ماژول، Package و نقش __init__.py | تقسیم منطق میان فایلها |
ساخت Router با router = APIRouter(...) | کلاس APIRouter |
افزودن و تودرتوکردن با app.include_router(...) | افزودن Routerها |
ساخت /api/v1/products و گروههای مستندات | Prefix و tags |
| حفاظت کل Router و مستندات مشترک 404 | Dependency و پاسخ Router |
| Router برای HTML یا متن ساده | پیشفرضهای Router |
پاسخدادن /users/{id} به /users/me | ترتیب Route میان Routerها |
operationId و نام متدهای SDK | operationId و generate_unique_id_function |
openapi_tags و Routeهای پنهان | ساماندهی OpenAPI |
ساخت برنامه با create_app() | App factory |
نقش main.py، asgi.py و --factory | Entry point |
| بازکردن Pool (استخر اتصال) و Client فقط یک بار | Lifespan |
| Router با Startup مخصوص خود | Lifespan و State در Router |
خواندن .env با BaseSettings | Settings با pydantic-settings |
| اولویت مقدارها و فایل اسرار | منابع settings و اولویت |
@lru_cache get_settings() و محیطهای dev/staging/prod | Dependency تنظیمات |
چیدمان routers/ schemas/ models/ services/ repositories/ | چیدمان بر اساس Layer |
برشهای عمودی catalog/ orders/ | چیدمان بر اساس Feature |
| محل SQL و قواعد کسبوکار | تفکیک مسئولیت |
from ..core import x و چرخهٔ import | Importها و import دوری |
انتخاب src/ و نام فایلها | Layout و نامگذاری |
اجرای /v1 و /v2 کنار هم | نسخهبندی با Router |
app.mount و StaticFiles | Mount و Sub-application |
| محل اجرای Middleware | Middleware و Router |
درخت tests/ متناظر با app/ | تست متناظر با Package |
سازوکار داخلی include_router و متن دقیق خطاها | سازوکارها |
| اشکالهای رایج ساختار پروژه | حل مسائل کلاسیک |
| Layer یا Feature، یک سرویس یا چند سرویس | انتخاب |
| حرکت از Monolith به سیستم توزیعشده | در معماری |
| اجرای مثالها | آزمایشگاه |
routes/api.php، Controller و Service provider | برای توسعهدهندهٔ PHP/Laravel |
نقش cmd/ و internal/ | زاویهٔ Go |
همهچیز در یک دقیقه (Everything in one minute)
اجزای سازنده. هر ردیف در فهرست مفاهیم باز میشود.
| جزء | چیست؟ | به زبان ساده | در مثال |
|---|---|---|---|
APIRouter | گروهی از Path operationها و settings مشترک | «FastAPI کوچک برای یک بخش» | shop/catalog/router.py |
include_router | افزودن Routeهای یک Router به برنامه یا Router دیگر | «وصلکردن گروه زیر یک prefix» | shop/api.py |
prefix | بخش Path که ابتدای همهٔ Routeهای Router میآید | «نوشتن /products فقط یک بار» | APIRouter(prefix="/products") |
tags | گروه مستندات و سرویس SDK تولیدشده | «فصلهای /docs» | tags=["catalog"] |
dependencies در Router | Dependencyهایی که پیش از هر Route اجرا میشوند | «یک محافظ برای کل گروه» | Router ادمین، require_admin |
| App factory | تابع سازنده و برگردانندهٔ برنامهٔ پیکربندیشده | «create_app(settings)، هر بار تازه» | shop/main.py |
| Lifespan | مدیر زمینهٔ ناهمگام (Async context manager) پیرامون عمر برنامه | «بازکردن پیش از yield، بستن پس از آن» | shop/core/lifespan.py |
app.state | محل نگهداری صفتها روی نمونهٔ برنامه | «جای Pool» | app.state.db |
BaseSettings | مدل Pydantic پرشده از متغیر محیطی، .env و فایل اسرار | «پیکربندی نوعدار» | shop/core/config.py |
get_settings + lru_cache | Dependency تنظیمات که یک بار ساخته میشود | «یک بار خواندن، تعویض در تست» | Depends(get_settings) |
app.mount | Mount کردن برنامهٔ ASGI مستقل زیر یک Path | «اینجا برنامهٔ دیگری قرار دارد» | /static، /legacy |
دو Layout برای یک API. هر دو در مثال Package واقعیاند؛ یک تست یکسانبودن عملیات منتشرشده را ثابت میکند.
| پرسش | بر اساس Layer فنی (layered/) | بر اساس Feature (shop/) |
|---|---|---|
| پوشههای سطح بالا | routers schemas models services repositories | catalog/، orders/، core/، internal/ |
| فایلهای orders | 5 فایل در 5 پوشه | 5 فایل در 1 پوشه |
| محل قواعد سفارش برای توسعهدهندهٔ تازه | services/orders.py، پس از حدسزدن Layer | orders/service.py |
| Import میان Featureها | همهجا؛ routers/orders.py از repositories/products.py import میکند | فقط از catalog/service.py |
| مناسب برای | سرویس کوچک، یک تیم، کمتر از حدود 10 منبع | برنامهٔ یکپارچه (Monolith) با دامنههای (Domains) متعدد و چند تیم |
| تبدیل به ریزسرویس (Microservice) | سخت؛ هر سرویس بخشی از همهٔ Layerها میخواهد | آسان؛ انتقال یک پوشه |
| مثالِ استفاده | آموزش FastAPI با app/routers/ و قالب full-stack با app/api/routes/ | fastapi-best-practices به سبک Netflix Dispatch |
منبع یک مقدار settings. اولویت pydantic-settings از بالا به پایین است؛ همه در test_settings.py بررسی شدهاند.
| اولویت | منبع | مثال | نکته |
|---|---|---|---|
| 1 | آرگومان نامدار (Keyword argument) | Settings(app_name="x") | تست و Factory |
| 2 | متغیر محیطی (Environment variable) | SHOP_APP_NAME=x | پیشفرض غیرحساس به بزرگی حروف؛ prefix از env_prefix |
| 3 | فایل Dotenv | .env، سپس .env.prod | فایل آخر برنده است؛ فایل غایب رد میشود |
| 4 | Secrets directory | /run/secrets/shop_app_name | نام فایل = نام متغیر؛ محتوا = مقدار |
| 5 | پیشفرض فیلد | app_name: str = "Shop API" | بدون پیشفرض یعنی اجباری |
ترکیب تنظیمات در include_router. بر پایهٔ APIRouter.include_router در کد 0.128.8.
| پارامتر | قاعدهٔ ترکیب | اثر |
|---|---|---|
prefix | include prefix + router prefix + route path | /api + /v1 + /products + /{product_id} |
tags | نخست tags در include، سپس tags خود Route | ["admin"] + tags مربوط به Route |
dependencies | app → include → router → decorator → parameters | اجرا به همین ترتیب؛ اندازهگیری شده |
responses | {**include_responses, **route.responses} | برای وضعیت یکسان، ورودی خود Route برنده است |
default_response_class | route → router → include → parent | نخستین مقدار تنظیمشده برنده است |
include_in_schema | route and router and include | هر False، Route را پنهان میکند |
deprecated | route or include or parent | هر True آن را علامت میزند |
generate_unique_id_function | route → router → include → parent | تعیین operationId |
lifespan | تودرتو در lifespan والد | Startup مربوط به Router پس از Startup برنامه |
چرا لازم است (Why it exists)
شروع با یک فایل FastAPI درست است؛ اما نقطهٔ پایان این سادگی قابل پیشبینی است. فایل چندصد خط میشود؛ دو نفر در یک هفته آن را تغییر میدهند؛ تست پایگاه دادهٔ دیگری میخواهد؛ /api/v1 و یک tag روی چهل دکوراتور (Decorator) تکرار میشوند؛ و Route تازه زیر یک Route پارامتری قرار میگیرد و به آن نمیرسد. پیکربندی با os.environ.get(...) از پنج جا و همیشه به شکل رشته خوانده میشود؛ "false" هم در شرط درست محسوب میشود. اتصال (Connection) پایگاه داده هنگام import ماژول باز میشود، پس import در تست هم آن را باز میکند. مثالِ قبل همین فایل است و تستش تکتک این مشکلها را ثبت میکند.
سه ابزار، سه مسئلهٔ متفاوت را حل میکنند. Router گروهبندی را حل میکند: Routeهای یک بخش و settings مشترک کنار هماند و برنامه محل قرارگیری گروه را مشخص میکند. App factory و lifespan سیمکشی اجزا را حل میکنند: ساخت برنامه تابعی است که settings میگیرد و شیء تازه برمیگرداند؛ منابع مشترک هم یک محل برای بازشدن و یک محل برای بستهشدن دارند. Settings مسئلهٔ پیکربندی را حل میکند: هر مقداری که میان لپتاپ، CI، staging و production فرق دارد، فیلدی نوعدار است؛ هنگام Startup یک بار Validation میشود و مانند برنامههای دوازدهعاملی از محیط خوانده میشود: "The twelve-factor app stores config in environment variables". قابل تزریق هم هست تا تست جایگزینش کند. انتخاب Layout پوشهها، Layer یا Feature، تصمیم چهارم است؛ تصمیمی که روند رشد و نگهداری کد را تعیین میکند.
یک main.py | Router + Factory + settings + Package |
|---|---|
/api/v1/products و tags=["products"] روی هر Decorator | یک بار APIRouter(prefix="/products", tags=["catalog"]) |
| کپی احراز هویت (Authentication) در هر Route ادمین | include_router(admin.router, dependencies=[Depends(require_admin)]) |
os.environ.get("DEBUG", "false") رشتهای با ارزش شرطی درست است | docs_enabled: bool تبدیل و Validation میشود |
| Connection هنگام import باز و هرگز بسته نمیشود | بازشدن در lifespan، بستهشدن پس از yield |
| تستها برنامهٔ مشترک سطح ماژول دارند | create_app(test_settings) برای هر تست |
| 1,500 خط و تعارض ادغام | یک پوشه و یک مالک برای هر Feature |
operationId = get_product_api_v1_products__product_id__get | catalog-get_product |
تصویر روزمره. فروشگاه بزرگی را تصور کنید. ساختمان برنامه است و بخشها Router هستند: هر بخش نقشهٔ خودش (Route)، تابلوهای خودش (tags) و گاهی میز نگهبانی خودش (Router dependencies) را دارد. راهنمای طبقات میگوید هر بخش کجا قرار دارد؛ این همان prefix است. روال بازکردن و بستن فروشگاه lifespan است: چراغ، صندوق فروش و گاوصندوق پیش از بازشدن درها آماده و پس از خروج آخرین مشتری بسته میشوند، نه با ورود هر مشتری. Settings دفترچهٔ همین شعبه است: ساعت کار، واحد پول و رمز گاوصندوق؛ رمز در پاکت جداست و در دفترچه چاپ نمیشود. Factory نقشهٔ تأسیس شعبهٔ تازه است: ساختمان همان است و دفترچه فرق دارد. پرسش Layout هم دربارهٔ انبار است: همهٔ قفسهها یک جا، برچسبها جای دیگر و صندوقها جای سوم باشند، یا هر بخش قفسه و برچسب و صندوق خودش را نگه دارد؟ اولی برای سه بخش ساده است؛ برای سی بخش دومی جواب میدهد.
سه بدفهمی از همین ابتدا (Three common misunderstandings)
- «Router برنامهای جداست.»
APIRouterنه Mountشده است و نه جدا؛ Routeهایش به جدول واحد Route و سند واحد OpenAPI میپیوندند. مستندات صریح است: "The APIRouters are not 'mounted', they are not isolated from the rest of the application." برنامهٔ Mountشده باapp.mountجداست: مستندات و پشتهٔ Middleware خودش را دارد و رویداد lifespan دریافت نمیکند. - «با هر دسترسی، settings دوباره خوانده میشود.»
Settings()محیط،.envو Secrets directory را هنگام ساخت شیء میخواند. با@lru_cacheرویget_settings()این اتفاق یک بار در هر پردازه (Process) میافتد. تغییر بعدی متغیر محیطی تا پاکشدن Cache اثری ندارد؛test_get_settings_is_cached_until_clearedهمین را میسنجد. - «پوشههای Feature فقط نامگذاری متفاوتاند.» تفاوت در محل تغییر است. با Layer، تغییر یک Feature همهٔ پوشههای Layer را درگیر میکند؛ با Feature یک پوشه تغییر میکند و مرزش قابل اعمال است؛ مثلاً
orders/فقط اجازهٔ import ازcatalog/service.pyرا دارد. همین مرز بعداً جداسازی ماژول به سرویس را ممکن میکند.
از کجا آمده (Where it comes from)
ایده پیش از FastAPI وجود داشته؛ آموزش آن میگوید: "If you come from Flask, this would be the equivalent of Flask's Blueprints." در FastAPI ابتدا include_router آمد و در انتشارهای اولیه ابتدا tags در include_router، سپس responses و بعد dependencies به آن اضافه شدند. نسخهٔ 0.62.0 در ۲۰۲۰-۱۱-۲۹ بیشتر گزینهها را به خود Router برد: "Up to now, for several options, the only way to apply them to a group of path operations was in include_router … Most of these settings are now supported in APIRouter, which normally lives closer to the related code, so it is recommended to use APIRouter when possible." نسخهٔ 0.75.0 در ۲۰۲۲-۰۳-۰۴، generate_unique_id_function اختصاصی و مستندات "Generate Clients" را اضافه کرد. نسخهٔ 0.93.0 در ۲۰۲۳-۰۳-۰۷، Context managerهای lifespan را آورد: "superseding startup and shutdown events". نسخهٔ 0.100.0 در ۲۰۲۳-۰۷-۰۷ به Pydantic v2 رفت و settings از Pydantic جدا شد: "To use settings you should now import from pydantic_settings import BaseSettings instead of importing from pydantic directly"؛ pydantic-settings 2.0.0 در ۲۰۲۳-۰۶-۳۰ منتشر شده بود. نسخهٔ 0.112.2 در ۲۰۲۴-۰۸-۲۴ ادغام lifespanهای تودرتو را به include_router آورد: "Ensure that app.include_router merges nested lifespans". نسخهٔ 0.126.0 در ۲۰۲۵-۱۲-۲۰، pydantic-settings را به extra با نام standard افزود. نسخهٔ 0.128.3 در ۲۰۲۶-۰۲-۰۶، on_event را داخل FastAPI دوباره پیاده کرد: "for compatibility with the next Starlette"؛ 0.133.0 در ۲۰۲۶-۰۲-۲۴ نیز Starlette 1.0.0+ را پشتیبانی کرد. تغییر ساختاری اصلی این فصل 0.137.0 در ۲۰۲۶-۰۶-۱۴ است: "Refactor internals to preserve APIRouter and APIRoute instances". پیش از آن "router.include_router(other_router) would take each path operation from other_router and 'clone' it"؛ پس از آن Route افزودهشده بعد از include دیده میشود و router.routes درخت است، نه فهرست تخت. نسخهٔ 0.138.0 در ۲۰۲۶-۰۶-۲۰، app.frontend("/", directory="dist") را برای Frontend تکصفحهای اضافه کرد و 0.146.0 در ۲۰۲۶-۱۰-۱۸، FastAPI(root_path=...) را به نفع گزینهٔ سرور منسوخ کرد.
در Python، واردکردن نسبی (Relative import) با نقطههای ابتدایی از PEP 328 میآید؛ ایجادشده در ۲۱ دسامبر ۲۰۰۳ برای Python 2.4–2.6. بستهٔ بدون __init__.py یا بستهٔ فضای نام (Namespace package) از PEP 420، ایجادشده در ۱۹ آوریل ۲۰۱۲ برای Python 3.3، آمده است. بحث src layout در برابر flat در Python Packaging User Guide قرار دارد.
1 2003-12 PEP 328 created (Python 2.4-2.6): relative imports with leading dots
2 2012 PEP 420 (Python 3.3): namespace packages without __init__.py
3 2020-11 FastAPI 0.62.0: prefix, tags, dependencies, responses on APIRouter itself
4 2022-03 FastAPI 0.75.0: generate_unique_id_function, "Generate Clients" docs
5 2023-03 FastAPI 0.93.0: lifespan= supersedes startup/shutdown events
6 2023-06/07 pydantic-settings 2.0.0; FastAPI 0.100.0 imports BaseSettings from pydantic_settings
7 2024-08 FastAPI 0.112.2: include_router merges nested router lifespans
8 2026-02 FastAPI 0.128.3 re-implements on_event; 0.133.0 supports Starlette 1.0
9 2026-06 FastAPI 0.137.0: routers kept live (no copy at include); 0.138.0 app.frontend()
10 2026-10/11 FastAPI 0.146.0 deprecates FastAPI(root_path=); 0.165.0 latest (needs Python >= 3.11)Python
قبل (Before)
تمام API کاتالوگ و سفارش در یک ماژول است. پیکربندی از os.environ هنگام import و به شکل رشته خوانده میشود؛ Connection مربوط به SQLite هم همان موقع باز میشود. /api/v1 و tag روی هر Decorator تکرار میشوند؛ یک بار products و یک بار Products. اعلان /api/v1/products/featured بعد از /api/v1/products/{product_id} است. Route بازنشانی ادمین عمومی است و در /docs دیده میشود؛ کار Startup هم در hook منسوخ on_event است.
"""BEFORE: the whole service in one module.
It works on a quiet day. Every problem below is pinned down by tests/before/test_before.py:
config read from os.environ at import time as raw strings, a database connection opened at import,
the /api/v1 prefix and the tag repeated (and misspelled) on every route, a literal route declared
after the parameter route that swallows it, an admin route that is public and listed in the docs,
and startup work in the deprecated on_event hook.
"""
from __future__ import annotations
import os
import sqlite3
from fastapi import FastAPI, HTTPException
# Read once, at import, as strings. "false" is a non-empty string, so DEBUG is truthy.
DEBUG = os.environ.get("SHOP_DEBUG", "false")
DATABASE_URL = os.environ.get("SHOP_DATABASE_URL", ":memory:")
PAGE_SIZE = os.environ.get("SHOP_PAGE_SIZE", "20") # a str; every caller must remember int()
# Opened when the module is imported: by uvicorn, by every test, by a script that only wants a constant.
conn = sqlite3.connect(DATABASE_URL, check_same_thread=False)
conn.execute("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, sku TEXT, name TEXT, price_cents INTEGER)")
app = FastAPI(debug=bool(DEBUG))
@app.on_event("startup") # deprecated; ignored entirely once a lifespan= is added
def seed() -> None:
conn.execute("DELETE FROM products")
conn.executemany(
"INSERT INTO products (id, sku, name, price_cents) VALUES (?, ?, ?, ?)",
[(1, "BK-001", "The Pragmatic Programmer", 4200), (2, "GM-001", "Catan", 4500)],
)
@app.get("/api/v1/products", tags=["products"])
def list_products(limit: int = int(PAGE_SIZE)):
rows = conn.execute("SELECT id, sku, name, price_cents FROM products ORDER BY id LIMIT ?", (limit,))
return [dict(zip(("id", "sku", "name", "price_cents"), r)) for r in rows]
@app.get("/api/v1/products/{product_id}", tags=["Products"]) # a second spelling: a second docs group
def get_product(product_id: int):
row = conn.execute("SELECT id, sku, name, price_cents FROM products WHERE id = ?", (product_id,)).fetchone()
if row is None:
raise HTTPException(404, "Product not found")
return dict(zip(("id", "sku", "name", "price_cents"), row))
@app.get("/api/v1/products/featured", tags=["products"]) # never reached: {product_id} matched first
def featured_products():
return [{"id": 2, "sku": "GM-001"}]
@app.get("/api/v1/orders/{order_id}", tags=["orders"])
def get_order(order_id: int):
raise HTTPException(404, "Order not found")
@app.post("/api/v1/admin/reset") # no auth, no tag, and listed in /docs for everyone
def admin_reset():
conn.execute("DELETE FROM products")
return {"reset": True}تست هر مشکل را مشخص میکند: bool("false") برابر True است؛ Connection بهمحض import وجود دارد؛ featured پاسخ ۴۲۲ میدهد؛ مستندات برای یک منبع دو گروه دارند و Route ادمین را نشان میدهند؛ و operationId پیشفرض get_product_api_v1_products__product_id__get است.
"""Pins down every problem of the flat before/main.py."""
from __future__ import annotations
from fastapi.testclient import TestClient
from before import main as before
def test_string_config_is_truthy():
assert before.DEBUG == "false"
assert bool(before.DEBUG) is True # the classic bug: "false" enables debug mode
assert before.app.debug is True
assert isinstance(before.PAGE_SIZE, str)
def test_connection_was_opened_at_import():
# Importing the module for a test already created a connection; nothing closes it.
assert before.conn.execute("SELECT 1").fetchone() == (1,)
def test_literal_route_after_parameter_route_is_shadowed():
with TestClient(before.app) as client:
r = client.get("/api/v1/products/featured")
assert r.status_code == 422 # "featured" was parsed as product_id: int
assert r.json()["detail"][0]["type"] == "int_parsing"
def test_tags_are_inconsistent_and_admin_is_public():
schema = before.app.openapi()
tags = {t for path in schema["paths"].values() for op in path.values() for t in op.get("tags", [])}
assert {"products", "Products"} <= tags # two docs groups for one resource
assert "/api/v1/admin/reset" in schema["paths"] # listed in /docs, no auth
with TestClient(before.app) as client:
assert client.post("/api/v1/admin/reset").json() == {"reset": True}
def test_default_operation_ids_are_long():
ops = before.app.openapi()["paths"]["/api/v1/products/{product_id}"]["get"]
assert ops["operationId"] == "get_product_api_v1_products__product_id__get"بعد (After)
همان API را در دو Layout این فصل میسازیم. نخست بر اساس Layer فنی: برای هر Layer یک Package و درون آن برای هر منبع یک ماژول.
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import AsyncIterator
from fastapi import APIRouter, FastAPI
from .db import Database
from .routers import orders, products
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app.state.db = Database()
app.state.db.connect()
yield
app.state.db.close()
def create_app(admin_token: str = "change-me") -> FastAPI:
app = FastAPI(title="Shop API (by layer)", lifespan=lifespan)
app.state.admin_token = admin_token
v1 = APIRouter(prefix="/api/v1")
v1.include_router(products.router) # include children BEFORE including v1 in the app (copy at include, 0.128.8)
v1.include_router(orders.router)
app.include_router(v1)
return appfrom __future__ import annotations
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from ..repositories.orders import OrderRepository
from ..repositories.products import ProductRepository
from ..schemas.orders import OrderIn, OrderOut
from ..services.orders import UnknownProduct, place_order
from .deps import order_repo, product_repo
router = APIRouter(prefix="/orders", tags=["orders"])
@router.post("", response_model=OrderOut, status_code=status.HTTP_201_CREATED)
def create_order(
body: OrderIn,
products: Annotated[ProductRepository, Depends(product_repo)],
orders: Annotated[OrderRepository, Depends(order_repo)],
):
try:
return place_order(products, orders, body.product_id, body.quantity)
except UnknownProduct:
raise HTTPException(422, "Unknown product") from None
@router.get("/{order_id}", response_model=OrderOut)
def get_order(order_id: int, orders: Annotated[OrderRepository, Depends(order_repo)]):
order = orders.get(order_id)
if order is None:
raise HTTPException(404, "Order not found")
return orderfrom __future__ import annotations
from ..models.orders import Order
from ..repositories.orders import OrderRepository
from ..repositories.products import ProductRepository
class UnknownProduct(Exception):
pass
def place_order(products: ProductRepository, orders: OrderRepository, product_id: int, quantity: int) -> Order:
"""Business rule lives here, not in the router: price is looked up, never taken from the client."""
product = products.get(product_id)
if product is None:
raise UnknownProduct(product_id)
return orders.add(product_id, quantity, product.price_cents * quantity)سپس بر اساس Feature: در shop/ برای هر قابلیت کسبوکار یک Package، مثل catalog/ و orders/، داریم؛ core/ برای نیاز مشترک همهٔ Featureها و internal/ برای Router مشترک با پروژههای دیگر است. ابتدا settings:
from __future__ import annotations
import os
from functools import lru_cache
from typing import Literal
from pydantic import Field, SecretStr, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
Environment = Literal["dev", "test", "staging", "prod"]
class Settings(BaseSettings):
"""Typed settings: every value arrives converted and validated, or the process refuses to start."""
model_config = SettingsConfigDict(
env_prefix="SHOP_", # SHOP_DATABASE_URL -> database_url (case-insensitive by default)
env_file=".env", # relative to the current working directory, not to this file
env_file_encoding="utf-8",
extra="forbid", # the default: a typo in .env is an error, not a silently ignored line
)
app_name: str = "Shop API"
environment: Environment = "dev"
database_url: str = "sqlite:///:memory:"
seed_demo_data: bool = True
docs_enabled: bool = True
api_prefix: str = "/api"
cors_origins: list[str] = [] # JSON in the environment: SHOP_CORS_ORIGINS='["https://shop.example"]'
admin_token: SecretStr = SecretStr("change-me") # repr shows '**********'
payments_base_url: str = "https://payments.invalid"
http_timeout_s: float = Field(default=2.0, gt=0, le=30)
@model_validator(mode="after")
def no_default_secrets_outside_dev(self) -> "Settings":
"""Refuse to start staging/prod with the public placeholder token: fail at startup, not at the first attack."""
if self.environment in ("staging", "prod") and self.admin_token.get_secret_value() == "change-me":
raise ValueError(f"SHOP_ADMIN_TOKEN must be set in {self.environment} (the default 'change-me' is public)")
return self
def load_settings(environment: str | None = None) -> Settings:
"""Per-environment config: .env, then .env.<environment> on top; real env vars beat both.
Secrets come from files (one file per value, file name = field name) when SHOP_SECRETS_DIR is set,
e.g. /run/secrets in Docker or a mounted Kubernetes Secret volume.
"""
env = environment or os.environ.get("SHOP_ENVIRONMENT", "dev")
secrets_dir = os.environ.get("SHOP_SECRETS_DIR") # read before Settings exists, so plain os.environ
return Settings(_env_file=(".env", f".env.{env}"), _secrets_dir=secrets_dir)
@lru_cache
def get_settings() -> Settings:
"""The Settings dependency: built once per process, overridable in tests."""
return load_settings()Lifespan، پایگاه داده و Client خروجی HTTP را یک بار در هر Process باز میکند:
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import AsyncIterator
import httpx
from fastapi import FastAPI
from .config import Settings
from .db import Database
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
"""Startup before `yield`, shutdown after it. Runs once per worker process, not per request."""
settings: Settings = app.state.settings
db = Database(settings.database_url)
db.connect(seed=settings.seed_demo_data)
http = httpx.AsyncClient(base_url=settings.payments_base_url, timeout=settings.http_timeout_s)
app.state.db = db # reached from handlers as request.app.state.db
app.state.http = http
app.state.events.append("startup")
try:
yield
finally: # runs on SIGTERM/SIGINT, and when `with TestClient(app)` exits
await http.aclose()
db.close()
app.state.events.append("shutdown")from __future__ import annotations
import secrets
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request, status
from .config import Settings, get_settings
from .db import Database
SettingsDep = Annotated[Settings, Depends(get_settings)]
def get_db(request: Request) -> Database:
return request.app.state.db
DbDep = Annotated[Database, Depends(get_db)]
def require_admin(settings: SettingsDep, x_admin_token: Annotated[str | None, Header()] = None) -> None:
"""Router-level dependency for the admin router: runs before every admin path operation."""
expected = settings.admin_token.get_secret_value()
if x_admin_token is None or not secrets.compare_digest(x_admin_token, expected):
raise HTTPException(status.HTTP_403_FORBIDDEN, "Admin token required")Feature کاتالوگ: Router با prefix، tag، مستندات مشترک ۴۰۴ و lifespan خودش؛ Repository مالک SQL است و سرویس (Service) رابط عمومی Feature را تشکیل میدهد.
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator
from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from shop.core.deps import DbDep, require_admin
from .repository import ProductRepository
from .schemas import ProductIn, ProductOut
@asynccontextmanager
async def catalog_lifespan(app: FastAPI) -> AsyncIterator[None]:
"""A router-level lifespan: merged into the app's by include_router, runs inside the app's lifespan."""
app.state.featured_ids = [p.id for p in ProductRepository(app.state.db).list(featured_only=True)]
app.state.events.append("catalog:startup")
yield
app.state.events.append("catalog:shutdown")
router = APIRouter(
prefix="/products",
tags=["catalog"],
responses={404: {"description": "Product not found"}}, # documented on every route of this router
lifespan=catalog_lifespan,
)
def repo(db: DbDep) -> ProductRepository:
return ProductRepository(db)
Repo = Annotated[ProductRepository, Depends(repo)]
@router.get("", response_model=list[ProductOut])
def list_products(repo: Repo):
return repo.list()
@router.get("/featured", response_model=list[ProductOut]) # literal before {product_id}
def list_featured_products(repo: Repo):
return repo.list(featured_only=True)
@router.get("/{product_id}", response_model=ProductOut)
def get_product(product_id: int, repo: Repo):
product = repo.get(product_id)
if product is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Product not found")
return product
@router.post(
"",
response_model=ProductOut,
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(require_admin)], # one route guarded; the admin router guards all of its routes
responses={403: {"description": "Admin token required"}},
)
def create_product(body: ProductIn, repo: Repo):
return repo.add(body.sku, body.name, body.price_cents)from __future__ import annotations
from shop.core.db import Database
from .models import Product
COLUMNS = "id, sku, name, price_cents, featured"
class ProductRepository:
def __init__(self, db: Database) -> None:
self.db = db
def list(self, featured_only: bool = False) -> list[Product]:
sql = f"SELECT {COLUMNS} FROM products" + (" WHERE featured = 1" if featured_only else "") + " ORDER BY id"
with self.db.lock:
return [Product(**dict(r)) for r in self.db.conn.execute(sql).fetchall()]
def get(self, product_id: int) -> Product | None:
with self.db.lock:
row = self.db.conn.execute(f"SELECT {COLUMNS} FROM products WHERE id = ?", (product_id,)).fetchone()
return Product(**dict(row)) if row else None
def add(self, sku: str, name: str, price_cents: int) -> Product:
with self.db.lock:
cur = self.db.conn.execute(
"INSERT INTO products (sku, name, price_cents) VALUES (?, ?, ?)", (sku, name, price_cents)
)
self.db.conn.commit()
return Product(cur.lastrowid, sku, name, price_cents, False)"""The catalog's public surface for other features. orders imports this module, never catalog.router."""
from __future__ import annotations
from shop.core.db import Database
from .models import Product
from .repository import ProductRepository
def find_product(db: Database, product_id: int) -> Product | None:
return ProductRepository(db).get(product_id)Feature سفارش فقط از طریق catalog.service اجازهٔ استفاده از کاتالوگ دارد:
from __future__ import annotations
from shop.catalog.service import find_product # across features: absolute import of the public surface
from shop.core.db import Database
from .models import Order
from .repository import OrderRepository # inside the feature: relative import
class UnknownProduct(Exception):
"""Domain error; the router maps it to HTTP. The service knows nothing about status codes."""
def place_order(db: Database, product_id: int, quantity: int) -> Order:
product = find_product(db, product_id)
if product is None:
raise UnknownProduct(product_id)
return OrderRepository(db).add(product_id, quantity, product.price_cents * quantity)from __future__ import annotations
from fastapi import APIRouter, HTTPException, status
from shop.core.deps import DbDep
from .repository import OrderRepository
from .schemas import OrderIn, OrderOut
from .service import UnknownProduct, place_order
router = APIRouter(prefix="/orders", tags=["orders"], responses={404: {"description": "Order not found"}})
@router.post("", response_model=OrderOut, status_code=status.HTTP_201_CREATED)
def create_order(body: OrderIn, db: DbDep):
try:
return place_order(db, body.product_id, body.quantity)
except UnknownProduct:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "Unknown product") from None
@router.get("/{order_id}", response_model=OrderOut)
def get_order(order_id: int, db: DbDep):
order = OrderRepository(db).get(order_id)
if order is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Order not found")
return orderRouter مشترک میان پروژهها را کاملاً کسی پیکربندی میکند که آن را include میکند:
"""A router shared between projects: no prefix, no auth, no tags of its own.
The including app decides all of that in include_router(), so the file stays reusable as is.
"""
from __future__ import annotations
from fastapi import APIRouter, Request
router = APIRouter()
@router.get("/stats")
def stats(request: Request):
db = request.app.state.db
with db.lock:
(orders,) = db.conn.execute("SELECT COUNT(*) FROM orders").fetchone()
return {"orders": orders, "lifespan_events": request.app.state.events}درخت Router: v1 شامل catalog، orders و Router پنهان admin؛ v2 دارای قرارداد تازهٔ catalog:
from __future__ import annotations
from fastapi import APIRouter, Depends
from shop.catalog import router as catalog
from shop.catalog import router_v2 as catalog_v2
from shop.core.deps import require_admin
from shop.internal import admin
from shop.orders import router as orders
def build_api_router() -> APIRouter:
"""The route tree under the API prefix. Built in a function so every create_app() gets a fresh tree.
FastAPI 0.128.8 copies routes at include time, so children are included into v1/v2 BEFORE
v1/v2 are included into the app (0.137.0+ keeps the routers live and the order stops mattering).
"""
v1 = APIRouter(prefix="/v1")
v1.include_router(catalog.router)
v1.include_router(orders.router)
v1.include_router(
admin.router,
prefix="/admin",
tags=["admin"],
dependencies=[Depends(require_admin)], # every admin route, without editing admin.py
responses={403: {"description": "Admin token required"}},
include_in_schema=False, # hidden from /docs and /openapi.json; still reachable
)
v2 = APIRouter(prefix="/v2")
v2.include_router(catalog_v2.router)
api = APIRouter()
api.include_router(v1)
api.include_router(v2)
return apiApp factory و Entry point مربوط به Process:
from __future__ import annotations
import time
import uuid
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles
from shop.api import build_api_router
from shop.core.config import Settings, get_settings
from shop.core.lifespan import lifespan
from shop.core.router import router as meta_router
from shop.legacy import create_legacy_app
STATIC_DIR = Path(__file__).parent / "static"
TAGS_METADATA = [ # order here = order of the groups in /docs
{"name": "catalog", "description": "Products, prices and the featured list."},
{"name": "orders", "description": "Placing and reading orders. Prices come from the catalog."},
{"name": "catalog-v2", "description": "v2 of the catalog: prices as money objects."},
{"name": "meta", "description": "Version and environment."},
]
def unique_id(route: APIRoute) -> str:
"""operationId = '<first tag>-<function name>', e.g. 'catalog-get_product' -> SDK method getProduct."""
return f"{route.tags[0]}-{route.name}" if route.tags else route.name
def create_app(settings: Settings | None = None) -> FastAPI:
"""App factory: build a fresh, fully wired app for this settings object (tests pass their own)."""
settings = settings or get_settings()
app = FastAPI(
title=settings.app_name,
version="1.0.0",
lifespan=lifespan,
openapi_tags=TAGS_METADATA,
generate_unique_id_function=unique_id,
openapi_url="/openapi.json" if settings.docs_enabled else None, # None also removes /docs and /redoc
)
app.state.settings = settings
app.state.events = []
app.dependency_overrides[get_settings] = lambda: settings # Depends(get_settings) sees the same object
@app.middleware("http")
async def request_id(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
response.headers["x-request-id"] = request.headers.get("x-request-id", uuid.uuid4().hex)
response.headers["x-process-time-ms"] = f"{(time.perf_counter() - start) * 1000:.2f}"
return response
if settings.cors_origins: # added last = outermost: CORS answers preflights before anything else runs
app.add_middleware(CORSMiddleware, allow_origins=settings.cors_origins, allow_methods=["*"])
app.include_router(build_api_router(), prefix=settings.api_prefix) # /api/v1/..., /api/v2/...
app.include_router(meta_router) # /healthz (hidden), /version
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/legacy", create_legacy_app()) # its own /legacy/docs and /legacy/openapi.json
return app"""The process entry point: `uvicorn shop.asgi:app` or `fastapi run` ([tool.fastapi] entrypoint).
Alternative without a module-level object: `uvicorn --factory shop.main:create_app`.
"""
from shop.main import create_app
app = create_app()تستها ساختار Package را تکرار میکنند: tests/shop/catalog/، tests/shop/orders/، tests/shop/core/. Fixture در سطحی قرار میگیرد که به آن نیاز دارد:
"""Root conftest: fixtures every test folder can use. Folder conftests add their own on top."""
from __future__ import annotations
import pytest
from shop.core.config import Settings, get_settings
@pytest.fixture(autouse=True)
def clean_settings_cache(monkeypatch: pytest.MonkeyPatch):
# No test may see the developer's SHOP_* variables or a cached Settings from another test.
import os
for key in [k for k in os.environ if k.startswith("SHOP_")]:
monkeypatch.delenv(key)
get_settings.cache_clear()
yield
get_settings.cache_clear()
@pytest.fixture()
def settings() -> Settings:
# _env_file=None: ignore any .env in the working directory; values are explicit.
return Settings(_env_file=None, environment="test", admin_token="test-admin", docs_enabled=True)"""Fixtures for the feature package's tests: placed in tests/shop/, so tests/layered/ never sees them."""
from __future__ import annotations
from typing import Iterator
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from shop.core.config import Settings
from shop.main import create_app
@pytest.fixture()
def app(settings: Settings) -> FastAPI:
return create_app(settings) # a fresh app per test: no state leaks between tests
@pytest.fixture()
def client(app: FastAPI) -> Iterator[TestClient]:
with TestClient(app) as c: # `with` runs the lifespan
yield c
@pytest.fixture()
def admin_headers(settings: Settings) -> dict[str, str]:
return {"x-admin-token": settings.admin_token.get_secret_value()}"""What the app factory wires: OpenAPI organisation, hidden routes, mounts, static files, middleware."""
from __future__ import annotations
from fastapi.testclient import TestClient
from shop.main import create_app
def test_tags_metadata_and_operation_ids(app):
schema = app.openapi()
assert [t["name"] for t in schema["tags"]] == ["catalog", "orders", "catalog-v2", "meta"]
ops = [op["operationId"] for path in schema["paths"].values() for op in path.values()]
assert len(ops) == len(set(ops)) # unique across v1 and v2 although both functions are get_product
assert {"catalog-get_product", "catalog-v2-get_product", "orders-create_order"} <= set(ops)
def test_router_responses_are_merged(app):
get_op = app.openapi()["paths"]["/api/v1/products/{product_id}"]["get"]
post_op = app.openapi()["paths"]["/api/v1/products"]["post"]
assert "404" in get_op["responses"] # from APIRouter(responses=...)
assert {"201", "403", "404", "422"} <= set(post_op["responses"]) # router + route + defaults
def test_internal_routes_are_hidden_but_guarded(client, admin_headers):
paths = client.get("/openapi.json").json()["paths"]
assert not any(p.startswith("/api/v1/admin") for p in paths) and "/healthz" not in paths
assert client.get("/api/v1/admin/stats").status_code == 403 # hidden is not protected; the dependency is
assert client.get("/api/v1/admin/stats", headers=admin_headers).json()["orders"] == 0
def test_mounted_sub_application_is_independent(client):
assert not any(p.startswith("/legacy") for p in client.get("/openapi.json").json()["paths"])
assert "/report" in client.get("/legacy/openapi.json").json()["paths"]
assert client.get("/legacy/docs").status_code == 200
assert client.get("/legacy/report").json() == {"lifespan_ran": False, "root_path": "/legacy"}
def test_static_mount_and_middleware(client):
r = client.get("/static/robots.txt")
assert r.status_code == 200 and "Disallow: /api/" in r.text
assert "x-request-id" in client.get("/nope").headers # middleware wraps 404s too
assert client.get("/version", headers={"x-request-id": "abc"}).headers["x-request-id"] == "abc"
def test_docs_can_be_switched_off(settings):
app = create_app(settings.model_copy(update={"docs_enabled": False}))
with TestClient(app) as client:
assert client.get("/openapi.json").status_code == 404
assert client.get("/docs").status_code == 404
assert client.get("/version").json() == {"app": "Shop API", "environment": "test"}
def test_cors_is_outermost_when_enabled(settings):
app = create_app(settings.model_copy(update={"cors_origins": ["https://shop.example"]}))
with TestClient(app) as client:
r = client.options(
"/api/v1/products",
headers={"Origin": "https://shop.example", "Access-Control-Request-Method": "GET"},
)
assert r.status_code == 200 and r.headers["access-control-allow-origin"] == "https://shop.example"
assert "x-request-id" not in r.headers # the preflight never reached the inner middleware"""Where a value comes from: init kwargs > environment > .env files (later wins) > secrets dir > default."""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from shop.core.config import Settings, get_settings, load_settings
def test_defaults_and_types():
s = Settings(_env_file=None)
assert s.environment == "dev" and s.http_timeout_s == 2.0 and s.cors_origins == []
assert repr(s.admin_token) == "SecretStr('**********')"
def test_environment_variables_are_converted(monkeypatch):
monkeypatch.setenv("SHOP_HTTP_TIMEOUT_S", "5")
monkeypatch.setenv("SHOP_DOCS_ENABLED", "false")
monkeypatch.setenv("SHOP_CORS_ORIGINS", '["https://shop.example"]')
s = Settings(_env_file=None)
assert s.http_timeout_s == 5.0 and s.docs_enabled is False and s.cors_origins == ["https://shop.example"]
def test_invalid_value_fails_at_startup(monkeypatch):
monkeypatch.setenv("SHOP_ENVIRONMENT", "production") # not one of dev/test/staging/prod
with pytest.raises(ValidationError) as exc:
Settings(_env_file=None)
assert exc.value.errors()[0]["type"] == "literal_error"
def test_priority_env_over_dotenv_over_secrets(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path) # env_file is resolved against the working directory
(tmp_path / ".env").write_text("SHOP_APP_NAME=from-dotenv\nSHOP_ADMIN_TOKEN=from-dotenv\n")
secrets = tmp_path / "secrets"
secrets.mkdir()
(secrets / "shop_admin_token").write_text("from-secret-file") # file name = prefix + field name
(secrets / "shop_app_name").write_text("from-secret-file")
(secrets / "shop_payments_base_url").write_text("https://payments.example")
monkeypatch.setenv("SHOP_APP_NAME", "from-env")
s = Settings(_secrets_dir=str(secrets))
assert s.app_name == "from-env" # real environment beats .env
assert s.admin_token.get_secret_value() == "from-dotenv" # .env beats the secrets dir
assert s.payments_base_url == "https://payments.example" # secrets dir beats the default
assert Settings(_secrets_dir=str(secrets), app_name="from-init").app_name == "from-init" # init beats all
def test_per_environment_file_overrides_base(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
(tmp_path / ".env").write_text("SHOP_APP_NAME=base\nSHOP_DOCS_ENABLED=true\n")
(tmp_path / ".env.prod").write_text("SHOP_DOCS_ENABLED=false\n")
prod = load_settings("prod")
assert prod.app_name == "base" and prod.docs_enabled is False
assert load_settings("dev").docs_enabled is True # no .env.dev: only the base file
def test_typo_in_dotenv_is_an_error(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
(tmp_path / ".env").write_text("SHOP_DATABSE_URL=sqlite:///typo.db\n")
with pytest.raises(ValidationError) as exc:
Settings()
assert exc.value.errors()[0]["type"] == "extra_forbidden"
def test_get_settings_is_cached_until_cleared(monkeypatch):
monkeypatch.chdir("/") # no .env here
first = get_settings()
monkeypatch.setenv("SHOP_APP_NAME", "changed")
assert get_settings() is first # lru_cache: read once per process
get_settings.cache_clear()
assert get_settings().app_name == "changed"
@pytest.mark.parametrize("environment", ["staging", "prod"])
def test_default_admin_token_is_refused_outside_dev(monkeypatch, environment):
monkeypatch.setenv("SHOP_ENVIRONMENT", environment)
with pytest.raises(ValidationError, match="SHOP_ADMIN_TOKEN must be set"):
Settings(_env_file=None)
monkeypatch.setenv("SHOP_ADMIN_TOKEN", "a-real-token")
assert Settings(_env_file=None).environment == environmentfrom __future__ import annotations
from fastapi.testclient import TestClient
from shop.main import create_app
def test_lifespan_runs_only_inside_with(settings):
app = create_app(settings)
TestClient(app) # no `with`: no startup
assert app.state.events == []
with TestClient(app) as client:
assert app.state.events == ["startup", "catalog:startup"] # app lifespan first, router lifespan inside it
assert client.get("/healthz").json() == {"status": "ok"}
assert app.state.featured_ids == [2, 3]
assert app.state.events == ["startup", "catalog:startup", "catalog:shutdown", "shutdown"]
assert app.state.db.conn is None and app.state.http.is_closed
def test_each_app_has_its_own_state(settings):
a, b = create_app(settings), create_app(settings)
with TestClient(a), TestClient(b):
assert a.state.db is not b.state.dbهر قاعدهٔ Router یک تست کوچک روی نسخهٔ ثابتشدهٔ FastAPI دارد:
"""APIRouter rules, each pinned down on the pinned FastAPI (0.128.8)."""
from __future__ import annotations
import warnings
import pytest
from fastapi import APIRouter, Depends, FastAPI
from fastapi.responses import HTMLResponse
from fastapi.testclient import TestClient
def test_routes_added_after_include_are_missing_on_0_128():
router = APIRouter()
app = FastAPI()
app.include_router(router) # 0.128.8 copies the routes that exist *now*
@router.get("/late")
def late():
return {"ok": True}
assert TestClient(app).get("/late").status_code == 404 # 0.137.0+: 200 (routers stay live)
def test_nested_router_must_be_complete_before_it_is_included():
parent, child = APIRouter(prefix="/v1"), APIRouter(prefix="/items")
app = FastAPI()
parent.include_router(child) # child is still empty: nothing is copied
@child.get("")
def list_items():
return []
app.include_router(parent)
assert TestClient(app).get("/v1/items").status_code == 404
def test_route_order_across_routers():
by_id, me = APIRouter(prefix="/users"), APIRouter(prefix="/users")
@by_id.get("/{user_id}")
def get_user(user_id: int):
return {"id": user_id}
@me.get("/me")
def get_me():
return {"id": "me"}
wrong, right = FastAPI(), FastAPI()
wrong.include_router(by_id)
wrong.include_router(me)
right.include_router(me)
right.include_router(by_id)
assert TestClient(wrong).get("/users/me").status_code == 422 # {user_id} matched first, int parsing failed
assert TestClient(right).get("/users/me").json() == {"id": "me"}
def test_path_conflict_first_router_wins_silently():
a, b = APIRouter(), APIRouter()
@a.get("/ping")
def ping_a():
return "a"
@b.get("/ping")
def ping_b():
return "b"
app = FastAPI()
app.include_router(a)
app.include_router(b) # no error, no warning at include time
assert TestClient(app).get("/ping").json() == "a"
def test_prefix_rules():
with pytest.raises(AssertionError, match="must not end with '/'"):
APIRouter(prefix="/items/")
with pytest.raises(AssertionError, match="must start with '/'"):
FastAPI().include_router(APIRouter(), prefix="items")
r = APIRouter()
with pytest.raises(AssertionError, match="Cannot include the same APIRouter instance into itself"):
r.include_router(r)
def _status_router() -> APIRouter:
r = APIRouter()
@r.get("/status")
def status_():
return "up"
return r
def test_same_router_under_two_prefixes():
app = FastAPI()
r = _status_router()
app.include_router(r, prefix="/api/v1")
app.include_router(r, prefix="/api/latest")
client = TestClient(app)
assert client.get("/api/v1/status").json() == client.get("/api/latest/status").json() == "up"
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
ids = [op["get"]["operationId"] for op in app.openapi()["paths"].values()]
assert ids == ["status__api_v1_status_get", "status__api_latest_status_get"] # default id contains the path
assert not caught
def test_function_name_ids_collide_when_a_router_is_mounted_twice():
app = FastAPI(generate_unique_id_function=lambda route: route.name)
r = _status_router()
app.include_router(r, prefix="/api/v1")
app.include_router(r, prefix="/api/latest")
with pytest.warns(UserWarning, match="Duplicate Operation ID status_"):
app.openapi()
def test_duplicate_operation_id_warns_when_schema_is_built():
r = APIRouter()
@r.get("/a", operation_id="read")
def read_a():
return 1
@r.get("/b", operation_id="read")
def read_b():
return 2
app = FastAPI()
app.include_router(r)
with pytest.warns(UserWarning, match="Duplicate Operation ID read for function read_b"):
app.openapi()
def test_dependency_order_router_then_decorator_then_parameters():
calls: list[str] = []
def app_dep():
calls.append("app")
def include_dep():
calls.append("include_router")
def router_dep():
calls.append("APIRouter")
def decorator_dep():
calls.append("decorator")
def param_dep():
calls.append("parameter")
return 1
r = APIRouter(dependencies=[Depends(router_dep)])
@r.get("/x", dependencies=[Depends(decorator_dep)])
def x(value: int = Depends(param_dep)):
return value
app = FastAPI(dependencies=[Depends(app_dep)])
app.include_router(r, dependencies=[Depends(include_dep)])
TestClient(app).get("/x")
assert calls == ["app", "include_router", "APIRouter", "decorator", "parameter"]
def test_router_default_response_class_and_include_in_schema():
pages = APIRouter(default_response_class=HTMLResponse)
@pages.get("/hello")
def hello():
return "<h1>hello</h1>"
app = FastAPI()
app.include_router(pages, include_in_schema=False)
r = TestClient(app).get("/hello")
assert r.headers["content-type"].startswith("text/html") and r.text == "<h1>hello</h1>"
assert "/hello" not in app.openapi()["paths"]
def test_default_operation_ids_can_collide_after_sanitising():
# generate_unique_id: f"{name}{path_format}", every non-word character -> "_", then "_{method}".
dash, underscore = APIRouter(), APIRouter()
@dash.get("/a-b")
def read():
return "dash"
@underscore.get("/a_b")
def read(): # noqa: F811 same function name in another module is common
return "underscore"
app = FastAPI()
app.include_router(dash)
app.include_router(underscore)
with pytest.warns(UserWarning, match="Duplicate Operation ID read_a_b_get"):
app.openapi()
def test_included_router_redirect_slashes_is_not_transferred():
r = APIRouter(redirect_slashes=False)
@r.get("/items/")
def items():
return []
app = FastAPI() # the app's router (redirect_slashes=True) decides, not r
app.include_router(r)
resp = TestClient(app).get("/items", follow_redirects=False)
assert resp.status_code == 307 and resp.headers["location"].endswith("/items/")
strict = FastAPI(redirect_slashes=False)
strict.include_router(r)
assert TestClient(strict).get("/items", follow_redirects=False).status_code == 404و این تست ثابت میکند که Layout تصمیمی داخلی است:
"""Layout is an internal decision: both packages publish the same catalog/orders contract."""
from __future__ import annotations
from layered.main import create_app as create_layered
from shop.main import create_app as create_shop
def _operations(app) -> set[tuple[str, str]]:
paths = app.openapi()["paths"]
return {(method, path) for path, ops in paths.items() for method in ops if path.startswith(("/api/v1/products", "/api/v1/orders"))}
def test_same_paths_and_methods(settings):
layered = _operations(create_layered())
shop = _operations(create_shop(settings))
assert layered == shop # identical catalog/orders operation sets, nothing subtracted
assert len(layered) == 6فایل پروژه؛ یادداشت نسخهها را در ابتدای صفحه ببینید:
[project]
name = "routers-project-structure"
version = "0.1.0"
description = "Snippets for the APIRouter & Project Structure chapter: a flat app, a layer-based package and a feature-based package"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ you can move to the latest releases.
requires-python = ">=3.9"
dependencies = [
"fastapi==0.128.8",
"starlette==0.49.3",
"pydantic==2.13.5",
# BaseSettings lives in its own package since Pydantic v2; 2.12.0 dropped Python 3.9.
"pydantic-settings==2.11.0",
"uvicorn[standard]==0.39.0",
# The outbound HTTP client the lifespan opens once per process.
"httpx==0.28.1",
# Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
"eval-type-backport==0.4.0; python_version < '3.10'",
]
[project.optional-dependencies]
test = [
"pytest==8.4.2",
]
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
# Flat layout: the three import packages sit next to pyproject.toml (see the page for src/).
include = ["before*", "layered*", "shop*"]
[tool.setuptools.package-data]
shop = ["static/*"]
[tool.fastapi]
# `fastapi dev` / `fastapi run` import this object; shop/asgi.py builds it with create_app().
entrypoint = "shop.asgi:app"
[tool.pytest.ini_options]
testpaths = ["tests"]
# importlib mode: test files in different folders may share a base name (pytest's recommendation for new projects).
addopts = "-q -p no:cacheprovider --import-mode=importlib"
pythonpath = ["."]فایل الگوی محیط، .env.example، در کنترل نسخه ثبت میشود و برای کار محلی به .env کپی میشود؛ .env در git نادیده گرفته میشود:
# Copy to .env for local development. Real environment variables always win over this file.
SHOP_ENVIRONMENT=dev
SHOP_DATABASE_URL=sqlite:///./shop-dev.db
SHOP_DOCS_ENABLED=true
SHOP_CORS_ORIGINS=["http://localhost:5173"]
# Secrets do not belong here in staging/production: mount them as files under SHOP_SECRETS_DIR.
SHOP_ADMIN_TOKEN=dev-admin-tokenزاویهٔ Python (The Python angle)
همهٔ اجزای این فصل Python معمولیاند؛ پس باید بدانید هر جزء بر کدام امکان زبان تکیه دارد. ماژول (Module) و Package: پوشهٔ دارای __init__.py یک Package معمولی است و مرجع زبان میگوید: "When a regular package is imported, this __init__.py file is implicitly executed". هر from shop.catalog import router نخست __init__.py بسته را اجرا میکند؛ آن فایلها را خالی یا تقریباً خالی نگه دارید. اثر جانبی زمان import (Import-time side effect): Decorator مثل @router.get هنگام import اجرا میشود، پس import ماژول Router همان چیزی است که Routeها را ثبت میکند. هر کد دیگر سطح ماژول، مثل بازکردن Connection یا خواندن محیط، نیز همان موقع اجرا میشود؛ Factory کار نوع دوم را از زمان import بیرون میبرد. contextlib.asynccontextmanager: lifespan تابع مولد (Generator) با یک yield است که به Async context manager تبدیل میشود. پیش از yield، Startup است و پس از آن Shutdown؛ try/finally تضمین میکند حتی اگر Startup یک lifespan داخلی شکست خورد، Shutdown اجرا شود. functools.lru_cache: نتیجه را برای هر ترکیب آرگومان Cache میکند؛ پس get_settings() بدون آرگومان شبیه متغیر سراسری ساختهشده در اولین نیاز است که با get_settings.cache_clear() بازنشانی میشود. typing.Annotated: تعریف SettingsDep = Annotated[Settings, Depends(get_settings)] وابستگی را یک بار تعریف میکند و نوع واقعی را برای ویرایشگر و mypy نگه میدارد. روی Python 3.11+ میتوانید typing.Self و StrEnum به کار ببرید؛ مثالها برای اجرای روی 3.9 از آنها استفاده نمیکنند.
فهرست مفاهیم (The concept catalogue)
تقسیم منطق میان فایلها: Module، Package و __init__.py (Breaking up logic across files) حیاتی
به زبان ساده: Python کد را با نام ماژول (Module) پیدا میکند. فایل shop/catalog/router.py همان ماژول shop.catalog.router است، چون shop/ و shop/catalog/ بسته (Package) هستند؛ پوشههایی که Python آنها را فضای نام میداند. تقسیم برنامهٔ FastAPI دو مرحله دارد: کد را در ماژولهای یک Package بگذارید و مطمئن شوید پوشهٔ حاوی Package هنگام شروع Uvicorn یا pytest در Path جستوجوی import است.
بدفهمی رایج: «__init__.py یادگار Python 2 است.» بدون آن هم پوشه به شکل Namespace package قابل import است؛ PEP 420 در Python 3.3. اما دو پوشهٔ همنام در Path بیصدا ادغام میشوند. آموزش FastAPI در هر پوشه این فایل را میگذارد: "There are several __init__.py files: one in each directory or subdirectory. This is what allows importing code from one file into another." آموزش Python دلیل را توضیح میدهد: فایلها "are required to make Python treat directories containing the file as packages (unless using a namespace package, a relatively advanced feature). This prevents directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path."
تعریف: توضیح گامبهگام آموزش FastAPI چنین است: "The app directory contains everything. And it has an empty file app/__init__.py, so it is a 'Python package' (a collection of 'Python modules'): app"؛ "There's a subdirectory app/routers/ with another file __init__.py, so it's a 'Python subpackage': app.routers"؛ "The file app/routers/items.py is inside a package, app/routers/, so, it's a submodule: app.routers.items."
file on disk module name found because
1 shop/__init__.py shop the project root is on sys.path (pytest pythonpath = ["."])
2 shop/main.py shop.main shop is a package
3 shop/catalog/__init__.py shop.catalog subpackage
4 shop/catalog/router.py shop.catalog.router submodule; importing it runs @router.get(...) -> routes registered
5 uvicorn shop.asgi:app imports shop -> shop.asgi -> shop.main -> every router module
6 pytest (rootdir = project) tests/shop/... import shop.main the same wayسناریوی واقعی: تقسیم main.py با ۱۲۰۰ خط به app/routers/products.py و app/routers/orders.py؛ اسکریپتی در scripts/ که چون از داخل scripts/ شروع شده، ModuleNotFoundError: No module named 'shop' میدهد؛ کاری در CI که فقط روی ماشین توسعهدهنده موفق بود، چون پوشهٔ کاری او اتفاقاً ریشهٔ پروژه بود.
| جزء | معنا | محل دردسر |
|---|---|---|
| ماژول (Module) | یک فایل .py با نام نقطهدار | دو ماژول همنام در Path |
| بستهٔ معمولی (Regular package) | پوشهٔ دارای __init__.py که هنگام import اجرا میشود | کد سنگین در __init__.py با هر import اجرا میشود |
| بستهٔ فضای نام (Namespace package) | پوشهٔ بدون __init__.py؛ PEP 420 | ادغام بیصدا؛ بعضی ابزارها آن را کشف نمیکنند |
sys.path | محل جستوجوی import؛ ابتدا پوشهٔ اسکریپت یا CWD | اجرا از پوشهای متفاوت |
| رشتهٔ import (Import string) | "shop.asgi:app" برای Uvicorn، entrypoint برای fastapi | CWD نادرست → ModuleNotFoundError |
pythonpath = ["."] | افزودن ریشهٔ پروژه به sys.path توسط pytest | بدون آن و بدون نصب، تست Package را import نمیکند |
راهحل / روش استفاده: برای هر برنامه یک Package سطح بالا مثل shop/، در هر پوشه یک __init__.py خالی، و شروع همهٔ Processها از ریشهٔ پروژه؛ یا پروژه را نصب کنید. به Uvicorn و [tool.fastapi] entrypoint یک Import string بدهید.
کلاس APIRouter (The APIRouter class) حیاتی
به زبان ساده: router = APIRouter() شیئی میدهد که Decoratorهای برنامه را دارد؛ @router.get، @router.post و غیره. عملیات مسیر (Path operation) هر Feature را در ماژول خودش روی آن تعریف میکنید. تا Router جایی include نشود، هیچ درخواستی سرویس داده نمیشود.
بدفهمی رایج: «Router برای تست به FastAPI() مخصوص خود نیاز دارد.» Router بهتنهایی رفتار روبهسرور ندارد؛ تست آن را در FastAPI() موقتی include میکند، مثل test_router_semantics.py، یا از App factory واقعی استفاده میکند. تصور دیگر این است که متغیر حتماً باید router نام داشته باشد. آموزش میگوید: "the variable is called router, but you can name it however you want". مثال ماژول را import میکند: from shop.catalog import router as catalog، تا متغیرهای router دو ماژول روی هم نوشته نشوند؛ هشدار آموزش این است: "the router from users would overwrite the one from items and we wouldn't be able to use them at the same time."
تعریف: آموزش میگوید: "You can think of APIRouter as a 'mini FastAPI' class. All the same options are supported. All the same parameters, responses, dependencies, tags, etc." سازندهٔ 0.128.8، مطابق fastapi/routing.py، این پارامترها را میگیرد: prefix، tags، dependencies، default_response_class، responses، callbacks، routes، redirect_slashes، default، dependency_overrides_provider، route_class، on_startup، on_shutdown، lifespan، deprecated، include_in_schema و generate_unique_id_function. کلاس APIRouter از Router در Starlette ارث میبرد.
shop/catalog/router.py (import time) what exists afterwards
1 router = APIRouter(prefix="/products", tags=["catalog"], router.prefix, router.tags, router.responses,
responses={404: ...}, lifespan=catalog_lifespan) router.lifespan_context
2 @router.get("") def list_products(...) APIRoute path="/products" (prefix already applied)
3 @router.get("/featured") def list_featured_products(...) APIRoute path="/products/featured"
4 @router.get("/{product_id}") def get_product(...) APIRoute path="/products/{product_id}"
5 @router.post("", dependencies=[Depends(require_admin)]) APIRoute path="/products" POST
6 (nothing is served yet: no app has included the router)سناریوی واقعی: catalog/router.py، orders/router.py و users/router.py، هر کدام متعلق به یک تیم؛ یا Package شخص ثالث با APIRouter آماده برای پنل ادمین، سلامت یا احراز هویت که برنامه آن را با prefix و dependencies خودش include میکند.
| پارامتر | محل اعمال | مقدار معمول |
|---|---|---|
prefix | Path همهٔ Routeها | "/products"؛ باید با / شروع شود و نباید با / تمام شود |
tags | tags در OpenAPI برای هر Route | ["catalog"] |
dependencies | پیش از هر Route | [Depends(require_admin)] |
responses | پاسخهای مستندشدهٔ هر Route | {404: {"description": "Product not found"}} |
default_response_class | هر Route بدون response_class مخصوص خود | HTMLResponse برای Router صفحهها |
deprecated / include_in_schema | همهٔ Routeها | Router قدیمی؛ Router داخلی |
lifespan | ادغام در lifespan برنامهٔ includeکننده | گرمکردن Cache، شروع مصرفکننده (Consumer) |
generate_unique_id_function | operationIdهای Routeهای Router | الگوی نامگذاری برای هر Router |
route_class | زیرکلاس APIRoute برای Routeهای آن | Route با زمانسنجی یا Log اختصاصی |
راهحل / روش استفاده: برای هر ماژول Feature یک Router داشته باشید؛ prefix، tags، پاسخ مشترک و Dependency را همانجا تنظیم کنید. ماژول را import کنید تا نام تنها و تکراری router وارد نشود.
افزودن Routerها با include_router و Router تودرتو (Including APIRouters) حیاتی
به زبان ساده: app.include_router(catalog.router) همهٔ Routeهای Router را به برنامه اضافه میکند و در این فرایند prefix، tags، dependencies و responses را ترکیب میکند. Router هم میتواند Router دیگری را include کند: v1.include_router(catalog.router). حاصل درختی مانند app → api → v1 → catalog است.
بدفهمی رایج: «اول Router را include میکنم و بعد Route اضافه میکنم.» پیش از FastAPI 0.137.0 این کار جواب نمیدهد. کد 0.128.8 روی router.routes حلقه میزند و در همان لحظه برای هر Route، self.add_api_route(prefix + route.path, …) را فراخوانی میکند. Route بعدی هرگز به برنامه نمیرسد. تست test_routes_added_after_include_are_missing_on_0_128 پاسخ ۴۰۴ میگیرد و بررسی آزمایشی فقط /openapi.json، /docs، /docs/oauth2-redirect و /redoc را در فهرست Routeها چاپ کرده است. در مورد Router تودرتو هم parent.include_router(child) پیش از ساختهشدن Routeهای child برای Pathهای فرزند ۴۰۴ میدهد. از 0.137.0: "Including subrouter in mainrouter can be done before adding routes (path operations) to subrouter, because now the entire object is stored instead of copying the routes". آموزش جاری هم میگوید: "You can do this before or after including router in the FastAPI app." برای سازگاری با هر دو، درخت را مانند build_api_router() از پایین به بالا بسازید.
تعریف: آموزش: "With app.include_router() we can add each APIRouter to the main FastAPI application. It will include all the routes from that router as part of it." دربارهٔ هزینه هم میگوید: "You don't have to worry about performance when including routers. This is designed to be lightweight and to avoid adding overhead to each request." مستندات جاری نکتهٔ 0.137.0+ را اضافه میکند: "Avoid directly mutating router.routes after including a router. FastAPI treats router inclusion as live … Treat router.routes as a lower-level route tree … and avoid relying on it as a flat list of final path operations."
build_api_router() then create_app(), FastAPI 0.128.8
1 v1 = APIRouter(prefix="/v1")
2 v1.include_router(catalog.router) -> v1 gets copies: /v1/products, /v1/products/featured, /v1/products/{product_id}, POST /v1/products
3 v1.include_router(orders.router) -> /v1/orders, /v1/orders/{order_id}
4 v1.include_router(admin.router, prefix="/admin", dependencies=[...], include_in_schema=False) -> /v1/admin/stats
5 api.include_router(v1); api.include_router(v2)
6 app.include_router(api, prefix="/api") -> /api/v1/products ... /api/v2/products/{product_id}
7 app.routes (real, registration order): docs routes, 8 v1 routes, 1 v2 route, /healthz, /version, Mount /static, Mount /legacyسناریوی واقعی: یک api_router تجمیعکنندهٔ Routerهای Feature؛ در قالب full-stack FastAPI، app/api/main.py دقیقاً api_router.include_router(login.router)، سپس users.router، utils.router و items.router را include میکند و بعد app.include_router(api_router, prefix=settings.API_V1_STR) اجرا میشود. مثالِ دیگر Router مخصوص توسعه است؛ همین قالب private.router را فقط با FASTAPI_ENV == "development" include میکند.
| فراخوانی | نتیجه | قاعده |
|---|---|---|
app.include_router(r) | افزودن Routeهای r به برنامه | کپی در لحظهٔ فراخوانی؛ ≤ 0.136 |
app.include_router(r, prefix="/api") | /api + r.prefix + path | قواعد prefix در ادامه |
parent.include_router(child) | کپی Routeهای فرزند در والد | ابتدا فرزندها را include کنید؛ ≤ 0.136 |
app.include_router(r, prefix="/v1") و دوباره با "/latest" | Route یکسان زیر دو Path | operationId پیشفرض متفاوت است چون Path جزئی از آن است |
r.include_router(r) | AssertionError: Cannot include the same APIRouter instance into itself. | پیام واقعی |
include کردن Router دارای Route با "" بدون prefix | FastAPIError: Prefix and path cannot be both empty (path operation: root) | پیام واقعی |
@router.get پس از include_router | در 0.128.8 غایب و 404؛ در 0.137.0+ قابل دسترس | وابسته به نسخه |
راهحل / روش استفاده: درخت Router را در تابع build_api_router() بسازید؛ برگها را پیش از شاخهها include کنید؛ آن را از Factory صدا بزنید و router.routes را دستی تغییر ندهید.
تنظیم APIRouter با prefix و tags (Prefix and tags) حیاتی
به زبان ساده: prefix="/products" یک بار نوشته میشود و به ابتدای Path همهٔ Routeهای Router میآید. tags=["catalog"] همه را در گروه catalog در /docs و در CatalogService یک Client تولیدشدهٔ TypeScript قرار میدهد. هر دو را میتوان روی خود Router یا هنگام include تنظیم کرد؛ مقدارها روی هم جمع میشوند.
بدفهمی رایج: «prefix میتواند با slash تمام شود.» نمیتواند: APIRouter(prefix="/items/") خطای AssertionError: A path prefix must not end with '/', as the routes will start with '/' میدهد و include_router(r, prefix="items") خطای AssertionError: A path prefix must start with '/'؛ هر دو واقعیاند. آموزش: "As the path of each path operation has to start with /, … the prefix must not include a final /." تصور دوم: «tags جای هم را میگیرند.» فهرستها به هم وصل میشوند: نخست tags در include، سپس tags خود Route؛ "This last path operation will have the combination of tags: ["items", "custom"]".
تعریف: در include_router نسخهٔ 0.128.8، Path تازه prefix + route.path است و tags با current_tags.extend(tags) و سپس current_tags.extend(route.tags) ساخته میشود. Route با Path برابر "" روی Router دارای prefix دقیقاً خود prefix را سرویس میدهد: @router.get("") + prefix="/products" → /products. به این ترتیب تغییرنشانی (Redirect) با کد ۳۰۷ میان /products و /products/ لازم نیست.
source of each piece value
1 app.include_router(api, prefix=settings.api_prefix) "/api"
2 api.include_router(v1) ; v1 = APIRouter(prefix="/v1") "/v1"
3 v1.include_router(catalog.router) catalog.router.prefix = "/products", tags = ["catalog"]
4 @router.get("/{product_id}") "/{product_id}"
5 final path /api/v1/products/{product_id}
6 final tags ["catalog"] (v1 and api add none)
7 final operationId (custom unique_id) "catalog-get_product"سناریوی واقعی: prefix کل API به شکل setting یعنی api_prefix: str = "/api"، تا استقرار داخلی زیر /internal/shop سرویس بدهد؛ افزودن tag با نام admin هنگام include به Router بدون tag؛ و یک tag برای هر Feature تا SDK تولیدشده برای هر Feature یک کلاس Service داشته باشد.
| محل | prefix | tags |
|---|---|---|
APIRouter(...) | متعلق به Feature؛ پیشنهاد یادداشت 0.62.0 | گروه مستندات Feature |
include_router(..., prefix=, tags=) | تصمیم includeکننده؛ نسخهها و Router شخص ثالث | گروه اضافه، مثلاً admin |
| Decorator | وجود ندارد؛ همان Path خود Route است | tag اضافه برای یک Route |
FastAPI(...) | prefix سراسری ندارد؛ Router بیرونی بگذارید: include_router(api, prefix="/api"). گزینهٔ --root-path سرور prefix مربوط به Routing نیست؛ به برنامه میگوید Proxy (پراکسی) بیرونی چه prefixی را حذف میکند و برنامه همچنان Pathهای خودش را سرویس میدهد | openapi_tags ترتیب و توضیح را تعیین میکند |
راهحل / روش استفاده: prefix و tag خود Feature روی Router خودش؛ prefix نسخه و API روی Routerهای includeکننده؛ و تستی برای اطمینانسنجی (Assert) Path نهایی و فهرست tag، مانند test_tags_metadata_and_operation_ids.
Dependencyها و پاسخهای Router (Router dependencies and responses) حیاتی
به زبان ساده: dependencies=[Depends(require_admin)] روی Router یا include_router، تابع require_admin را پیش از هر Route آن اجرا میکند؛ تابع Route مقداری از آن دریافت نمیکند. responses={404: {...}} هم آن پاسخ را به مستندات همهٔ Routeها میافزاید. هر دو تکرار را حذف میکنند: «کل این گروه به Token (توکن) نیاز دارد» یک خط میشود و روی Route تازه فراموش نمیشود.
بدفهمی رایج: «پنهانکردن Router با include_in_schema=False آن را محافظت میکند.» فقط از /openapi.json و /docs حذفش میکند. Router ادمین مثال هم پنهان است و هم محافظتشده؛ test_internal_routes_are_hidden_but_guarded Assert میکند که Route پنهان بدون Token پاسخ ۴۰۳ و با آن ۲۰۰ میدهد. اجرای واقعی curl هم 403 و سپس {"orders":0,"lifespan_events":["startup","catalog:startup"]} چاپ کرده است.
تعریف: آموزش: "we can add a list of dependencies that will be added to all the path operations in the router and will be executed/solved for each request made to them" و "The router dependencies are executed first, then the dependencies in the decorator, and then the normal parameter dependencies." مثال زنجیرهٔ کامل، شامل Dependency سطح app و include را اندازه گرفته: ["app", "include_router", "APIRouter", "decorator", "parameter"]، در test_dependency_order_router_then_decorator_then_parameters. برای پاسخ، include_router مقدار combined_responses = {**responses, **route.responses} را میسازد؛ برای کد وضعیت یکسان، ورودی خود Route برنده است.
GET /api/v1/admin/stats with x-admin-token: lab-token (real run)
1 app dependencies (FastAPI(dependencies=[...])) none in the shop app
2 include_router(admin.router, dependencies=[Depends(require_admin)])
3 require_admin(settings=get_settings(), x_admin_token="lab-token") -> compare_digest -> ok
4 admin.router dependencies none (the shared file stays generic)
5 decorator dependencies none
6 parameter dependencies request: Request (injected)
7 stats(request) -> {"orders": 0, "lifespan_events": [...]} 200
8 same request without the header: step 3 raises HTTPException(403, "Admin token required")سناریوی واقعی: Router داخلی مشترک میان چند پروژه که هر پروژه حفاظت خودش را دارد؛ مثال آموزش: "other projects could use the same APIRouter with a different authentication method". مثالهای دیگر: Dependency نیاز به کاربر احرازهویتشده روی همهٔ Routerها بهجز کاتالوگ عمومی؛ و مستندکردن یکبارهٔ responses={401: ..., 403: ...} برای Router محافظتشده.
| سطح | نحو | محل اجرا |
|---|---|---|
| App | FastAPI(dependencies=[Depends(f)]) | همهٔ Routeهای برنامه؛ Dependency سراسری |
| Include | app.include_router(r, dependencies=[...]) | همهٔ Routeهای r، فقط در این برنامه |
| Router | APIRouter(dependencies=[...]) | همهٔ Routeهای Router، هرجا include شود |
| Decorator | @router.get(..., dependencies=[...]) | یک Route؛ مقدار ارسال نمیشود |
| Parameter | x: Annotated[T, Depends(f)] | یک Route؛ مقدار به تابع میرسد |
راهحل / روش استفاده: مجوز (Authorization) گروه روی Router یا include_router باشد. Dependencyهای مقداردهنده، مثل کاربر جاری و Session پایگاه داده، پارامتر بمانند. تستی Route محافظتشده را بدون اطلاعات ورود صدا بزند. جزئیات سازوکار: تزریق وابستگی.
پیشفرضهای Router: default_response_class، deprecated، include_in_schema (Router defaults) تکمیلی
به زبان ساده: Router علاوه بر prefix و tags پیشفرضهای دیگری برای Routeها دارد: کلاس پاسخ، مثل HTMLResponse برای صفحههای رندرشده روی سرور؛ deprecated=True برای یک نسخهٔ قدیمی کامل؛ و include_in_schema=False برای نقطههای پایانی (Endpoints) داخلی.
بدفهمی رایج: «True روی Route، مقدار include_in_schema=False روی Router را خنثی میکند.» ترکیب AND است: در 0.128.8 مقدار نهایی route.include_in_schema and self.include_in_schema and include_in_schema است؛ هر False، Route را پنهان میکند. ترکیب deprecated، OR است: route.deprecated or deprecated or self.deprecated.
تعریف: برای کلاس پاسخ، include_router نخستین مقدار تنظیمشده را به ترتیب Route → Router → فراخوانی include → والد برمیدارد: get_value_or_default(route.response_class, router.default_response_class, default_response_class, self.default_response_class). یادداشت 0.62.0 میگوید: "default_response_class: updated to handle defaults in APIRouter and include_router."
pages = APIRouter(default_response_class=HTMLResponse); app.include_router(pages, include_in_schema=False)
1 @pages.get("/hello") returns "<h1>hello</h1>"
2 response_class: route (unset) -> router HTMLResponse -> chosen
3 GET /hello -> 200, content-type text/html; charset=utf-8, body <h1>hello</h1> (real test)
4 include_in_schema: True and True and False -> False -> "/hello" not in openapi()["paths"] (real test)سناریوی واقعی: Router صفحههای HTML در /admin/ui کنار API برای JSON؛ علامتزدن کل v1 با deprecated=True پس از انتشار v2؛ پنهانکردن /healthz و /metrics از SDK کاربران.
| تنظیم | قاعدهٔ ترکیب | کاربرد |
|---|---|---|
default_response_class | نخستین مقدار: Route، Router، include، والد | Router متن ساده یا HTML |
deprecated | هر True | نسخهٔ قدیمی و دورهٔ پایان پشتیبانی |
include_in_schema | همه باید True باشند | Route داخلی، سلامت و ادمین |
redirect_slashes | در 0.128.8 با include_router منتقل نمیشود؛ Routeها کپی میشوند و تنظیم Router برنامه یعنی FastAPI(redirect_slashes=...) تصمیم میگیرد. در test_included_router_redirect_slashes_is_not_transferred، حتی APIRouter(redirect_slashes=False) در برنامهٔ پیشفرض به /items پاسخ 307 میدهد | روی FastAPI(...) تنظیم کنید |
route_class | برای هر Router | زیرکلاس اختصاصی APIRoute |
راهحل / روش استفاده: رفتار کل گروه را یک بار روی Router تنظیم کنید؛ بازنویسی هر Route برای استثناها بماند؛ اثر در طرحواره (Schema) را در تست Assert کنید.
ترتیب Route میان Routerها و تداخل Path (Route order and path conflicts) حیاتی
به زبان ساده: پس از include یک فهرست تخت از Routeها به ترتیب افزودن داریم. درخواست از ابتدای این فهرست بررسی میشود و نخستین تطبیق برنده است. پس ترتیب include_router بخشی از Routing است: اگر Router دارای /users/{user_id} پیش از Router دارای /users/me include شود، /users/me دسترسناپذیر میشود.
بدفهمی رایج: «ابتدا prefix هر Router تطبیق داده میشود و بعد داخل آن جستوجو میشود.» در 0.128.8 چنین نیست؛ Routeها در والد کپی شدهاند، پس مرحلهٔ مستقلی برای Router نداریم و کل جدول بهترتیب پیمایش میشود. Path تکراری میان Routerها هم خطا نیست: test_path_conflict_first_router_wins_silently، GET /ping را در دو Router ثبت میکند و اولی پاسخ میدهد؛ هنگام include نه Exception داریم و نه Warning.
تعریف: مستندات Starlette: "Incoming paths are matched against each Route in order. In cases where more that one route could match an incoming path, you should take care to ensure that more specific routes are listed before general cases." شکست واقعی میان دو Router: GET /users/me → ۴۲۲ با {"type":"int_parsing","loc":["path","user_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"me"}.
wrong.include_router(by_id); wrong.include_router(me) right: me first
1 routes: GET /users/{user_id}, GET /users/me routes: GET /users/me, GET /users/{user_id}
2 GET /users/me -> /users/{user_id} matches (path only) GET /users/me -> /users/me matches
3 user_id = "me" -> int parsing fails get_me() -> {"id": "me"}
4 422 int_parsing (real) 200 (real)سناریوی واقعی: Router مربوط به Feature با نام users و Router جداگانهٔ me برای پروفایل و settings، هر دو زیر /users؛ Router نسخهٔ v2 که اشتباهاً بهدلیل prefix یکسان، Path نسخهٔ v1 را دوباره تعریف میکند؛ Router صفحه با /{slug} که همهچیز را میگیرد و باید آخر include شود.
| وضعیت | چه میشود؟ | راهحل |
|---|---|---|
| Path ثابت پس از Path پارامتری در یک Router | ثابت دسترسناپذیر است؛ 422 یا تابع اشتباه | ثابتها اول؛ /featured پیش از /{product_id} |
| همین وضعیت میان دو Router | همان نتیجه | Router ثابت را اول include کنید یا دو Router را یکی کنید |
| Method و Path یکسان در دو Router | اولی برنده، دومی بیصدا بیاستفاده | تست فهرست (method, path) و یکتایی آن |
| Path یکسان با Method متفاوت | هر دو کار میکنند؛ 405 نخستین تطبیق جزئی را فهرست میکند | مشکلی ندارد |
Route فراگیر (/{path:path}) | همهٔ موارد بعدی را میگیرد | آخر include کنید؛ یا app.frontend() در 0.138.0+ |
راهحل / روش استفاده: هر خانوادهٔ Path را در یک Router نگه دارید، Routerها را از خاص به عام include کنید و تست جدول Route داشته باشید؛ چاپ app.routes در بررسی آزمایشی الگوی خوبی است.
یکتایی operationId و generate_unique_id_function (operationId uniqueness) مهم
به زبان ساده: هر Path operation در OpenAPI یک operationId دارد و تولیدکنندهٔ Client آن را به نام متد تبدیل میکند. پیشفرض FastAPI بلند و وابسته به Path است: read_item_api_v1_items__item_id__get. تابع اختصاصی generate_unique_id_function نام کوتاه میدهد: catalog-get_product به getProduct در CatalogService تبدیل میشود. شناسهها باید در کل برنامه، میان Routerها و میان نسخهها یکتا باشند.
بدفهمی رایج: «FastAPI شناسهٔ تکراری را رد میکند.» فقط هشدار میدهد؛ آن هم هنگام تولید Schema، یعنی اولین درخواست /openapi.json یا app.openapi(). خروجی واقعی: UserWarning: Duplicate Operation ID read for function read_b at …/p1_routers.py. طرح نامگذاری فقط بر اساس نام تابع، با include دوبارهٔ Router در /api/v1 و /api/latest یا نام تابع یکسان در دو نسخه تداخل پیدا میکند؛ test_function_name_ids_collide_when_a_router_is_mounted_twice.
تعریف: تابع generate_unique_id در 0.128.8 با operation_id = f"{route.name}{route.path_format}" شروع میکند؛ نویسههای غیرکلمه را به _ تبدیل و سپس _{method} را اضافه میکند. مستندات "Generate Clients": "OpenAPI requires that each operation ID is unique across all the path operations, so FastAPI uses the function name, the path, and the HTTP method/operation to generate that operation ID". تابع اختصاصی "takes an APIRoute and outputs a string"؛ مثلاً "using the first tag … and the path operation name (the function name)". هشدار راهنمای پیشرفته دربارهٔ روش نام تابع: "you have to make sure each one of your path operation functions has a unique name. Even if they are in different modules (Python files)."
route default id shop unique_id
1 GET /api/v1/items/{item_id} read_item read_item_api_v1_items__item_id__get (not used in the shop)
2 GET /api/v1/products/{product_id} get_product_api_v1_products__product_id__get catalog-get_product
3 GET /api/v2/products/{product_id} get_product_api_v2_products__product_id__get catalog-v2-get_product (tag keeps it unique)
4 same router at /api/v1 and /api/latest status__api_v1_status_get / status__api_latest_status_get lambda r: r.name -> "status_" twice -> UserWarning
real: row 1 default (probe p1), row 2 default (Before app test), rows 2-3 shop ids (curl), row 4 (tests); row 3 default is the formulaسناریوی واقعی: Client TypeScript با فرمان مستندات FastAPI یعنی npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client که نام متدش نباید با تغییر Path عوض شود؛ تیم موبایلی که سند OpenAPI را ثابت و تغییر operationIdها را در CI مقایسه میکند.
| روش | مثال | شرط یکتایی | محل شکست |
|---|---|---|---|
| پیشفرض؛ نام + Path + Method | get_product_api_v1_products__product_id__get | معمولاً، نه همیشه: نویسهٔ غیرکلمه به _ تبدیل میشود؛ read روی /a-b و read روی /a_b هر دو read_a_b_get میدهند؛ هشدار واقعی Duplicate Operation ID در تست | تغییر Path همهٔ نامهای SDK را عوض میکند |
route.name | get_product | نام تابع در کل برنامه یکتا باشد | Router دوباره، نامهای یکسان v1/v2 |
f"{route.tags[0]}-{route.name}"؛ قالب full-stack و این مثال | catalog-get_product | نام در هر tag اول یکتا باشد | Route بدون tags؛ باید مدیریت شود |
operation_id="..." برای هر Route | getProduct | خودتان بررسی کنید | کپیکردن کد |
راهحل / روش استفاده: یکتایی پیشفرض را مفروض نگیرید؛ یکسانسازی - و _ تداخل میسازد، مطابق test_default_operation_ids_can_collide_after_sanitising. یک generate_unique_id_function با tag و نام و گزینهٔ جایگزین برای Route بدون tag، یا operation_id صریح تنظیم کنید. Router نسخهدار tag خودش را داشته باشد و تست یکتایی همهٔ شناسهها مثل test_tags_metadata_and_operation_ids باقی بماند.
ساماندهی OpenAPI: openapi_tags، tags_metadata و Route داخلی (OpenAPI organisation) مهم
به زبان ساده: FastAPI(openapi_tags=TAGS_METADATA) برای هر گروه مستندات توضیح میگذارد، با پشتیبانی Markdown، و ترتیب گروهها را تعیین میکند. include_in_schema=False روی Route، Router یا فراخوانی include آن Routeها را از سند حذف میکند. با این دو، /docs از فهرست Routeها به ترتیب ثبت، به مرجع مرتب API تبدیل میشود.
بدفهمی رایج: «همهٔ tagها باید توضیح داشته باشند.» مستندات میگوید: "You don't have to add metadata for all the tags that you use." tag بدون توضیح هم نمایش داده میشود؛ tag دارای توضیح به ترتیب openapi_tags ظاهر میشود. تصور دیگر: «Routeهای Sub-application در مستندات اصلی دیده میشوند.» چنین نیست؛ برنامهٔ Mountشده /legacy/docs و /legacy/openapi.json خودش را دارد؛ هر دو در اجرای واقعی ۲۰۰ دادهاند.
تعریف: مستندات فراداده (Metadata) میگوید openapi_tags، "takes a list containing one dictionary for each tag". هر دیکشنری name دارد: "the same tag name you use in the tags parameter in your path operations and APIRouters"؛ description دارد: "It can have Markdown and will be shown in the docs UI"؛ و externalDocs. ترتیب واقعی tagها در /openapi.json مثال: ['catalog', 'orders', 'catalog-v2', 'meta'].
what /openapi.json contains (real run, shop app)
1 info: title "Shop API", version "1.0.0"
2 tags: catalog, orders, catalog-v2, meta <- TAGS_METADATA order and descriptions
3 paths: /api/v1/products (get, post), /featured, /{product_id}, /api/v1/orders, /{order_id}, /api/v2/products/{product_id}, /version
4 absent: /api/v1/admin/stats (include_in_schema=False), /healthz (route flag), /static, /legacy (mounts)
5 operationIds: catalog-create_product, catalog-get_product, ..., orders-get_order (8, unique)سناریوی واقعی: API عمومی که مستنداتش Catalog را پیش از Orders با لینک راهنمای قیمتگذاری نشان میدهد؛ سرویس دارای /healthz، /metrics و Route ادمین که بخشی از قرارداد Client نیستند؛ محیط production با openapi_url=None و مستندات خاموش، در حالی که CI هنوز Schema را از create_app(test_settings) صادر میکند.
| هدف | ابزار | نکته |
|---|---|---|
| توضیح و ترتیب گروهها | FastAPI(openapi_tags=[...]) | Markdown در description |
| پنهانکردن یک Route | @router.get(..., include_in_schema=False) | همچنان سرویس میدهد |
| پنهانکردن کل Router | include_router(r, include_in_schema=False) | همچنان سرویس میدهد |
| خاموشکردن مستندات | openapi_url=None؛ /docs و /redoc هم حذف میشوند؛ 404 واقعی | از settings، متناسب با محیط |
| مستندات جدا برای برنامهٔ جدا | app.mount("/legacy", sub_app) | دارای /legacy/docs خودش |
| علامتزدن نسخهٔ قدیمی | include_router(v1, deprecated=True) | در مستندات خط میخورد |
راهحل / روش استفاده: همهٔ tagهای Feature را در یک فهرست TAGS_METADATA کنار Factory توضیح دهید. Routeها و Routerهای داخلی را هنگام include پنهان کنید، openapi_url را از settings بگیرید و Schema را در CI صادر کنید.
کارخانهٔ برنامه: create_app() (The app factory) حیاتی
به زبان ساده: بهجای app = FastAPI() در سطح ماژول که هنگام import ساخته میشود، تابع def create_app(settings=None) -> FastAPI بنویسید؛ برنامهٔ کامل شامل settings، lifespan، Middleware، Router و Mount را بسازد و برگرداند. سرور در هر Worker یک بار صدایش میزند؛ هر تست با settings خودش فراخوانی میکند و برنامهای مستقل میگیرد.
بدفهمی رایج: «Factory فقط برای Flask است.» FastAPI آن را اجباری نکرده، اما دلیلها یکساناند: انتخاب settings هنگام ساخت، نداشتن وضعیت مشترک سطح ماژول میان تستها؛ test_each_app_has_its_own_state دو برنامه و دو پایگاه داده دارد؛ و import بسته بدون اثر جانبی. Uvicorn مستقیم پشتیبانی میکند: uvicorn --factory shop.main:create_app؛ اجرای واقعی.
تعریف: در مثال، create_app() یک Settings اختیاری میگیرد؛ در نبود آن از get_settings() استفاده میکند، آن را روی app.state.settings میگذارد و app.dependency_overrides[get_settings] = lambda: settings ثبت میکند. در نتیجه همهٔ Depends(get_settings)های برنامه همان شیء مورد استفادهٔ Factory را میبینند. سپس Middleware را اضافه میکند، build_api_router() را زیر settings.api_prefix include میکند، meta router را اضافه و /static و /legacy را Mount میکند.
create_app(settings) why here
1 settings = settings or get_settings() one source of truth, passed in by tests
2 app = FastAPI(title=settings.app_name, lifespan=lifespan, openapi_tags=..., generate_unique_id_function=unique_id,
openapi_url=None if not settings.docs_enabled)
3 app.state.settings = settings; app.state.events = []
4 app.dependency_overrides[get_settings] = lambda: settings
5 @app.middleware("http") request_id; CORSMiddleware if settings.cors_origins (added last = outermost)
6 app.include_router(build_api_router(), prefix=settings.api_prefix)
7 app.include_router(meta_router); app.mount("/static", ...); app.mount("/legacy", create_legacy_app())
8 return app nothing has been opened yet: that is the lifespan's jobسناریوی واقعی: مجموعهتستی که یک برنامه با docs_enabled=False و دیگری با CORS origins میسازد؛ test_docs_can_be_switched_off و test_cors_is_outermost_when_enabled. فرمان خط فرمان (CLI) مثل python -m shop.cli export-openapi که برنامه را فقط برای خروجی Schema میسازد؛ یا Process مربوط به Worker که Package را بدون شروع HTTP import میکند.
app در سطح ماژول | create_app() |
|---|---|
| ساخت و خواندن settings هنگام import | ساخت هنگام فراخوانی با settings دادهشده |
| یک برنامه در هر Process، مشترک میان تستها | یک برنامه برای هر تست، بدون نشت وضعیت |
| Overrideها باید دستی برگردانده شوند | خود برنامه را دور بیندازید |
uvicorn shop.main:app | uvicorn --factory shop.main:create_app یا shop.asgi:app |
| برای تکفایل مناسب است | با اضافهشدن settings، Mount و تست لازم میشود |
راهحل / روش استفاده: یک Factory در main.py و یک asgi.py دوخطی با app = create_app() برای سرور و fastapi run؛ تستها هرگز shop.asgi را import نکنند.
نقطههای ورود: main.py، asgi.py، --factory و [tool.fastapi] (Entry points) مهم
به زبان ساده: باید چیزی محل شیء برنامه را به سرور بگوید. شکلهای معمول، Import string مثل uvicorn shop.asgi:app، رشتهٔ Factory مثل uvicorn --factory shop.main:create_app و برای CLI با نام fastapi، گزینهٔ entrypoint در pyproject.toml است. فایل importشده توسط سرور را کوچک نگه دارید؛ همهٔ منطق در Factory باشد.
بدفهمی رایج: «Routeها باید در main.py باشند.» در برنامهٔ ساختاریافته، main.py اجزا را وصل میکند؛ عبارت آموزش "ties everything together" است: "This will be the main file in your application that ties everything together. And as most of your logic will now live in its own specific module, the main file will be quite simple". Routeها در Routerهای Feature زندگی میکنند.
تعریف: آموزش: "As your FastAPI app object lives in app/main.py, you can configure the entrypoint in your pyproject.toml file like this: [tool.fastapi] entrypoint = "app.main:app"". در غیر این صورت "other tools might not be able to find it, for example the VS Code Extension or FastAPI Cloud". مثال مقدار entrypoint = "shop.asgi:app" را تنظیم میکند.
command (from the project root) what is imported real?
1 uvicorn --factory shop.main:create_app --port 18931 shop.main, then create_app() real: "Application startup complete."
2 uvicorn shop.asgi:app --workers 2 shop.asgi in each worker real: two "Application startup complete." lines
3 fastapi run ([tool.fastapi] entrypoint) shop.asgi:app expected, not run (fastapi-cli not installed here)
4 pytest shop.main.create_app in fixtures real: 45 passedسناریوی واقعی: یک Image که بهصورت API با uvicorn shop.asgi:app و بهصورت Worker با python -m shop.worker شروع میشود؛ Worker، shop.core را import میکند اما Routerها را نه. یا Procfile و command در Kubernetes که به Factory اشاره میکنند.
| فایل | محتوا | چه چیزی آن را import میکند؟ |
|---|---|---|
shop/main.py | create_app()، Metadata مربوط به tags و تابع شناسهٔ یکتا | تست، asgi.py و ابزار |
shop/asgi.py | app = create_app() | Uvicorn، Gunicorn، fastapi run |
pyproject.toml | [tool.fastapi] entrypoint، dependencies و تنظیم pytest | ابزارها |
shop/api.py | build_api_router() | main.py |
router.py در Feature | Path operationها | api.py |
راهحل / روش استفاده: اثر جانبی import را فقط در asgi.py نگه دارید؛ همهٔ اجراکنندهها به آن یا به Factory اشاره کنند؛ Entry point را در pyproject.toml ثبت کنید.
کنترل lifespan: asynccontextmanager، Startup، Shutdown و app.state (Lifespan control) حیاتی
به زبان ساده: چرخهٔ عمر (Lifespan) یک تابع async با یک yield است. کد پیش از yield هنگام شروع برنامه توسط سرور یک بار اجرا میشود: بازکردن Engine پایگاه داده، ساخت HTTP client یا بارگذاری Model. کد پس از yield هنگام توقف برنامه یک بار آنها را میبندد. منابع بازشده را روی app.state ذخیره کنید و در درخواست از طریق request.app.state به آنها برسید.
بدفهمی رایج: «کنار lifespan میتوانم @app.on_event("startup") را هم نگه دارم.» مستندات میگوید: "If you provide a lifespan parameter, startup and shutdown event handlers will no longer be called. It's all lifespan or all events, not both." بررسی آزمایشی، on_event("startup") را روی برنامهٔ دارای lifespan= ثبت کرد و handler اجرا نشد. استفادهٔ تنها از on_event هشدار واقعی DeprecationWarning: on_event is deprecated, use lifespan event handlers instead. میدهد. تصور دوم: «lifespan در هر تست اجرا میشود.» TestClient(app) بدون with آن را اجرا نمیکند؛ مقدار واقعی app.state.events == [] است. فقط with TestClient(app) as client: آن را اجرا میکند.
تعریف: مستندات FastAPI: "You can define this startup and shutdown logic using the lifespan parameter of the FastAPI app, and a 'context manager'" و "The first part of the function, before the yield, will be executed before the application starts. And the part after the yield will be executed after the application has finished." دلیل بارگذارینکردن هنگام import: "You could load it at the top level of the module/file, but that would also mean that it would load the model even if you are just running a simple automated test". Starlette میگوید: "You can store arbitrary extra state on the application instance, using the generic app.state attribute." سازوکار زیربنایی ASGI Lifespan Protocol با رویدادهای startup و shutdown است.
uvicorn --factory shop.main:create_app (real log lines in the right column)
1 create_app(): settings read, routes registered INFO: Started server process [5678]
2 lifespan startup sent by Uvicorn INFO: Waiting for application startup.
3 app lifespan: Database.connect(seed=True), httpx.AsyncClient(base_url=..., timeout=2.0)
4 nested catalog lifespan: app.state.featured_ids = [2, 3]
5 yield (both) INFO: Application startup complete.
6 requests: handlers read request.app.state.db INFO: 127.0.0.1:56644 - "GET /api/v1/products/featured HTTP/1.1" 200 OK
7 SIGTERM INFO: Shutting down / Waiting for application shutdown.
8 catalog lifespan exits, then app lifespan: await http.aclose(); db.close()
9 INFO: Application shutdown complete.سناریوی واقعی: AsyncEngine در SQLAlchemy که هنگام Startup ساخته و هنگام Shutdown آزاد میشود؛ SQLAlchemy 2 و SQLModel. یک httpx.AsyncClient در هر Process برای پرداخت با استفادهٔ مجدد از Connectionها؛ Model یادگیری ماشین که یک بار در حافظه بارگذاری میشود؛ Client مربوط به Redis؛ یا Task مصرفکنندهٔ پسزمینه که شروع و لغو میشود.
| منبع | بازکردن؛ پیش از yield | بستن؛ پس از yield | دسترسی |
|---|---|---|---|
| Engine یا مجموعهٔ اتصال (Connection pool) پایگاه داده | create_async_engine(url) در راهنمای asyncio SQLAlchemy 2.0 / Database.connect() | await engine.dispose() / close() | request.app.state.db یا Dependency |
| HTTP client | httpx.AsyncClient(timeout=...) | await client.aclose() | request.app.state.http |
| Cache client | redis.asyncio.Redis(...) در راهنمای asyncio redis-py | await client.aclose()؛ "requires an explicit disconnect" | Dependency |
| Model یادگیری ماشین | load_model(path) | آزادکردن حافظه/GPU | app.state.model |
| Settings | اینجا نه؛ خواندن در Factory | — | Depends(get_settings) |
| شیء مخصوص هر درخواست | هرگز اینجا؛ Session و تراکنش (Transaction) | — | Dependency دارای yield |
راهحل / روش استفاده: یک lifespan در core/lifespan.py، try/finally دور yield، منابع روی app.state و تحویلشان به Route از Dependency کوچک مثل get_db. شیء مخصوص هر درخواست در Dependency دارای yield باشد؛ تزریق وابستگی.
lifespan در Router و وضعیت lifespan (Router lifespans and lifespan state) تکمیلی
به زبان ساده: Router میتواند lifespan خودش را همراه بیاورد: APIRouter(lifespan=...). هنگام include، FastAPI آن را داخل lifespan والد قرار میدهد؛ پس Feature میتواند مالک کار Startup خودش، مثل گرمکردن Cache یا شروع Consumer، باشد، بدون اینکه lifespan برنامه جزئیاتش را بداند. Lifespan میتواند بهجای تنظیم app.state یک دیکشنری yield کند؛ این دیکشنری در هر درخواست به request.state تبدیل میشود.
بدفهمی رایج: «lifespan برنامهٔ Mountشده هم اجرا میشود.» نمیشود؛ هشدار مستندات FastAPI: "these lifespan events (startup and shutdown) will only be executed for the main application, not for Sub Applications - Mounts". برنامهٔ /legacy مثال، هم در تست و هم curl، مقدار واقعی {"lifespan_ran": false} میدهد. Routerهای includeشده اجرا میشوند؛ برنامههای Mountشده نه.
تعریف: در 0.128.8 ادغام با _merge_lifespan_context(self.lifespan_context, router.lifespan_context) انجام میشود: ابتدا Context اصلی یا والد وارد میشود و Context تودرتو داخل آن. Stateهای yieldشده با {**nested_state, **original_state} ترکیب میشوند، پس برای کلید یکسان مقدار والد برنده است. بررسی واقعی: برنامه {"source": "app", "app_only": 1} و Router، {"source": "router", "router_only": 2} را yield میکند؛ درخواست {'source': 'app', 'app_only': 1, 'router_only': 2} میبیند و ترتیب اجرا ['app:start', 'router:start', 'router:stop', 'app:stop'] است. Starlette: "The state received on the requests is a shallow copy of the state received on the lifespan handler." دسترسی دیکشنریمانند، request.state["http_client"]، "was introduced in Starlette 0.52.0 (January 2026)"؛ جدیدتر از نسخهٔ ثابتشدهٔ 0.49.3.
app = FastAPI(lifespan=app_ls); app.include_router(APIRouter(lifespan=router_ls)) (real probe)
1 enter app_ls -> state {"source": "app", "app_only": 1}
2 enter router_ls -> state {"source": "router", "router_only": 2}
3 merged state = {**router_state, **app_state} = {"source": "app", "app_only": 1, "router_only": 2}
4 request.state.source == "app"; request.state.router_only == 2
5 shutdown: router_ls exits first, app_ls lastسناریوی واقعی: گرمکردن featured_ids توسط Feature کاتالوگ هنگام Startup در مثال؛ Feature رویدادها که Kafka consumer را در lifespan Router شروع و هنگام Shutdown متوقف میکند؛ یا State نوعدار با TypedDict که از lifespan yield میشود و جای app.state بدون نوع را میگیرد.
| سازوکار | حوزه (Scope) | برای Mount اجرا میشود؟ | دسترسی |
|---|---|---|---|
FastAPI(lifespan=...) | برنامه | خیر؛ فقط سطح بالا | app.state / دیکشنری yieldشده |
APIRouter(lifespan=...) | ادغام در includeکننده؛ 0.112.2+ | خیر | همان |
on_event("startup") | منسوخ؛ با lifespan= نادیده گرفته میشود | خیر | متغیر سراسری |
| دیکشنری State حاصل از yield | هر درخواست؛ کپی سطحی (Shallow copy) | — | request.state.x |
app.state.x = ... | Process | — | request.app.state.x |
راهحل / روش استفاده: برای Startup متعلق به Feature که به منابع core نیاز دارد، lifespan مربوط به Router مناسب است، چون داخل lifespan برنامه اجرا میشود. نام کلیدها را متمایز بگذارید و هرگز به lifespan برنامهٔ Mountشده تکیه نکنید.
settings با pydantic-settings: BaseSettings، SettingsConfigDict و env_file (Settings) حیاتی
به زبان ساده: class Settings(BaseSettings) مدل Pydantic است که فیلدهایش بهجای dict از متغیر محیطی، و در صورت انتخاب از .env و فایل اسرار، پر میشوند. شما نوع و پیشفرض مینویسید؛ Pydantic رشتهها را تبدیل میکند و اگر مقداری نادرست باشد، اجازهٔ شروع برنامه نمیدهد.
بدفهمی رایج: «متغیر محیطی میتواند bool یا عدد باشد.» نمیتواند؛ مستندات FastAPI: "any value read in Python from an environment variable will be a str, and any conversion to a different type or any validation has to be done in code." برای همین os.environ.get("SHOP_DEBUG", "false") در مثالِ قبل در شرط درست است، اما docs_enabled: bool در Settings چنین نیست؛ در تست واقعی "false" به False تبدیل میشود. تصور دیگر: «BaseSettings در pydantic است.» از Pydantic v2 بستهای جداست: from pydantic_settings import BaseSettings، مطابق یادداشت FastAPI 0.100.0.
تعریف: مستندات FastAPI: "Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable APP_NAME will still be read for the attribute app_name. Next it will convert and validate the data." پیکربندی در model_config = SettingsConfigDict(...) قرار میگیرد: env_prefix که "allows you to set a prefix for all environment variables" و پیشفرضش '' است؛ env_file، env_file_encoding، secrets_dir، case_sensitive، env_nested_delimiter و extra. شکستهای واقعی Validation مثال: مقدار "production" برای environment → Input should be 'dev', 'test', 'staging' or 'prod' [type=literal_error ...]؛ مقدار SHOP_HTTP_TIMEOUT_S=60 با le=30 → Input should be less than or equal to 30 [type=less_than_equal ...]؛ مقدار SHOP_CORS_ORIGINS=https://shop.example برای list[str] → SettingsError: error parsing value for field "cors_origins" from source "EnvSettingsSource". نوع مرکب از JSON خوانده میشود.
process environment Settings field value after validation (real)
1 SHOP_HTTP_TIMEOUT_S=5 http_timeout_s: float (gt=0, le=30) 5.0
2 SHOP_DOCS_ENABLED=false docs_enabled: bool False
3 SHOP_CORS_ORIGINS='["https://shop.example"]' cors_origins: list[str] ["https://shop.example"]
4 shop_app_name=lower-case-name app_name: str "lower-case-name" (case-insensitive)
5 APP_NAME=no-prefix app_name: str "Shop API" (prefix required)
6 SHOP_ADMIN_TOKEN=s3cret admin_token: SecretStr repr: SecretStr('**********')سناریوی واقعی: DATABASE_URL که بهصورت PostgresDsn اعتبارسنجی و در field_validator برای Driver با postgresql+psycopg:// بازنویسی میشود؛ همان کاری که قالب full-stack انجام میدهد. Feature flag با فیلد bool؛ یا Environment = Literal["dev", "test", "staging", "prod"] که اشتباه تایپی را هنگام Startup رد میکند.
کلید SettingsConfigDict | مقدار مثال | اثر |
|---|---|---|
env_prefix | "SHOP_" | SHOP_DATABASE_URL → database_url؛ DATABASE_URL تنها نادیده گرفته میشود |
env_file | ".env" و .env.<env> از load_settings | خواندن نسبت به CWD |
env_file_encoding | "utf-8" | مستقل از پیشفرض سیستمعامل |
extra | "forbid"؛ پیشفرض | کلید ناشناخته در dotenv → extra_forbidden |
secrets_dir | با _secrets_dir هنگام ساخت نمونه | هر مقدار در یک فایل |
case_sensitive | پیشفرض False | shop_app_name هم کار میکند |
env_nested_delimiter | استفاده نشده | SHOP_DB__POOL_SIZE → فیلد مدل تودرتو |
راهحل / روش استفاده: برای هر سرویس یک کلاس Settings در core/config.py و یک prefix داشته باشید؛ Literal برای مجموعهٔ بستهٔ مقدارها، SecretStr برای اسرار و Field برای قیدها. هیچ جای دیگر کد از os.environ نخواند.
منابع settings و اولویت: .env، محیط واقعی و secrets_dir (Settings sources and priority) مهم
به زبان ساده: یک مقدار از پنج جا میآید و منبع بالاتر برنده است: آرگومانهای Settings(...)، متغیر محیطی واقعی، فایل .env، فایل Secrets directory، و پیشفرض کلاس. .env وسیلهٔ راحتی توسعهدهنده است؛ در staging و production، محیط واقعی و فایل اسرار Mountشده مرجعاند.
بدفهمی رایج: «.env مثل فایل Config روی محیط غلبه میکند.» برعکس است: "environment variables will always take priority over values loaded from a dotenv file" و "a dotenv file and environment variables will always take priority over values loaded from the secrets directory"؛ مستندات Pydantic Settings. تست test_priority_env_over_dotenv_over_secrets همهٔ این ترتیب را میسنجد. تصور دیگر: «اشتباه تایپی در .env نادیده گرفته میشود.» با پیشفرض extra="forbid"، نوشتن SHOP_DATABSE_URL=... در .env شکست میخورد؛ خروجی واقعی 1 validation error for Settings | shop_databse_url | Extra inputs are not permitted [type=extra_forbidden, input_value='sqlite:///typo.db', input_type=str] است.
تعریف: مستندات ترتیب را "in descending order of priority" میآورد: آرگومان CLI اگر cli_parse_args فعال باشد؛ "Arguments passed to the Settings class initialiser"؛ "Environment variables"؛ "Variables loaded from a dotenv (.env) file"؛ "Variables loaded from the secrets directory"؛ و "The default field values for the Settings model." برای چند فایل dotenv: "The files will be loaded in order, with each file overriding the previous one." فایل Secret، "follows the same principal as a dotenv file except it only contains a single value and the file name is used as the key". با prefix، نام فایل هم آن را دارد؛ shop_admin_token در تست واقعی. مستندات: "By default Docker uses /run/secrets as the target mount point." غیبت Secrets directory فقط هشدار است: UserWarning: directory "/run/secrets-missing" does not exist؛ خروجی واقعی.
the same field from four places (tests/shop/core/test_settings.py, real)
1 secrets/shop_app_name = "from-secret-file"; .env SHOP_APP_NAME=from-dotenv; env SHOP_APP_NAME=from-env
2 Settings(_secrets_dir=...).app_name -> "from-env" (environment beats .env)
3 admin_token: .env "from-dotenv" vs secret file -> "from-dotenv" (.env beats secrets dir)
4 payments_base_url only in the secrets dir -> "https://payments.example" (beats the default)
5 Settings(..., app_name="from-init") -> "from-init" (init beats everything)سناریوی واقعی: لپتاپ با .env کپیشده از .env.example و نادیدهگرفتهشده در git، در کنار CI که فقط متغیر واقعی دارد؛ Pod در Kubernetes با ConfigMap بهشکل متغیر محیطی و Secret بهشکل فایل زیر /run/secrets؛ یا secrets: در Docker Swarm یا Compose که در /run/secrets Mount میشود.
| منبع | مناسب برای | نامناسب برای |
|---|---|---|
| Init kwargs | تست، Factory و CLI | مقدار production |
| محیط واقعی | همهٔ محیطهای استقرار؛ Config دوازدهعاملی | Secret بزرگ و کلید چندخطی |
.env؛ نادیده در git | پیشفرض توسعهٔ محلی | production؛ کسی نباید روی سرور فایل را ویرایش کند |
.env.example؛ ثبتشده | مستندکردن متغیرها | Secret واقعی |
| Secrets directory | گذرواژه، API key و گواهی به شکل فایل | Config غیرمحرمانه |
| پیشفرض کلاس | مقدار امن که محلی کار میکند | Secret؛ change-me نباید به production برسد |
راهحل / روش استفاده: .env.example را ثبت و .env را نادیده بگیرید؛ .gitignore این repo از قبل .env دارد. مقدار production را از محیط واقعی و فایل Secret بدهید، extra="forbid" را نگه دارید و هنگام Startup بیرون dev/test اسرار پیشفرض را رد کنید. در Settings مثال یک model_validator(mode="after") وجود دارد که اگر environment برابر staging یا prod باشد و admin_token هنوز change-me باشد خطا میدهد. تست test_default_admin_token_is_refused_outside_dev آن را میسنجد؛ شروع واقعی prod بدون Token با Value error, SHOP_ADMIN_TOKEN must be set in prod خارج میشود. امکانات مستندات جاری که در 2.11.0 نیستند، یعنی env_file_depth، dotenv_filtering، env_prefix_target و ثبت همهٔ منابع با PYDANTIC_SETTINGS_DEBUG، به pydantic-settings جدیدتر روی Python 3.10+/3.11+ نیاز دارند.
Dependency تنظیمات: lru_cache، Config هر محیط و تست (The Settings dependency) حیاتی
به زبان ساده: ساخت Settings را در تابع دارای @lru_cache قرار دهید و با Depends(get_settings) Dependency کنید. اولین فراخوانی محیط و فایل را میخواند؛ همهٔ فراخوانیهای بعد همان شیء را میگیرند. تست با app.dependency_overrides[get_settings] جایگزینش میکند؛ یا Factory شیء settings میگیرد و خودش Override نصب میکند.
بدفهمی رایج: «نوشتن Settings() در Dependency کافی است.» بدون Cache، به گفتهٔ مستندات FastAPI، "we would create that object for each request, and we would be reading the .env file for each request". با Cache، تغییر متغیر تا get_settings.cache_clear() دیده نمیشود؛ تست واقعی دارد. از طرف دیگر settings = Settings() در سطح ماژول هنگام import خوانده میشود؛ همان چیزی که Factory از آن دوری میکند.
تعریف: مستندات FastAPI: "as we are using the @lru_cache decorator on top, the Settings object will be created only once, the first time it's called" و "That way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing." تابع functools.lru_cache، "up to the maxsize most recent calls" را Cache میکند؛ تابع بدون آرگومان یک ورودی دارد. برای فایل هر محیط، load_settings(env) در مثال _env_file=(".env", f".env.{env}") میدهد؛ .env.prod روی .env غالب میشود و فایل غایب .env.dev فقط رد میشود؛ تست واقعی test_per_environment_file_overrides_base.
process lifetime get_settings() cache
1 first Depends(get_settings) or create_app() miss -> load_settings() -> Settings(...) read env, .env, .env.<env>, secrets
2 every later request hit -> the same object (no file I/O)
3 test: get_settings.cache_clear(); monkeypatch.setenv(...) next call re-reads
4 test: create_app(Settings(_env_file=None, environment="test")) factory installs dependency_overrides[get_settings]
5 worker 2 of --workers 2 its own cache: settings read once per processسناریوی واقعی: GET /version با SHOP_ENVIRONMENT=staging پاسخ {"app":"Shop API","environment":"staging"} میدهد؛ curl واقعی. با SHOP_ENVIRONMENT=prod مقدار "prod" میدهد؛ اجرای واقعی با دو Worker. مثال دیگر تستی است که بدون دستزدن به محیط، مستندات را خاموش میکند.
| الگو | زمان خواندن Config | تستپذیری | نتیجه |
|---|---|---|---|
os.environ.get در محل مصرف | هر بار، به شکل رشته | Monkeypatch همهچیز | پرهیز کنید |
settings = Settings() در سطح ماژول | هنگام import | نیاز به بارگذاری دوبارهٔ ماژول | فقط اسکریپت کوچک |
@lru_cache get_settings() + Depends | یک بار در هر Process | dependency_overrides، cache_clear() | پیشنهاد مستندات FastAPI |
create_app(settings) + Override | تصمیم فراخواننده | دادن شیء Settings | Factory این فصل |
کلاس Python برای هر محیط؛ ProdSettings(Settings) | یک بار | بله | کار میکند؛ فایل یا متغیر محیطی سادهتر است |
راهحل / روش استفاده: get_settings با @lru_cache در core/config.py، تعریف SettingsDep = Annotated[Settings, Depends(get_settings)]، و cache_clear() در Fixture خودکار (Autouse fixture). مقدار مخصوص محیط در کار محلی از .env.<env> و در استقرار از متغیر واقعی بیاید. همین Settings dependency نقطهای است که تست FastAPI برای پایگاه دادهٔ تست عوض میکند.
سازماندهی بر اساس Layer فنی (Organizing code by technical layer) حیاتی
به زبان ساده: برای هر نوع کد یک پوشه داریم: routers/ برای HTTP، schemas/ برای مدل درخواست و پاسخ Pydantic، models/ برای مدل پایگاه داده، services/ برای قواعد کسبوکار، و repositories/ برای Query. داخل هر کدام یک ماژول برای هر منبع. آموزش FastAPI با همین Layout شروع میکند: app/routers/items.py و app/routers/users.py. قالب full-stack هم app/api/routes/، app/models.py و app/crud.py دارد.
بدفهمی رایج: «Layer یعنی کد مستقل از هم است.» پوشه جلوی import را نمیگیرد: در layered/، فایل routers/orders.py مستقیم از repositories/products.py import میکند و هیچچیز مانع import کردن routers/ از repositories/ نیست. تقسیم به Layer تا وقتی ابزار اعمالش نکند قرارداد است. import-linter قراردادهای اعلامشده را بررسی میکند؛ انواع آن "Forbidden"، "Layers" و "Independence" هستند. قاعدهٔ banned-api در Ruff، یعنی TID251، "Derived from the flake8-tidy-imports linter" است؛ زیر lint.flake8-tidy-imports.banned-api تنظیم میشود و "Checks for banned imports".
تعریف: Layout بستهٔ layered/ و جهت وابستگی مورد انتظار آن:
1 layered/
2 ├── main.py create_app(): lifespan, include_router(v1)
3 ├── db.py Database (SQLite stand-in for an engine)
4 ├── routers/ HTTP: paths, status codes, Depends -> may import schemas, services, repositories
5 │ ├── deps.py, products.py, orders.py
6 ├── schemas/ Pydantic API models (OrderIn, OrderOut) -> imports nothing of ours
7 ├── services/orders.py business rules (price from catalog) -> imports repositories, models
8 ├── repositories/ SQL -> imports db, models
9 └── models/ persistence models (rows / ORM classes) -> imports nothing of ours
10 direction: routers -> services -> repositories -> models (schemas only at the HTTP edge)سناریوی واقعی: سرویس داخلی با شش Endpoint و یک توسعهدهنده؛ APIِ CRUD که همهٔ منابعش شکل مشابه دارند و Layer محور مفیدی است؛ یا کدی که مدلهای ORM میان چند منبع مشترکاند و نگهداری در یک Package به نام models/ سادهتر است.
| قوت | ضعف |
|---|---|
| برای آشنا به MVC روشن است | تغییر یک Feature همهٔ پوشههای Layer را درگیر میکند |
| یافتن «همهٔ SQLها» یا «همهٔ Schemaها» آسان است | پوشه پر از دهها فایل نامرتبط میشود |
| مطابق آموزش و قالبها | Import میان Featureها نامشهود است |
| تصمیمهای کم در سطح بالا | استخراج یک Feature به سرویس نیازمند بریدن بخشی از هر Layer است |
| مناسب سرویس کوچک و Microservice | مالکیت تیمی روشن نیست |
راهحل / روش استفاده: تا وقتی سرویس چند منبع و یک تیم دارد، از آن استفاده کنید. جهت وابستگی را نگه دارید: routers → services → repositories → models. وقتی پوشهٔ Layer دیگر در یک صفحه جا نمیشود، به Feature بروید.
سازماندهی بر اساس Feature: برش عمودی و مرز ماژول (Organizing code by feature) حیاتی
به زبان ساده: برای هر قابلیت کسبوکار یک پوشه مثل catalog/، orders/ و payments/ داریم؛ هر کدام router.py، schemas.py، models.py، repository.py و service.py خودش را دارد. این برش عمودی (Vertical slice) از همهٔ Layerها میگذرد. زیرساخت مشترک در core/ است: Config، پایگاه داده، lifespan و Dependency مشترک. Featureها فقط از یک ماژول عمومی کوچک با هم حرف میزنند.
بدفهمی رایج: «Feature یعنی Layer نداریم.» Layerها همچنان داخل Feature، هر کدام یک فایلاند. محور سطح بالا عوض شده؛ پوشهای که باز میکنید مفهوم کسبوکار است. راهنمای fastapi-best-practices دلیل تغییر نویسندگانش را چنین توضیح میدهد: سازماندهی "by file type (e.g., crud, routers, models) … works well for microservices or smaller projects. However, this approach didn't scale well for our monolith with many domains and modules". ساختاری که "more scalable and evolvable is inspired by Netflix's Dispatch" میدانند از همان تجربه آمده است.
تعریف: Package با نام shop/ و قواعد مرزی که مثال رعایت میکند:
1 shop/
2 ├── main.py, asgi.py, api.py, legacy.py factory, entry point, router tree, mounted app
3 ├── core/ config.py, db.py, lifespan.py, deps.py, router.py <- imported by features, imports no feature
4 ├── catalog/ router.py, router_v2.py, schemas.py, models.py, repository.py, service.py (public)
5 ├── orders/ router.py, schemas.py, models.py, repository.py, service.py
6 ├── internal/admin.py shared router, configured at include time
7 └── static/robots.txt
8 rule 1: inside a feature, relative imports (from .repository import OrderRepository)
9 rule 2: across features, absolute imports of the public module only (from shop.catalog.service import find_product)
10 rule 3: core never imports a feature; features never import each other's router or repositoryسناریوی واقعی: Monolith فروشگاه با catalog، cart، orders، payments و shipping، هر کدام متعلق به یک تیم؛ زمانی که payments به آهنگ استقرار مستقل نیاز پیدا میکند، پوشهاش همراه تستها به سرویس تبدیل میشود. این همان انتخاب معماری یکپارچهٔ ماژولار است.
| دغدغه | پاسخ Layout مبتنی بر Feature |
|---|---|
| قواعد سفارش کجاست؟ | orders/service.py |
| چه کسی میتواند صدایش بزند؟ | Feature دیگر فقط از طریق orders/service.py |
| تست سفارش کجاست؟ | tests/shop/orders/ |
| Feature تازه چه میخواهد؟ | پوشه با پنج فایل، یک خط include_router، یک tag |
| کد مشترک کجاست؟ | core/ برای زیرساخت، یا ماژول عمداً عمومی برای Domain |
| مرزها چگونه اعمال شوند؟ | بازبینی و قرارداد "Forbidden" یا "Independence" در import-linter؛ shop.orders حق import از shop.catalog.repository ندارد؛ یا Ruff با banned-api و TID251 |
راهحل / روش استفاده: یک پوشه برای هر قابلیت، core/ برای زیرساخت، service.py عمومی برای فراخوانی میان Featureها و تست متناظر با پوشهها. با رشد تیم، قاعدهٔ import در CI بررسی شود. مرز ماژول بهعنوان دغدغهٔ معماری: معماری پاک و ششضلعی.
تفکیک مسئولیت data.py: Router، Service و Repository (Separation of concerns) مهم
به زبان ساده: سه کار را جدا نگه دارید. Router با HTTP حرف میزند: درخواست را میخواند، یک تابع Service را صدا میزند و نتیجه یا خطای دامنه (Domain error) را به کد وضعیت تبدیل میکند. Service قاعدهٔ کسبوکار را نگه میدارد؛ «قیمت از کاتالوگ میآید، نه از Client». Repository، همان data.py دوره، SQL را نگه میدارد. هر جزء در سطح خودش تست میشود و فایل Router آنقدر کوتاه میماند که فهرست مطالب API باشد.
بدفهمی رایج: «SQL داخل تابع Route سادهتر است.» برای یک Route بله؛ برای بیست Route، یک Query سه بار تکرار میشود، تغییر Schema نیازمند جستوجوی همهٔ Routerهاست و قاعدهٔ کسبوکار فقط از HTTP تست میشود. تست Service مثال بدون برنامه یا Client اجرا میشود: در test_orders_service.py داریم place_order(db, product_id=1, quantity=3).total_cents == 12600.
تعریف: در مثال، orders/router.py خطای UnknownProduct را به ۴۲۲ و سفارش غایب را به ۴۰۴ نگاشت میکند؛ orders/service.py خطای UnknownProduct را ایجاد و price_cents * quantity را حساب میکند؛ و orders/repository.py فرمان INSERT را اجرا میکند. Service کد وضعیت HTTP نمیشناسد و Repository از قواعد کسبوکار خبر ندارد. SQL متعلق به Repositoryها:
-- shop/core/db.py: the schema both features use (SQLite here; PostgreSQL in production)
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
featured INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products (id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
total_cents INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS orders_product_id_idx ON orders (product_id);
-- catalog/repository.py, ProductRepository.list(featured_only=True)
SELECT id, sku, name, price_cents, featured FROM products WHERE featured = 1 ORDER BY id;
-- orders/repository.py, OrderRepository.add() (values bound, never formatted into the string)
INSERT INTO orders (product_id, quantity, total_cents) VALUES (?, ?, ?); POST /api/v1/orders {"product_id": 2, "quantity": 2} (real curl: 201 {"id":1,"product_id":2,"quantity":2,"total_cents":9000})
1 router create_order(body: OrderIn, db: DbDep) validation by Pydantic (quantity 1..100)
2 service place_order(db, 2, 2)
3 service -> catalog.service.find_product(db, 2) public surface of another feature
4 repo SELECT ... FROM products WHERE id = ? price_cents = 4500
5 service total = 4500 * 2 = 9000
6 repo INSERT INTO orders (...) VALUES (?, ?, ?)
7 router 201 + OrderOut (response_model filters the fields)
8 unknown product: service raises UnknownProduct -> router -> 422 {"detail": "Unknown product"}سناریوی واقعی: تقسیم main.py دوره به routes.py و data.py؛ جایگزینی Repository با پیادهسازی SQLAlchemy بدون تغییر Router، در SQLAlchemy 2 و SQLModel؛ استفادهٔ دوباره از Service در CLI یا کار پسزمینه.
| Layer | چه میشناسد؟ | چه نمیشناسد؟ | ابزار تست |
|---|---|---|---|
| Router | HTTP، کد وضعیت، Schema، Dependency | SQL | TestClient |
| Service | قاعده و خطای Domain | HTTP، Request، کد وضعیت | pytest ساده و پایگاه دادهٔ تست |
| Repository | SQL، ردیفها، Driver پایگاه داده | قاعدهٔ کسبوکار، HTTP | پایگاه دادهٔ واقعی SQLite/PostgreSQL |
| Schema | شکل API | ماندگاری داده (Persistence) | تست Router |
| Model | شکل Persistence | شکل API | تست Repository |
راهحل / روش استفاده: Router سبک، Service خالص و SQL فقط در Repository باشد. Service خطای Domain ایجاد کند و در یک محل به HTTP نگاشت شود؛ در هر Router یا در کل برنامه با Exception handler؛ خطاها و پاسخها.
import نسبی در Package، __init__.py و import دوری (Imports and circular imports) مهم
به زبان ساده: داخل Package، ماژول همسایه با یک نقطه import میشود: from .repository import OrderRepository؛ ماژول Package والد با دو نقطه: from ..db import Database. واردکردن مطلق (Absolute import)، مثل from shop.core.db import Database، همیشه از هر جا کار میکند. واردکردن دوری (Circular import) وقتی رخ میدهد که A از B و B مستقیم یا با واسطه از A import کند و یکی نامی را بخواهد که هنوز ساخته نشده است.
بدفهمی رایج: «Relative import با اجرای مستقیم فایل هم کار میکند.» فایل اجراشده بهعنوان اسکریپت Package ندارد؛ python app/orders/script.py خطای واقعی ImportError: attempted relative import with no known parent package میدهد. آموزش Python: "relative imports are based on the name of the current module's package. Since the main module does not have a package, modules intended for use as the main module of a Python application must always use absolute imports." آن را به شکل ماژول اجرا کنید: python -m app.orders.script. رفتن بیشازحد به بالا، مثل from ...config import settings در app/orders/، خطای واقعی ImportError: attempted relative import beyond top-level package میدهد.
تعریف: PEP 328: "A single leading dot indicates a relative import, starting with the current package. Two or more leading dots give a relative import to the parent(s) of the current package, one level per dot after the first." پیام واقعی چرخه در بررسی آزمایشی، وقتی catalog از orders و orders از catalog import میکند: ImportError: cannot import name 'count_orders_for' from partially initialized module 'app.orders.service' (most likely due to a circular import). شیء ماژول بهمحض شروع import در sys.modules وجود دارد، اما نامهایش با اجرای بدنه ساخته میشوند؛ from X import name در این فاصله ماژولی نیمهساخته پیدا میکند.
python -c "import app.orders.service" (real probe, imports-probe/)
1 start app.orders.service sys.modules["app.orders.service"] = <empty module>
2 line 1: from app.catalog.service import find_product
3 start app.catalog.service
4 line 1: from app.orders.service import count_orders_for
5 app.orders.service is in sys.modules but count_orders_for is not defined yet (we are still at its line 1)
6 ImportError: cannot import name 'count_orders_for' from partially initialized module ...
7 fix: catalog must not import orders; move the shared piece to core/ or invert the callسناریوی واقعی: orders قیمت محصول میخواهد و catalog تعداد سفارش هر محصول را؛ هر دو از هم import میکنند و برنامه هنگام Startup شکست میخورد. Import صرفاً برای راهنمای نوع (Type hint) هم ممکن است چرخه بسازد؛ راهحل if TYPE_CHECKING: و Annotation رشتهای است. فایل __init__.py که همهچیز را دوباره صادر میکند نیز هر import را به import کل Package تبدیل میکند.
| شکل | مثال | کاربرد |
|---|---|---|
| Relative در همان Package | from .repository import OrderRepository | داخل Feature |
| Relative از والد | from ..dependencies import get_token_header؛ آموزش | داخل برنامهٔ کوچک |
| Absolute | from shop.catalog.service import find_product | میان Featureها، در تست و اسکریپت |
| Import ماژول | from shop.catalog import router as catalog | جلوگیری از تداخل نام متغیرهای router |
Import با if TYPE_CHECKING: | فقط نوعها | شکستن چرخهٔ ناشی از Annotation |
بازصادرات در __init__.py | from .service import find_product | محدود؛ یک رابط عمومی برای هر Feature |
راهحل / روش استفاده: داخل Feature نسبی و میان Featureها مطلق import کنید. جهت وابستگی یکطرفه باشد: Featureها → core و orders → catalog، هرگز برعکس. کد را با python -m یا Package نصبشده اجرا کنید. چرخهٔ import علامت مسئلهٔ طراحی است؛ آن را با import داخل تابع پنهان نکنید.
src layout در برابر flat و قواعد نامگذاری (src layout vs flat layout) تکمیلی
به زبان ساده: در Layout تخت (Flat layout)، Package قابل import یعنی shop/ کنار pyproject.toml است؛ در src layout داخل src/shop/. در مورد src layout باید پروژه را نصب کنید یا PYTHONPATH=src بگذارید تا قابل import شود؛ این کار تضمین میکند چیزی را تست کنید که تحویل میدهید. مثال از flat استفاده میکند تا pythonpath = ["."] در pytest کافی باشد.
بدفهمی رایج: «src برای برنامه اجباری است.» پیشنهاد بستهبندی است و بیشترین اهمیتش برای کتابخانه و تست Package نصبشده است. Packaging User Guide: "The src layout requires installation of the project to be able to run its code, and the flat layout does not" و "helps prevent accidental usage of the in-development copy of the code"، چون "the Python interpreter includes the current working directory as the first item on the import path". pytest میگوید: "especially if you use the default import mode prepend, it is strongly suggested to use a src layout."
تعریف: در بررسی واقعی پروژهٔ src، اجرای python -c "import shopx" از ریشهٔ پروژه خطای ModuleNotFoundError: No module named 'shopx' داد؛ با PYTHONPATH=src فایل srcdemo/src/shopx/__init__.py import شد. قواعد نامگذاری مفید برای سرویس FastAPI: نام ماژول با حروف کوچک؛ یک router.py در هر Feature؛ schemas.py برای مدل API در Pydantic و models.py برای Persistence؛ service.py و repository.py مفرد؛ deps.py یا dependencies.py؛ config.py برای settings؛ نام tag برابر نام Feature؛ و نام تابع شبیه متد SDK، مثل list_products، get_product و create_order.
flat (this snippet) src
1 pyproject.toml pyproject.toml
2 shop/__init__.py src/shop/__init__.py
3 tests/... tests/...
4 pytest: pythonpath = ["."] pytest: pythonpath = ["src"] or pip install -e .
5 uvicorn shop.asgi:app (from the root) uvicorn shop.asgi:app after install, or --app-dir src
6 risk: the CWD copy shadows the installed one risk: forgetting to reinstall after adding package dataسناریوی واقعی: Layout راهنمای fastapi-best-practices، مثل src/auth/router.py و src/posts/service.py؛ Image مربوط به Docker که با pip install . پروژه را نصب و از / اجرا میکند تا درخت کد منبع Package نصبشده را نپوشاند؛ monorepo با چند سرویس که هر کدام src/<service>/ خود را دارند.
| نام | محتوا | پرهیز از |
|---|---|---|
router.py / routers/ | APIRouter و Path operation | قاعدهٔ کسبوکار، SQL |
schemas.py | مدل درخواست و پاسخ Pydantic | کلاس ORM |
models.py | مدل ORM/Persistence | شکل صرفاً مخصوص API |
service.py | منطق و خطای Domain | Request، HTTPException |
repository.py یا crud.py | Queryها | کد وضعیت |
deps.py | Dependency مثل get_db و require_admin | منطق سنگین |
config.py | Settings، get_settings | خواندن متغیر محیطی در جای دیگر |
main.py / asgi.py | Factory / ورودی Process | Routeها |
راهحل / روش استفاده: برای سرویس منفرد، flat همراه pythonpath = ["."]؛ وقتی Package منتشر میشود یا میخواهید نسخهٔ نصبشده زیر تست باشد، src همراه نصب قابل ویرایش (Editable install). نام فایلها در همهٔ Featureها یکسان باشد.
نسخهبندی API با Router: /v1 و /v2 کنار هم (API versioning with routers) مهم
به زبان ساده: Routeهای هر نسخه را زیر Router با prefix="/v1" یا prefix="/v2" قرار دهید و هر دو را include کنید. Endpoint بدون تغییر میتواند در هر دو نسخه include شود؛ Endpoint تغییریافته در v2، Router و مدل پاسخ تازه میگیرد. سند OpenAPI هر دو را کنار هم نشان میدهد.
بدفهمی رایج: «کپی کل Package مربوط به v1 در v2 یعنی نسخهبندی.» این کار کد همهٔ Endpointهای بدون تغییر را دو برابر میکند. فقط آنچه عوض شده نسخهٔ تازه بگیرد. در مثال، v2 فقط یک Route دارد: GET /api/v2/products/{product_id}، پاسخ واقعی {"price":{"amount":"45.00","currency":"EUR"}} میدهد، در حالی که v1، price_cents را نگه میدارد. اینکه اصلاً چه وقت نسخه بسازیم و v1 چقدر بماند، تصمیم طراحی در نسخهبندی و تکامل API است.
تعریف: آموزش: "You can also use .include_router() multiple times with the same router using different prefixes. This could be useful, for example, to expose the same API under different prefixes, e.g. /api/v1 and /api/latest." اگر operationId از نام تابع باشد، include دوباره تداخل ایجاد میکند؛ هشدار واقعی Duplicate Operation ID status_. شناسهٔ مبتنی بر tag وقتی Router هر نسخه tag خودش را دارد یکتا میماند: catalog-v2-get_product.
build_api_router()
1 v1 = APIRouter(prefix="/v1"): catalog.router, orders.router, admin.router (hidden)
2 v2 = APIRouter(prefix="/v2"): catalog_v2.router (tags=["catalog-v2"])
3 api.include_router(v1); api.include_router(v2); app.include_router(api, prefix="/api")
4 GET /api/v1/products/2 -> {"price_cents": 4500, ...}
5 GET /api/v2/products/2 -> {"price": {"amount": "45.00", "currency": "EUR"}, ...}
6 later: app.include_router(api_v1, deprecated=True) marks v1 in the docs; removal after the sunset dateسناریوی واقعی: اپ موبایل که بهروزرسانی اجباری ندارد و یک سال v1 را صدا میزند؛ /api/latest بهعنوان نام مستعار (Alias) آخرین نسخه برای ابزار داخلی؛ v2 که فقط نمایش پول را تغییر میدهد.
| روش | ابزار FastAPI | بدهبستان |
|---|---|---|
| نسخه در Path نشانی | prefix مربوط به Router؛ /v1 و /v2 | آشکار، قابل Cache، Routing آسان در Gateway |
| یک Router زیر دو prefix | دو بار include_router(r, prefix=...) | مراقب operationId باشید |
نسخه در Header؛ Accept-Version | Dependency یا APIRouter.matches()؛ آزمایشی در 0.137.0+ | در URL دیده نمیشود؛ Cache سختتر |
| استقرار جدا برای هر نسخه | دو برنامه پشت Gateway | بیشترین جداسازی و هزینه |
| منسوخکردن | deprecated=True روی include؛ Headerهای Sunset/Deprecation در Middleware | تاریخها را اعلام کنید |
راهحل / روش استفاده: از Router نسخهبندی با prefixهای /v1 و /v2 استفاده کنید؛ Package را کپی نکنید. هر Router نسخه tag خودش را داشته باشد؛ Router مشترک مشترک بماند؛ نسخهٔ قدیمی هنگام include منسوخ علامت بخورد.
Mount کردن Sub-application و فایل ایستا با app.mount (Mounts and sub-applications) مهم
به زبان ساده: app.mount("/legacy", other_app) همهٔ درخواستهای زیر /legacy را به برنامهٔ ASGI کاملاً جدا میدهد؛ با Route، /legacy/docs، Middleware و Exception handler خودش. app.mount("/static", StaticFiles(directory=...)) همین کار را با سرویسدهندهٔ فایل Starlette میکند. برای بخشهای API خودتان include_router و برای چیزی که واقعاً برنامهای دیگر است mount به کار ببرید.
بدفهمی رایج: «Mount و include دو روش انجام یک کارند.» آموزش: "'Mounting' means adding a completely 'independent' application in a specific path". برنامهٔ Mountشده در سند OpenAPI اصلی نیست، lifespan والد را نمیگیرد و root_path میبیند؛ خروجی واقعی {"root_path": "/legacy"}. FastAPI از آن استفاده میکند تا مستندات زیربرنامه کار کنند: "FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a root_path."
تعریف: در Starlette Routing، Mount('/users', routes=[...]) برای Routeهای فرعی و Mount("/static", app=StaticFiles(directory="static"), name="static") برای برنامه است. در مثال /static/robots.txt پاسخ واقعی ۲۰۰ میدهد و /legacy/docs پاسخ واقعی 200 text/html; charset=utf-8؛ سند اصلی /openapi.json هیچ Path مربوط به /legacy ندارد. جدول Route هر دو را پس از Routeهای API بهشکل ورودی Mount فهرست میکند. در FastAPI جاری، Frontend تکصفحهای Buildشده بهتر است با app.frontend("/", directory="dist") سرویس داده شود؛ از 0.138.0+. این تابع "low-priority routes" ثبت میکند که "only if no normal route matched" بررسی میشوند.
request route table (in order) handled by
1 GET /api/v1/products/2 APIRoute /api/v1/products/{id} shop app, main lifespan state
2 GET /static/robots.txt Mount /static StaticFiles (no OpenAPI entry)
3 GET /legacy/report Mount /legacy legacy FastAPI app: lifespan_ran false, root_path /legacy
4 GET /legacy/docs Mount /legacy legacy app's own Swagger UI
5 GET /nope no match 404 from the main app (with x-request-id: middleware wraps it)سناریوی واقعی: ادمین قدیمی Flask یا Django با سازگارکنندهٔ ASGI زیر /admin-legacy؛ برنامهٔ صادرکنندهٔ سنجه زیر /metrics؛ برنامهٔ GraphQL زیر /graphql؛ فایل ایستا در توسعه، با Nginx یا CDN در production.
| نیاز | ابزار | Router/مستندات والد را میگیرد؟ | lifespan والد را میگیرد؟ |
|---|---|---|---|
| Feature همین API | include_router | بله | بله |
| برنامهٔ FastAPI/Starlette جدا | app.mount(path, app) | خیر؛ مستندات خودش | خیر |
| فایلهای یک پوشه | app.mount("/static", StaticFiles(...)) | خیر | — |
| برنامهٔ تکصفحهای (SPA) Buildشده؛ 0.138.0+ | app.frontend("/", directory="dist") | Route کماولویت | — |
| برنامهٔ WSGI | Mount با ASGI adapter | خیر | خیر |
راهحل / روش استفاده: Feature خودتان را include کنید؛ فقط برنامهٔ مستقل و فایل را Mount کنید، با StaticFiles برای فایل و app.mount برای زیربرنامه. به برنامهٔ Mountشده مقداردهی اولیهٔ مستقل از lifespan بدهید، یا Factory منبع مشترک را به آن تحویل دهد.
جای Middleware نسبت به Routerها (Middleware placement) مهم
به زبان ساده: میانافزار (Middleware) کل برنامه را دربرمیگیرد، نه یک Router را. پیش از Routing برای همهٔ درخواستها اجرا میشود، از جمله ۴۰۴ و Path برنامهٔ Mountشده. آخرین Middleware اضافهشده بیرونیترین است. رفتاری که فقط به یک Router تعلق دارد باید در Dependency آن باشد.
بدفهمی رایج: «میتوانم به APIRouter، Middleware اضافه کنم.» در FastAPI 0.128.8 نمیتوانید؛ Router متد add_middleware ندارد. یادداشت 0.137.0، "Middleware per router" را فقط زیر "Future Features Enabled" آورده است. رفتار مختص Router در وضعیت مورد بحث با Router dependency اجرا میشود.
تعریف: مستندات FastAPI: "each new middleware wraps the application, forming a stack. The last middleware added is the outermost, and the first is the innermost. On the request path, the outermost middleware runs first." در مثال، Middleware شناسهٔ درخواست اول و CORS آخر اضافه شده؛ پس CORS بیرونی است. درخواست پیشبررسی (Preflight) با OPTIONS را CORSMiddleware پاسخ میدهد و هرگز به Middleware شناسهٔ درخواست نمیرسد. تست test_cors_is_outermost_when_enabled پاسخ ۲۰۰ با access-control-allow-origin و بدون x-request-id میگیرد؛ اما ۴۰۴ عادی x-request-id دارد، مطابق test_static_mount_and_middleware.
app.add order: request_id (1st), CORSMiddleware (2nd) -> stack from outside in:
1 ServerErrorMiddleware (Starlette, always outermost)
2 CORSMiddleware preflight OPTIONS answered here (no x-request-id)
3 request_id middleware adds x-request-id, x-process-time-ms (real: x-process-time-ms: 1.28)
4 ExceptionMiddleware HTTPException -> JSON
5 Router /api/v1/..., /healthz, Mount /static, Mount /legacy
6 router dependencies require_admin for /api/v1/admin/* onlyسناریوی واقعی: شناسهٔ درخواست و Access log برای همهٔ درخواستها با Middleware؛ CORS برای مرورگر بهعنوان Middleware بیرونی؛ Authentication فقط برای Router ادمین با Dependency؛ و GZip برای پاسخ بزرگ با Middleware.
| حوزهٔ اعمال مورد نظر | ابزار | دلیل |
|---|---|---|
| همهٔ درخواستها، حتی 404 | Middleware | پیش از Routing اجرا میشود |
| یک Router | Router dependency | در 0.128.8 نمیتوان حوزهٔ Middleware را به Router محدود کرد |
| یک Route | Decorator dependency | محدودترین مورد |
| CORS preflight | CORSMiddleware، آخر اضافه شود | باید پیش از بقیه پاسخ دهد |
| فقط برنامهٔ Mountشده | Middleware خود آن برنامه | پشتهٔ جدا |
راهحل / روش استفاده: Middlewareها را در Factory با ترتیب عمدی اضافه کنید؛ CORS آخر. آنها را کمهزینه نگه دارید و رفتار مختص Router را به dependencies ببرید.
تست متناظر با Package و جای conftest (Tests mirroring packages) مهم
به زبان ساده: تست shop/orders/ در tests/shop/orders/ و تست shop/core/ در tests/shop/core/ باشد. هر وضعیت آمادهٔ تست (Fixture) را در conftest.py پایینترین پوشهای بگذارید که به آن نیاز دارد: settings مشترک در tests/conftest.py و app و client مخصوص Package در tests/shop/conftest.py. محل فایل تست نشان میدهد چه ماژولی را میسنجد و با جابهجایی Feature، تست هم همراهش میرود.
بدفهمی رایج: «فایلهای تست در پوشههای مختلف همیشه میتوانند همنام باشند.» با حالت (Mode) پیشفرض import pytest یعنی prepend و بدون __init__.py، دو فایل test_router.py تداخل دارند. مثال --import-mode=importlib را تنظیم کرده؛ پیشنهاد pytest: "For new projects, we recommend to use importlib import mode". تصور دیگر: «Fixtureهای conftest سراسریاند.» حوزهٔ آنها پوشه است: "each directory can have its own conftest.py with its own fixtures, adding on to the ones provided by the conftest.py files in parent directories". پس tests/layered/ هرگز Fixture با نام client در shop را نمیبیند.
تعریف: درخت تست مثال و حوزهٔ Fixtureها:
1 tests/
2 ├── conftest.py autouse: clear SHOP_* env vars, get_settings.cache_clear(); fixture: settings
3 ├── before/test_before.py the flat app's problems (5 tests)
4 ├── layered/test_layered.py the layer-based package (2)
5 ├── shop/conftest.py app = create_app(settings), client (with TestClient), admin_headers
6 ├── shop/test_app.py OpenAPI organisation, hidden routes, mounts, middleware (7)
7 ├── shop/catalog/test_catalog_router.py (3) shop/orders/test_orders_router.py (2), test_orders_service.py (2, no HTTP)
8 ├── shop/core/test_settings.py (9, incl. the prod default-token refusal), test_lifespan.py (2)
9 ├── test_router_semantics.py APIRouter rules on 0.128.8 (12)
10 └── test_layouts_equivalent.py layered and shop publish the same operations (1)
11 real run: 45 passed, 2 warnings in 0.63s (the warnings are the Before app's on_event)سناریوی واقعی: تیمی که مالک shop/payments/ و tests/shop/payments/ است؛ Fixture راهانداز PostgreSQL تست در tests/shop/conftest.py تا تست واحد (Unit test) خالص در پوشهٔ دیگر هزینهاش را ندهد؛ CI که برای تغییر shop/orders/، فرمان pytest tests/shop/orders اجرا میکند.
| Fixture | محل | مصرفکننده |
|---|---|---|
| پاککردن محیط و Cache تنظیمات؛ autouse | tests/conftest.py | همهٔ تستها |
settings | tests/conftest.py | همهٔ Packageها |
app، client، admin_headers | tests/shop/conftest.py | فقط تست shop |
db در سطح Service | tests/shop/orders/test_orders_service.py | همان فایل |
| پایگاه دادهٔ تست PostgreSQL | conftest بستهای که نیاز دارد | تست FastAPI |
راهحل / روش استفاده: درخت Package را تکرار کنید، Fixture در محدودترین پوشه باشد، --import-mode=importlib به کار ببرید، برای هر تست برنامهٔ تازه از Factory بسازید و Service را بدون HTTP تست کنید.
سازوکارها (Mechanics)
عملکرد گامبهگام include_router؛ 0.128.8 در برابر 0.137.0+ (What include_router does, step by step) مهم
در نسخهٔ ثابتشده، APIRouter.include_router(router, prefix=..., tags=..., dependencies=..., responses=..., ...) حلقهای است که هر Route متعلق به Router ورودی را روی Router includeکننده دوباره ثبت میکند. این ترتیب از fastapi/routing.py با tag برابر 0.128.8 خوانده شده است:
self.include_router(router, prefix, tags, dependencies, responses, ...)
1 assert self is not router "Cannot include the same APIRouter instance into itself."
2 if prefix: assert prefix.startswith("/"), not prefix.endswith("/")
3 else: any route with an empty path -> FastAPIError("Prefix and path cannot be both empty ...")
4 for route in router.routes: the routes that exist NOW
5 APIRoute: self.add_api_route(prefix + route.path, route.endpoint,
tags = include tags + route tags, dependencies = include deps + route deps,
responses = {**include responses, **route.responses},
response_class = first of route / router default / include default / self default,
include_in_schema = route and self and include, deprecated = route or include or self,
generate_unique_id_function = first of route / router / include / self)
6 Starlette Route / WebSocket routes: re-added with the prefix
7 router.on_startup / on_shutdown handlers -> self.add_event_handler(...)
8 self.lifespan_context = _merge_lifespan_context(self.lifespan_context, router.lifespan_context)نتیجه همان رفتار «کپی» است که در افزودن Router اندازهگیری شد: والد شیءهای APIRoute تازه میگیرد و تغییر بعدی Router ورودی اثری ندارد. FastAPI 0.137.0 آن را عوض کرد: "Before this, router.include_router(other_router) would take each path operation from other_router and 'clone' it … The way it is structured here is that there are a few additional classes to handle intermediate metadata for router and route inclusion". تغییر ناسازگار این است: "router.routes is no longer a plain list of APIRoute objects, it can contain these intermediate objects … forming a tree" و "router.routes should be considered an internal implementation detail". کدی که app.routes را برای فهرست Endpointها میپیماید روی 0.128.8 کار میکند؛ بررسی آزمایشی فهرست تخت چاپ میکند. در 0.137.0+ باید بهجای آن از app.openapi()["paths"] استفاده کند.
درخواست چگونه Route و منابعش را پیدا میکند (Request path) تکمیلی
GET /api/v1/products/featured (real run, uvicorn --factory)
1 Uvicorn scope built; await app(scope, receive, send)
2 ServerErrorMiddleware -> request_id middleware (CORS absent: no origins configured)
3 Router linear scan: docs routes, /api/v1/products (path mismatch), /api/v1/products/featured -> full match
4 route dependencies include-level: none for catalog; router-level: none; parameter: repo(db=get_db(request))
5 get_db request.app.state.db (set by the lifespan before the first request)
6 list_featured_products def -> thread pool; ProductRepository.list(featured_only=True) runs the SELECT
7 response_model list[ProductOut] -> JSON
8 middleware x-request-id: 2ed3bd41..., x-process-time-ms: 1.28 -> 200 OKترتیب Startup در یک Process (Startup order) تکمیلی
uvicorn shop.asgi:app --workers 2 (real log, per worker)
1 import shop.asgi -> shop.main -> shop.api -> every feature router module (routes registered on the module routers)
2 create_app(): get_settings() (lru_cache miss -> Settings read once), FastAPI(...), include_router tree, mounts
3 Uvicorn sends lifespan.startup "Waiting for application startup."
4 app lifespan (outer) -> catalog lifespan (inner, merged)
5 "Application startup complete." printed twice: one per worker [31044], [31045]
6 SIGTERM to the parent: "Terminated child process" x2, each worker "Waiting for application shutdown." -> "Application shutdown complete."متن دقیق خطا، هشدار و Log (Exact errors) حیاتی
هر خط زیر خروجی اجرای مثال یا بررسی آزمایشی ذخیرهشده است: FastAPI 0.128.8، Starlette 0.49.3، Pydantic 2.13.5، pydantic-settings 2.11.0، Uvicorn 0.39.0 و CPython 3.9.6.
| محرک | خروجی دقیق |
|---|---|
APIRouter(prefix="/items/") | AssertionError: A path prefix must not end with '/', as the routes will start with '/' |
include_router(r, prefix="items") | AssertionError: A path prefix must start with '/' |
r.include_router(r) | AssertionError: Cannot include the same APIRouter instance into itself. Did you mean to include a different router? |
include کردن @router.get("") بدون prefix | FastAPIError: Prefix and path cannot be both empty (path operation: root) |
دو Route با operation_id="read"، هنگام app.openapi() | UserWarning: Duplicate Operation ID read for function read_b at …/p1_routers.py |
Router دارای /users/{user_id} پیش از Router دارای /users/me | 422 {"type":"int_parsing","loc":["path","user_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"me"} |
Route اضافهشده پس از include_router | 404 در 0.128.8 |
@app.on_event("startup") | DeprecationWarning: on_event is deprecated, use lifespan event handlers instead. |
اشتباه تایپی SHOP_DATABSE_URL در .env | 1 validation error for Settings / shop_databse_url / Extra inputs are not permitted [type=extra_forbidden, input_value='sqlite:///typo.db', input_type=str] |
SHOP_ENVIRONMENT=prod بدون SHOP_ADMIN_TOKEN | Value error, SHOP_ADMIN_TOKEN must be set in prod (the default 'change-me' is public) [type=value_error, ...]؛ Process خارج میشود |
SHOP_ENVIRONMENT=production | Input should be 'dev', 'test', 'staging' or 'prod' [type=literal_error, input_value='production', input_type=str] |
SHOP_HTTP_TIMEOUT_S=60 با le=30 | Input should be less than or equal to 30 [type=less_than_equal, input_value='60', input_type=str] |
SHOP_CORS_ORIGINS=https://shop.example؛ غیر JSON | SettingsError: error parsing value for field "cors_origins" from source "EnvSettingsSource" |
_secrets_dir="/run/secrets-missing" | UserWarning: directory "/run/secrets-missing" does not exist |
repr(settings) | ... admin_token=SecretStr('**********') ... |
| Circular import میان دو Feature | ImportError: cannot import name 'count_orders_for' from partially initialized module 'app.orders.service' (most likely due to a circular import) |
from ...config import settings در app/orders/ | ImportError: attempted relative import beyond top-level package |
python app/orders/script.py با Relative import | ImportError: attempted relative import with no known parent package |
| src بدون نصب | ModuleNotFoundError: No module named 'shopx' |
| Route پنهان ادمین بدون Token؛ curl | 403؛ Access log: "GET /api/v1/admin/stats HTTP/1.1" 403 Forbidden |
openapi_url=None | GET /docs → 404؛ curl، دو Worker |
| Uvicorn با دو Worker | Started parent process [31039] … Application startup complete. ×2 |
حل مسائل کلاسیک (Solving the classic problems)
| اشکال | نشانه | راهحل | هزینه |
|---|---|---|---|
همهچیز در main.py | 1,500 خط، تعارض ادغام | Router برای هر Feature، Factory در main.py | یک بعدازظهر |
| prefix و tag روی هر Decorator | غلط تایپی گروه دوم Products میسازد | APIRouter(prefix=..., tags=[...]) | چند دقیقه |
| Route ادمین عمومی | هر کس /admin/reset را صدا میزند | include_router(admin, dependencies=[Depends(require_admin)]) | یک خط |
| یکیگرفتن «پنهان» با «امن» | Route پنهان هنوز قابل فراخوانی است | پنهانسازی و محافظت | یک خط |
| Route ثابت پس از پارامتری، میان Routerها | /users/me → 422 | Router خاصتر اول include شود | ترتیب |
| افزودن Route پس از include؛ ≤ 0.136 | Route تازه بیخطا 404 میدهد | ساخت درخت از پایین به بالا در تابع | تغییر ساختار |
| operationId بلند یا متداخل | نام بد SDK؛ هشدار Duplicate Operation ID | generate_unique_id_function با tag و نام؛ tag برای هر نسخه | یک تابع |
Config با os.environ.get | "false" در شرط درست است؛ عدد رشته میماند | BaseSettings نوعدار | یک کلاس |
| settings هنگام import | تست نمیتواند تغییر دهد؛ import، .env را میخواند | @lru_cache get_settings() + Factory | کم |
| Connection هنگام import | تست Connection واقعی باز میکند؛ بسته نمیشود | Lifespan + app.state | 10 خط |
on_event کنار lifespan | handler مربوط به Startup بیصدا اجرا نمیشود | انتقال همهچیز به lifespan | کم |
| انتظار lifespan در برنامهٔ Mountشده | منابع هرگز مقداردهی اولیه نمیشوند | تحویل منابع، یا include بهجای Mount | طراحی |
| Circular import میان Featureها | ImportError ... partially initialized module در Startup | وابستگی یکطرفه، Service عمومی | طراحی |
| یک برنامهٔ مشترک برای تستها | شکست وابسته به ترتیب | create_app(settings) برای هر تست | کم |
| Middleware برای یک Router | روی همهچیز اجرا میشود | Router dependency | کم |
از یک فایل به Routerها (From one file to routers)
هر گروه Route را به <feature>/router.py با router = APIRouter(prefix=..., tags=[...]) ببرید؛ prefix و tag را از Decoratorها حذف کنید و Routerها را در تابعی که Factory صدا میزند include کنید. رشتهٔ Path نسبی بماند: ""، /featured و /{product_id}. پیش و پس از تغییر، بررسی جدول Route یا app.openapi()["paths"] را اجرا کنید؛ مجموعهٔ (method, path) باید یکسان باشد. تست test_layouts_equivalent.py دقیقاً همین را برای دو Layout انجام میدهد.
پیکربندی قابل اعتماد (Configuration you can trust)
هر خواندن os.environ را با فیلدی در یک کلاس Settings عوض کنید: نوع، Literal، قید Field و SecretStr. prefix بدهید، extra="forbid" را حفظ کنید، با @lru_cache get_settings() تزریق کنید و Factory نمونهٔ Settings بپذیرد. حالا Process هنگام Startup با خطای روشن Validation شکست میخورد، نه ساعت سه صبح با اولین درخواستی که مقدار خراب را میخواند.
منابع با عمر مشخص (Resources with a lifetime)
هر چیزی که ساختش گران و اشتراکگذاریاش امن است، مانند Engine، Pool، HTTP client و Model، پیش از yield در lifespan ساخته و پس از آن بسته میشود. روی app.state میماند و با Dependency به Route میرسد. هر چیزی که متعلق به یک درخواست است، مثل Session، Transaction و کاربر جاری، در Dependency دارای yield قرار میگیرد.
مرزهایی که با رشد حفظ میشوند (Boundaries that survive growth)
Layout را آگاهانه انتخاب کنید؛ انتخاب. قواعد import را بنویسید: Featureها → core، orders → catalog.service و هرگز برعکس. ماژول عمومی هر Feature کوچک بماند و وقتی بیش از یک تیم روی کد کار میکند، CI قواعد را با Import linter بررسی کند.
انتخاب (Choosing)
| وضعیت | انتخاب | دلیل |
|---|---|---|
| کمتر از 10 Route، یک نفر | یک main.py و config.py | هزینهٔ ساختار از صرفهجویی آن بیشتر است |
| چند منبع، یک تیم | Layer فنی؛ routers/، schemas/ و غیره | آشنا؛ شکل آموزش و قالب |
| Domain زیاد، چند تیم | Feature با Vertical slice و core/ | تغییر در یک پوشه؛ مالکیت روشن |
| Router مشترک میان پروژهها | بدون prefix و Auth در فایل؛ تنظیم در include_router | استفادهٔ مجدد بدون ویرایش |
| Auth برای گروه | Dependency روی Router یا include | روی Route تازه فراموش نمیشود |
| Endpoint داخلی | include_in_schema=False و Dependency | خارج از SDK، همچنان محافظتشده |
| برنامهٔ جدا؛ legacy، GraphQL، metrics | app.mount | مستندات و پشتهٔ خودش |
| Build فرانتاند | Mount با StaticFiles در dev / app.frontend در 0.138.0+ / CDN در prod | کماولویت، قابل Cache |
| تغییر ناسازگار بعضی Endpointها | Router نسخهٔ v2 فقط برای همانها | بدون کپی کل API |
| Settings | BaseSettings + Dependency دارای lru_cache + پارامتر Factory | نوعدار، یک بار، قابل Override |
| اسرار | فایل Secret با secrets_dir یا محیط | خارج از .env روی سرور |
| پیشفرض محلی | .env نادیدهگرفتهشده و .env.example ثبتشده | شروع آسان بدون نشت |
| تست | متناظر با Package؛ conftest هر پوشه | نزدیکی کد و تست |
| کتابخانه یا Package منتشرشده | src | همان چیزی را تست کنید که تحویل میدهید |
| سرویس قابل استقرار منفرد | flat + pythonpath = ["."] | تشریفات کمتر |
زمان تغییر از Layer به Feature (When to switch)
وقتی دو نشانه برقرار شد تغییر دهید: پوشهٔ Layer در یک صفحه جا نمیشود؛ بیشتر Pull requestها سه یا بیشتر از پوشههای Layer را تغییر میدهند؛ دو تیم فایلهای یک Layer را ویرایش میکنند؛ یا به استخراج بخشی از سیستم به سرویس مستقل فکر میکنید. جابهجایی مکانیکی است: یک پوشه برای هر Feature، پنج فایل در هر کدام و بازنویسی importها. تست برابری Layout حفاظ شماست؛ Pathهای OpenAPI نباید عوض شوند.
Monorepo، سرویس منفرد و زمان تفکیک سرویسها (Monorepo vs single service)
| پرسش | یک سرویس با پوشهٔ Feature | چند سرویس در یک monorepo | چند repo |
|---|---|---|---|
| استقرار | یک واحد (Unit) | واحدهای مستقل، ابزار مشترک | همهچیز مستقل |
| فراخوانی میان Featureها | تابع Python؛ catalog.service.find_product | HTTP/gRPC/events | HTTP/gRPC/events |
| کد مشترک | Package با نام core/ | Package کتابخانهٔ مشترک در repo | Package منتشرشده |
| سازگاری (Consistency) | یک تراکنش (Transaction) | Saga/Outbox | Saga/Outbox |
| چه وقت از اینجا شروع کنید؟ | تقریباً همیشه | تیمها استقرار مستقل میخواهند | مرز سازمانی |
زمان تفکیک سرویس تصمیم معماری است، نه Layout پوشه. پوشههای Feature با مرزهای اعمالشده پیششرطی هستند که جداسازی بعدی را کمهزینه میکند. بدهبستانها در یکپارچهٔ ماژولار و معماری پاک و ششضلعی آمدهاند.
در معماری: از یک Process تا سیستم توزیعشده (In architecture)
برنامهٔ یکپارچه: یک Process، یک پایگاه داده (Monolith)
یک برنامهٔ FastAPI ساختهشده با create_app()، یک lifespan که یک Pool پایگاه داده و یک HTTP client باز میکند، Router هر Feature زیر /api/v1 و settings از محیط. بستهٔ shop/ این فصل همین شکل را با SQLite دارد؛ در production، جانشین سادهٔ Database به Engine در SQLAlchemy تبدیل میشود و اسرار از /run/secrets میآیند. جدول Route نقشهٔ API است، سند OpenAPI قرارداد آن و tests/ متناظر با Packageهاست.
یکپارچهٔ ماژولار و چند پایگاه داده (Modular monolith)
همان Process را داریم، اما پوشههای Feature ماژولهایی با مرز اعمالشدهاند. هر کدام مالک جدولهایش است: catalog مالک products و orders مالک orders. بقیه فقط service.py عمومی را صدا میزنند و هرگز Repository را؛ Import linter با import ممنوع CI را ناموفق میکند. ذخیرهساز دوم، مثل Redis برای سبد یا index جستوجو برای کاتالوگ، Client خودش را در lifespan میگیرد و ماژول مصرفکننده مالک آن است؛ lifespan مربوط به Router محل مناسبی است. اینجاست که Layout مبتنی بر Feature سودش را نشان میدهد؛ معماری در یکپارچهٔ ماژولار توضیح داده شده است.
ریزسرویسها (Microservices)
هر Feature استخراجشده برنامهٔ FastAPI خودش را با Factory، prefix تنظیمات، lifespan و سند OpenAPI مستقل میگیرد. فراخوانی Python میان Featureها به فراخوانی HTTP از طریق httpx.AsyncClient تبدیل میشود؛ Client در lifespan باز میشود و مهلت زمانی (Timeout) را از settings با http_timeout_s میگیرد. Layout مبتنی بر Feature انتقال را به جابهجایی پوشه تبدیل میکند: shop/orders/ و tests/shop/orders/ به orders-service/orders/ و تستهایش تبدیل میشوند. فراخوانی catalog.service.find_product با ماژول Client کوچکی با همان امضا جایگزین میشود. حالا ثبات operationId و tags مهمتر است، چون تیم دیگر از Schema شما Client تولید میکند.
دادهٔ توزیعشده: Replica، Cache، پایگاه دادهٔ Shardشده و چند Region (Distributed data)
هر چیزی روی app.state مختص Process است. در اجرای --workers 2 هر Worker lifespan خودش را اجرا کرد؛ دو خط "Application startup complete." ثبت شد و هر کدام Cache مخصوص featured_ids خود را خواهد داشت. وضعیت مشترک به Redis یا PostgreSQL میرود و از Clientهایی که در lifespan باز شدهاند در دسترس است. Settings توپولوژی را بدون تغییر کد قابل تنظیم میکند: URL Replica خواندنی (Read replica)، URL مربوط به Cache و نام ناحیه (Region) فیلد هستند؛ پس یک Image با متغیرهای محیطی متفاوت در همهٔ Regionها اجرا میشود. اسرار هر Region بهصورت فایل زیر Secrets directory میرسند. Cache و تأخیر Replica در Caching آمده است.
مسیر مقیاسپذیری: ۱×، ۱۰×، ۱۰۰× (Scaling path)
| بار | چه تغییر میکند؟ | روش ساختاری |
|---|---|---|
| 1×؛ یک Process، یک تیم | کد از یک فایل بزرگتر میشود | Router، Factory، settings، lifespan؛ Layer مناسب است |
| 10×؛ چند Worker و چند تیم | وضعیت Processها متفاوت میشود؛ تیمها در پوشهٔ Layer به هم میرسند | پوشهٔ Feature، وضعیت مشترک در Redis/PostgreSQL، operationId مبتنی بر tag، قواعد import، OpenAPI صادرشده از CI |
| 100×؛ سرویسها و تیمهای زیاد | قرارداد میان تیمها و استقرار مستقل | استخراج Feature در امتداد مرز پوشهٔ موجود؛ Router نسخهدار؛ prefix تنظیمات هر سرویس؛ اسرار از فایل؛ نسخهبندی API |
آزمایشگاه (Lab)
همهٔ فرمانها از docs/snippets/python/routers-project-structure/ اجرا میشوند. گامهای «واقعی» روی CPython 3.9.6 در macOS با نسخههای ثابتشده اجرا شدهاند؛ خروجیها از گزارش اجرای ذخیرهشده کپی شدهاند.
۱. نصب و اجرای تستها؛ واقعی (Install and run tests)
python3 -m venv ~/venvs/rps # the venv lives outside the repo
~/venvs/rps/bin/pip install '.[test]' # pins from pyproject.toml (FastAPI 0.128.8, pydantic-settings 2.11.0 ...)
source ~/venvs/rps/bin/activate
export PYTHONDONTWRITEBYTECODE=1 # no __pycache__ in the snippet tree; pyproject sets -p no:cacheprovider
python -m pytest -v
# tests/before/test_before.py ..... [ 11%]
# tests/layered/test_layered.py .. [ 15%]
# tests/shop/catalog/test_catalog_router.py ... [ 22%]
# tests/shop/core/test_lifespan.py .. [ 26%]
# tests/shop/core/test_settings.py ......... [ 46%]
# tests/shop/orders/test_orders_router.py .. [ 51%]
# tests/shop/orders/test_orders_service.py .. [ 55%]
# tests/shop/test_app.py ....... [ 71%]
# tests/test_layouts_equivalent.py . [ 73%]
# tests/test_router_semantics.py ............ [100%]
# before/main.py:28 DeprecationWarning: on_event is deprecated, use lifespan event handlers instead.
# 45 passed, 2 warnings in 0.63s <- both warnings are the Before app's on_event, on purpose۲. اجرای Factory با Uvicorn و فراخوانی آن؛ واقعی (Run the factory)
SHOP_ADMIN_TOKEN=lab-token SHOP_ENVIRONMENT=staging uvicorn --factory shop.main:create_app --port 18931
curl -si http://127.0.0.1:18931/api/v1/products/featured
# HTTP/1.1 200 OK
# server: uvicorn
# content-type: application/json
# x-request-id: 2ed3bd41ef1740c69d83059c8601ed9a
# x-process-time-ms: 1.28
# [{"id":2,"sku":"GM-001","name":"Catan","price_cents":4500},{"id":3,"sku":"MU-001","name":"Kind of Blue (vinyl)","price_cents":2900}]
curl -s http://127.0.0.1:18931/version # {"app":"Shop API","environment":"staging"}
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18931/api/v1/admin/stats # 403
curl -s -H "x-admin-token: lab-token" http://127.0.0.1:18931/api/v1/admin/stats
# {"orders":0,"lifespan_events":["startup","catalog:startup"]}
curl -s -X POST http://127.0.0.1:18931/api/v1/orders -H "content-type: application/json" -d '{"product_id":2,"quantity":2}'
# {"id":1,"product_id":2,"quantity":2,"total_cents":9000}
curl -s http://127.0.0.1:18931/api/v2/products/2
# {"id":2,"sku":"GM-001","name":"Catan","price":{"amount":"45.00","currency":"EUR"}}
curl -s http://127.0.0.1:18931/legacy/report # {"lifespan_ran":false,"root_path":"/legacy"}۳. خواندن سازماندهی OpenAPI؛ واقعی (Read OpenAPI organisation)
curl -s http://127.0.0.1:18931/openapi.json | python3 -c "import json,sys; d=json.load(sys.stdin); \
print([t['name'] for t in d['tags']]); print(sorted(op['operationId'] for p in d['paths'].values() for op in p.values()))"
# ['catalog', 'orders', 'catalog-v2', 'meta']
# ['catalog-create_product', 'catalog-get_product', 'catalog-list_featured_products', 'catalog-list_products',
# 'catalog-v2-get_product', 'meta-version', 'orders-create_order', 'orders-get_order']
# (no /api/v1/admin/*, no /healthz, no /static or /legacy entries)۴. دو Worker با settings محیط production؛ واقعی (Two workers)
SHOP_ENVIRONMENT=prod SHOP_DOCS_ENABLED=false uvicorn shop.asgi:app --port 18933 # no token: refused
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
# Value error, SHOP_ADMIN_TOKEN must be set in prod (the default 'change-me' is public) [type=value_error, ...]
SHOP_ENVIRONMENT=prod SHOP_DOCS_ENABLED=false SHOP_ADMIN_TOKEN=prod-lab-token uvicorn shop.asgi:app --workers 2 --port 18932
# INFO: Started parent process [31039]
# INFO: Started server process [31044]
# INFO: Started server process [31045]
# INFO: Application startup complete. <- twice: one lifespan (and one settings read) per worker
# INFO: Application startup complete.
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18932/docs # 404 (openapi_url=None)
curl -s http://127.0.0.1:18932/version # {"app":"Shop API","environment":"prod"}
curl -s -o /dev/null -w "%{http_code}\n" -H "x-admin-token: change-me" http://127.0.0.1:18932/api/v1/admin/stats # 403۵. خرابکردن عمدی؛ بررسی واقعی در کپی موقت (Break it on purpose)
# a) include a router, then add a route to it: 404, app.routes has only the docs routes (runs/p1-output.txt)
# b) swap the order of two routers sharing /users: GET /users/me -> 422 int_parsing (test_route_order_across_routers)
# c) make catalog import orders and orders import catalog:
# ImportError: cannot import name 'count_orders_for' from partially initialized module 'app.orders.service'
# d) add SHOP_DATABSE_URL=... to .env: ValidationError ... [type=extra_forbidden ...]
# e) set SHOP_ENVIRONMENT=production: ValidationError ... [type=literal_error ...]۶. اجرا روی FastAPI جاری؛ انتظار میرود، اجرا نشده (Current FastAPI)
روی Python 3.12 با fastapi>=0.137 انتظار میرود دستکم test_routes_added_after_include_are_missing_on_0_128 و test_nested_router_must_be_complete_before_it_is_included شکست بخورند، چون Router زنده میماند و Route دیرتر اضافهشده ۲۰۰ میدهد. Assertهای دیگری که به جزئیات 0.128.8 مثل operationId پیشفرض یا متن هشدار بستهاند نیز شاید به تغییر نیاز داشته باشند. انتظار میرود fastapi run از fastapi[standard]، برنامه را از [tool.fastapi] entrypoint = "shop.asgi:app" پیدا کند. هیچیک از این دو اجرا اینجا انجام نشده است.
برای توسعهدهندهٔ PHP/Laravel (For PHP/Laravel developers)
Laravel همین پرسشها را با قرارداد پاسخ میدهد، نه با شیء. فایلهای Route همان نقش Router را دارند: "All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by Laravel using the configuration specified in your application's bootstrap/app.php file." فایل Laravel یعنی routes/api.php نزدیکترین معادل api_router با prefix است: "The routes in routes/api.php are stateless and are assigned to the api middleware group. Additionally, the /api URI prefix is automatically applied to these routes". این prefix با apiPrefix: در withRouting(...) تغییر میکند. عبارت Route::prefix('admin')->middleware('auth')->group(...) معادل include_router(admin, prefix="/admin", dependencies=[...]) است. فایل Route تازه در Closure با نام then: متعلق به withRouting ثبت میشود، همانطور که Router تازه به build_api_router() افزوده میشود. کنترلکنندهها (Controllers) محل Path operation در Laravel هستند؛ Controller تکعملیاتی با __invoke معادل یک تابع Path operation در FastAPI است. فراهمکنندههای سرویس (Service providers) نقش lifespan و Factory را یکجا دارند: "Service providers are the central place of all Laravel application bootstrapping". متد register برای Bindingهای Container و boot برای بقیه است و ثبت در bootstrap/providers.php انجام میشود. مدل Process فرق دارد: زیر PHP-FPM، Provider با هر درخواست boot میشود؛ lifespan در FastAPI یک بار در هر Worker اجرا میشود؛ Laravel Octane رفتار Laravel را به آن نزدیک میکند. پیکربندی شباهت مهم دیگر است: .env در Laravel، "can be overridden by external environment variables such as server-level or system-level environment variables"؛ همان اولویت pydantic-settings. مقدارها رشتهاند و مستندات تبدیل صریح نشان میدهد: 'debug' => (bool) env('APP_DEBUG', false). پس از php artisan config:cache، "your application's .env file will not be loaded by the framework during requests"؛ شبیه بردن lru_cache روی get_settings() به مرحلهٔ استقرار. درخت پیشفرض app/ در Laravel با Http، Models و Providers مبتنی بر Layer است؛ پوشهٔ Feature مثل app/Domain/Orders/... آنجا هم قرارداد جامعه است.
// bootstrap/app.php (Laravel 13): the factory, the route tree and the API prefix
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php', // include_router(api_router, prefix="/api")
apiPrefix: 'api',
then: function () { // another router file, like admin.router at include time
Route::middleware(['api', 'auth:sanctum', 'can:admin']) // dependencies=[Depends(require_admin)]
->prefix('api/v1/admin') // prefix="/admin" under /api/v1
->group(base_path('routes/admin.php'));
},
)->create();
// routes/api.php: the v1 tree; one controller per feature (shop/catalog/router.py, shop/orders/router.py)
Route::prefix('v1')->group(function () {
Route::get('/products/featured', [ProductController::class, 'featured']); // literal before {product}
Route::get('/products/{product}', [ProductController::class, 'show']);
Route::post('/orders', StoreOrderController::class); // single-action controller (__invoke)
});
// config/shop.php: typed config read once (php artisan config:cache), like get_settings()
return ['timeout' => (float) env('SHOP_HTTP_TIMEOUT_S', 2.0), 'docs' => (bool) env('SHOP_DOCS_ENABLED', true)];| Laravel 13 | FastAPI |
|---|---|
routes/api.php در Laravel با prefix خودکار /api | app.include_router(api_router, prefix="/api") |
Route::prefix('v1')->group(...) | APIRouter(prefix="/v1") + include_router |
->middleware('auth') روی گروه | include_router(r, dependencies=[Depends(auth)]) |
فایل Route ثبتشده در withRouting(then: ...) | افزودن Router یک Feature با build_api_router() |
Controller؛ Resource یا تکعملیاتی __invoke | تابع Path operation در router.py |
Service provider با register و boot، فایل bootstrap/providers.php | create_app() + lifespan |
| Binding در Service container | Provider با Depends(...) و منبع روی app.state |
.env + config/*.php + env() | .env + BaseSettings |
php artisan config:cache | @lru_cache get_settings() |
اولویت متغیر محیطی بر .env | همان قاعده در pydantic-settings |
| فایل env رمزشده در کنترل نسخه | فایل Secret زیر secrets_dir |
app/Http و app/Models؛ مبتنی بر Layer | routers/ و models/؛ مبتنی بر Layer |
پوشهٔ Domain؛ app/Domain/Orders | shop/orders/؛ مبتنی بر Feature |
php artisan route:list | app.routes / /openapi.json |
tests/Feature، tests/Unit | tests/shop/<feature>/، تست Service بدون HTTP |
زاویهٔ Go (The Go angle)
همتای این فصل چیدمان، Lint و Build پروژهٔ Go است. راهنمای رسمی Go شکل سروری را توضیح میدهد که Package مبتنی بر Feature بازتابش میدهد: "Server projects typically won't have packages for export, since a server is usually a self-contained binary … it's recommended to keep the Go packages implementing the server's logic in the internal directory. Moreover, since the project is likely to have many other directories with non-Go files, it's a good idea to keep all Go commands together in a cmd directory." ترکیب cmd internal pkg زیاد نقل میشود، اما راهنمای رسمی فقط cmd/ و internal/ را توضیح میدهد؛ pkg/ قرارداد جامعه برای کدی است که قرار است ماژول دیگر import کند. دو تفاوت مهم است. مرز را کامپایلر اعمال میکند: Package زیر internal/، "cannot be imported outside this module"، و چرخهٔ import خطای کامپایل است. Python چرخه را زمان اجرا با ImportError ... partially initialized module پیدا میکند و قاعدهٔ internal ندارد؛ import-linter این کمبود را پر میکند. Factory و lifespan همان main() هستند: lifespan در Framework نداریم؛ cmd/api/main.go، Config را در Struct میخواند، Pool را باز میکند، Router میسازد؛ یک ServeMux برای هر Feature با http.StripPrefix یا Sub-router وصل میشود؛ سپس سرویس میدهد و پس از srv.Shutdown(ctx) منابع را میبندد.
// cmd/api/main.go: config -> resources -> routes -> serve -> shutdown (create_app + lifespan in one function)
func main() {
cfg := config.MustLoad() // like Settings(): env vars into a typed struct, fail fast
db := store.MustOpen(cfg.DatabaseURL) // lifespan, before yield
defer db.Close() // lifespan, after yield
api := http.NewServeMux()
catalog.Register(api, catalog.NewService(db)) // internal/catalog: router + service + repository
orders.Register(api, orders.NewService(db, catalog.API)) // orders depends on catalog's exported API only
root := http.NewServeMux()
root.Handle("/api/v1/", http.StripPrefix("/api/v1", api)) // include_router(v1, prefix="/api/v1")
root.Handle("/static/", http.FileServer(http.Dir("static")))
srv := &http.Server{Addr: cfg.Addr, Handler: requestID(root)} // middleware wraps everything, like FastAPI
go func() { _ = srv.ListenAndServe() }()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, os.Interrupt)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}| دغدغه | FastAPI | Go |
|---|---|---|
| گروه Route | APIRouter | یک ServeMux یا تابع Register(mux) برای هر Package |
| Prefix | prefix= / include_router(prefix=) | http.StripPrefix یا prefix الگو |
| Auth گروه | Router dependency | Middleware دور همان Sub-mux |
| App factory | create_app(settings) | run(cfg) error که از main صدا زده میشود |
| Lifespan | asynccontextmanager + yield | defer و srv.Shutdown(ctx) در main |
| Settings | BaseSettings، متغیر محیطی، .env، فایل Secret | Struct و تبدیل محیط؛ کتابخانهٔ استاندارد یا خارجی |
| پوشهٔ Feature | shop/orders/ | internal/orders/ |
| اعمال مرز | قرارداد و import-linter | قاعدهٔ internal/ و کامپایلر |
| چرخهٔ import | ImportError زمان اجرا | خطای کامپایل |
| Entry point | shop/asgi.py، [tool.fastapi] entrypoint | cmd/api/main.go |
بدفهمیهای رایج (Common misconceptions)
| باور | واقعیت |
|---|---|
APIRouter برنامهای جداست | Routeهایش به جدول و سند OpenAPI واحد برنامه میپیوندند؛ mount برنامهٔ جدا میسازد |
Route اضافهشده پس از include_router سرویس میدهد | پیش از 0.137.0 نه؛ هنگام include کپی میشود؛ 404 اندازهگیری شده |
| اول prefix Router و بعد داخلش تطبیق داده میشود | یک جدول تخت و مرتب؛ نخستین تطبیق میان همهٔ Routerها برنده است |
| Route تکراری میان Routerها خطا میدهد | اولی بیصدا برنده است |
prefix میتواند با / تمام شود | AssertionError: A path prefix must not end with '/' |
| tags مربوط به Router جای tags مربوط به Route را میگیرد | فهرستها متصل میشوند؛ اول include، سپس Route |
include_in_schema=False محافظت میکند | پنهان میکند؛ محافظت با Dependency است |
| FastAPI، operationId تکراری را رد میکند | هنگام ساخت Schema، UserWarning میدهد |
| Middleware به یک Router وصل میشود | در 0.128.8 نه؛ Router dependency به کار ببرید |
on_event و lifespan ترکیب میشوند | با lifespan=، Event handler اجرا نمیشود |
| برنامهٔ Mountشده lifespan والد را میگیرد | فقط برنامهٔ سطح بالا رویداد lifespan میگیرد |
TestClient(app)، lifespan را اجرا میکند | فقط داخل with TestClient(app) |
.env بر متغیر محیطی اولویت دارد | محیط بر .env و .env بر فایل Secret غالب است |
غلط تایپی .env نادیده گرفته میشود | پیشفرض extra="forbid" خطای extra_forbidden میدهد |
bool(os.environ["DEBUG"]) درست کار میکند | "false" در شرط درست است؛ از فیلد نوعدار Settings بخوانید |
Settings() در Dependency کافی است | بدون lru_cache با هر درخواست .env را دوباره میخواند |
| تغییر متغیر محیطی در اجرا settings را عوض میکند | تا get_settings.cache_clear() نه |
| Layout مبتنی بر Feature، Layer ندارد | هر Feature همهٔ Layerها را در فایلهای جدا دارد |
| پوشه مرز ماژول را اعمال میکند | در Python فقط ابزار مثل import-linter یا بازبینی آن را اعمال میکند |
| Relative import در اسکریپت کار میکند | attempted relative import with no known parent package؛ از python -m استفاده کنید |
| src اجباری است | برای Package و تست نسخهٔ نصبشده توصیه میشود؛ flat برای سرویس کار میکند |
app.state میان Workerها مشترک است | هر Worker process وضعیت و lifespan خودش را دارد |
برگهٔ تقلب (Cheat sheet)
| موضوع | به یاد بسپارید |
|---|---|
| Router | router = APIRouter(prefix="/products", tags=["catalog"], responses={404: ...}) |
| Include | app.include_router(r, prefix=..., tags=..., dependencies=[...], include_in_schema=...) |
| تودرتویی | ساخت از پایین به بالا؛ v1.include_router(child) پیش از app.include_router(v1)؛ رفتار کپی در ≤ 0.136 |
| Prefix | با / شروع و هرگز با / تمام نشود؛ @router.get("") خود prefix را سرویس میدهد |
| ترتیب | نخستین تطبیق میان همهٔ Routerها برنده؛ Router خاصتر اول |
| Dependencies | app → include → router → decorator → parameters |
| Responses | {**include_responses, **route.responses}؛ Route برنده است |
| operationId | generate_unique_id_function=lambda r: f"{r.tags[0]}-{r.name}"؛ یک tag برای هر نسخه |
| مستندات | openapi_tags=[...]، include_in_schema=False، openapi_url=None متناسب با محیط |
| Factory | create_app(settings=None) -> FastAPI؛ asgi.py: app = create_app()؛ uvicorn --factory |
| Lifespan | @asynccontextmanager + yield؛ منابع روی app.state؛ دسترسی با request.app.state |
| lifespan مربوط به Router | APIRouter(lifespan=...) داخل lifespan برنامه؛ Mount چیزی نمیگیرد |
| Settings | BaseSettings + SettingsConfigDict(env_prefix=, env_file=, extra="forbid") |
| اولویت | init > env > .env؛ فایل بعدی برنده > secrets dir > default |
| Dependency تنظیمات | @lru_cache def get_settings()؛ Annotated[Settings, Depends(get_settings)] |
| Layout | کوچک: Layer؛ Domain یا تیم زیاد: Feature + core/ |
| Import | داخل Feature نسبی، میان آنها مطلق؛ وابستگی یکطرفه |
| Mount | app.mount("/static", StaticFiles(...))، app.mount("/legacy", sub_app) |
| Middleware | آخرین اضافهشده بیرونیترین؛ CORS آخر |
| تست | tests/ متناظر با Package؛ conftest هر پوشه؛ --import-mode=importlib |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — فرق app.include_router(router) با app.mount("/x", other_app) چیست؟ حیاتی
پاسخ
پاسخ: include_router عملیات Router را به جدول Route خود برنامه میافزاید؛ Middleware، Exception handler، lifespan، dependencies و سند OpenAPI مشترکاند: "The APIRouters are not 'mounted', they are not isolated from the rest of the application". متد mount برنامهٔ ASGI کاملاً مستقل را زیر یک Path وصل میکند؛ با Routeهای خودش، /x/docs و /x/openapi.json خودش، مقدار root_path و بدون رویداد lifespan. برای Featureهای API از include و برای برنامهٔ جدا و StaticFiles از Mount استفاده کنید؛ Mount و Sub-application.
۲ — ابتدا Router دارای /users/{user_id} و بعد Router دارای /users/me را include میکنید. GET /users/me چه میشود و راهحل چیست؟ حیاتی
پاسخ
پاسخ: پس از include یک جدول مرتب داریم و نخستین تطبیق برنده است. /users/{user_id} زودتر تطبیق مییابد؛ user_id="me" در تبدیل به int شکست میخورد و Client پاسخ اندازهگیریشدهٔ ۴۲۲ با int_parsing میگیرد. Router دارای Path ثابت را اول include کنید یا هر دو را در یک Router با اعلان ثابت پیش از پارامتری قرار دهید. جفت Method و Path تکراری میان Routerها هم بیصداست و اولی برنده میشود؛ ترتیب Route.
۳ — برای همهٔ Routeهای یک Router که اجازهٔ ویرایشش را ندارید، چگونه Token ادمین را اجباری میکنید؟ حیاتی
پاسخ
پاسخ: Dependency را هنگام include بدهید: app.include_router(admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(require_admin)], responses={403: {...}}). فقط در همین برنامه پیش از هر Route آن Router اجرا میشود و فایل قابل استفادهٔ مجدد میماند. پنهانکردن با include_in_schema=False اختیاری است و بهتنهایی هیچ حفاظتی ایجاد نمیکند. ترتیب اجرا app، include، Router، Decorator و سپس Dependency پارامتری است؛ Dependencyهای Router.
۴ — چرا بهجای app = FastAPI() در سطح ماژول از App factory استفاده میکنیم؟ حیاتی
پاسخ
پاسخ: Factory هنگام فراخوانی و با settings دادهشده برنامه میسازد؛ هر تست با create_app(test_settings) برنامهٔ تازه و مستقل میگیرد، import بسته اثر جانبی ندارد و Config متفاوت مثل مستندات خاموش یا CORS روشن با یک آرگومان انتخاب میشود. سرور آن را با uvicorn --factory shop.main:create_app یا asgi.py کوچکی که app = create_app() دارد صدا میزند؛ App factory.
۵ — Engine پایگاه داده و HTTP client را کجا باز میکنید و Route چگونه به آنها میرسد؟ حیاتی
پاسخ
پاسخ: در lifespan؛ تابع دارای @asynccontextmanager که به FastAPI(lifespan=...) داده میشود. پیش از yield بسازید، پس از آن در finally ببندید و روی app.state بگذارید. Route از request.app.state یا بهتر، Dependency کوچک مثل get_db(request) استفاده میکند. Lifespan یک بار در هر Worker process اجرا میشود، در تست فقط داخل with TestClient(app) و برای برنامهٔ Mountشده هرگز؛ با lifespan=، handlerهای on_event صدا زده نمیشوند؛ Lifespan.
۶ — SHOP_APP_NAME در محیط، .env و /run/secrets/shop_app_name مقدار دارد. Settings() کدام را برمیدارد؟ مهم
پاسخ
پاسخ: متغیر محیطی. ترتیب pydantic-settings از بالاترین اولویت: آرگومان سازنده، متغیر محیطی، فایل dotenv که فایل بعدی روی قبلی غالب است، Secrets directory و سپس پیشفرض فیلد. پس .env ابزار محلی است که متغیر واقعی استقرار روی آن غلبه میکند؛ فایل Secret منبع جایگزین برای اسرار است. تست مثال با نام test_priority_env_over_dotenv_over_secrets هر مرحله را بررسی میکند؛ منابع settings.
۷ — چرا get_settings() را با @lru_cache میپوشانیم و اثرش روی تست چیست؟ مهم
پاسخ
پاسخ: بدون آن، هر درخواست وابسته به settings یک Settings تازه میسازد و محیط و .env را دوباره میخواند. با آن، settings یک بار در هر Process ساخته میشود و شبیه متغیر سراسری قابل جایگزینی است: تست از app.dependency_overrides[get_settings] استفاده میکند یا Settings را به Factory میدهد. بین تستها get_settings.cache_clear() صدا بزنید، چون تغییر متغیر محیطی برای شیء Cacheشده نامرئی است؛ Dependency تنظیمات.
۸ — Layout مبتنی بر Layer یا Feature؛ هر کدام را چه وقت انتخاب میکنید؟ مهم
پاسخ
پاسخ: Layer فنی با routers/ schemas/ models/ services/ repositories/ برای سرویس کوچک و یک تیم مناسب است؛ آشناست و با آموزش و قالب full-stack تطبیق دارد. با Domainهای زیاد یا چند تیم، Feature مثل catalog/ و orders/ را انتخاب کنید؛ هر کدام Vertical slice و کنارشان core/. تغییر در یک پوشه میماند، مالکیت روشن و مرز قابل اعمال است و Feature بعداً میتواند سرویس شود. وقتی پوشههای Layer شلوغ شدند و بیشتر تغییرها سه یا بیش از سه پوشه را درگیر کردند، جابهجا شوید؛ انتخاب.
۹ — متدهای SDK نامهایی مثل getProductApiV1ProductsProductIdGet دارند. چگونه بدون ازبینبردن یکتایی اصلاحشان میکنید؟ مهم
پاسخ
پاسخ: به FastAPI یک generate_unique_id_function بدهید که شناسه را از tag اول و نام تابع بسازد: f"{route.tags[0]}-{route.name}". همهٔ Routeها tag داشته باشند و نسخهٔ دوم tag خودش، مثل catalog-v2، را بگیرد تا get_product در v1 و v2 یکتا بماند. FastAPI با تداخل فقط هشدار UserWarning: Duplicate Operation ID ... میدهد؛ پس تست یکتایی همهٔ operationIdها را نگه دارید؛ operationId.
۱۰ — orders/service.py از catalog/service.py و catalog/service.py از orders/service.py import میکند. چه چیزی میشکند و راهحل چیست؟ مهم
پاسخ
پاسخ: Import هر کدام هنگام Startup با ImportError: cannot import name ... from partially initialized module ... (most likely due to a circular import) شکست میخورد؛ ماژول اول پیش از ساختهشدن نامهایش در sys.modules ثبت شده است. طراحی را اصلاح کنید، نه نشانه را: وابستگی یکطرفه باشد، یعنی orders → سرویس عمومی catalog؛ کد مشترک به core/ برود؛ یا جهت فراخوانی برعکس شود، catalog داده منتشر کند و orders مصرف کند. داخل Feature از Relative import و میان Featureها از Absolute import استفاده کنید؛ Import و چرخهها.
۱۱ — پس از app.include_router(router)، تابع @router.get("/late") را تعریف میکنید. چرا /late در FastAPI 0.128.8 پاسخ ۴۰۴ و در 0.140 پاسخ ۲۰۰ میدهد؟ تکمیلی
پاسخ
پاسخ: تا 0.136، include_router هر Route موجود را با حلقهای از self.add_api_route(prefix + route.path, ...) در والد کپی میکرد؛ افزودن بعدی به برنامه نمیرسید. نسخهٔ 0.137.0 در ۲۰۲۶-۰۶-۱۴، Routing را "to preserve APIRouter and APIRoute instances" بازآرایی کرد؛ Router ذخیره میشود، کپی نمیشود، Route بعدی دیده میشود و router.routes درخت میشود. کدی که باید روی هر دو کار کند، درخت Router را از پایین به بالا میسازد؛ سازوکارها.
۱۲ — تستهای Package مبتنی بر Feature چگونه چیده میشوند و Fixture کجا قرار میگیرد؟ تکمیلی
پاسخ
پاسخ: شکل Package را تکرار کنید: tests/shop/catalog/، tests/shop/orders/ و tests/shop/core/ با --import-mode=importlib تا فایلهای پوشههای متفاوت بتوانند همنام باشند. هر Fixture در conftest.py پایینترین پوشهٔ نیازمند آن باشد؛ pytest حوزهٔ Fixtureهای conftest را بر اساس پوشه تعیین میکند. پاکسازی محیط و settings در tests/conftest.py، برنامه و Client در tests/shop/conftest.py. برای هر تست برنامهٔ تازه از Factory بسازید و Service را بدون HTTP تست کنید؛ تست متناظر با Package.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
APIRouter | کلاس FastAPI برای گروهبندی Path operation با prefix، tags، dependencies و responses مشترک؛ «FastAPI کوچک» |
include_router | متد افزودن Routeهای Router به برنامه یا Router دیگر، همراه ترکیب prefix، tags، dependencies و responses |
| Router تودرتو (Nested routers) | Router داخل Router؛ api → v1 → catalog |
prefix | بخش Path که در ابتدای همهٔ Routeهای Router یا فراخوانی include میآید |
tags | برچسب گروهبندی OpenAPI؛ بخش مستندات و کلاس Service در SDK |
| وابستگی Router (Router dependencies) | dependencies=[...] روی Router یا include؛ پیش از هر Route اجرا میشود |
| پاسخ Router (Router responses) | responses={...} مستندشده برای همهٔ Routeهای Router |
default_response_class | کلاس پاسخ Routeهایی که خودشان کلاس تعیین نکردهاند |
include_in_schema | پرچم حذف Route، Router یا include از OpenAPI؛ نه از Routing |
| ترتیب Route (Route order) | نخستین Route ثبتشدهٔ منطبق، درخواست را پردازش میکند |
| تداخل Path (Path conflict) | دو Route برای Method و Path یکسان؛ اولی بیصدا برنده است |
| operationId | شناسهٔ یکتای عملیات در OpenAPI؛ مبنای نام متد SDK |
generate_unique_id_function | تابع قابل فراخوانی APIRoute -> str برای ساخت operationId |
openapi_tags / فرادادهٔ tags (Tags metadata) | فهرست dictهای tag با name، description و externalDocs، دادهشده به FastAPI |
| کارخانهٔ برنامه (App factory) | تابع create_app که برنامهٔ پیکربندیشده میسازد و برمیگرداند |
| نقطهٔ ورود (Entry point) | Import string سرور یا CLI؛ shop.asgi:app و [tool.fastapi] entrypoint |
--factory | پرچم Uvicorn برای فراخوانی تابع نامبرده و گرفتن برنامه |
| چرخهٔ عمر (Lifespan) | Async context manager پیرامون عمر برنامه؛ Startup پیش از yield و Shutdown پس از آن |
asynccontextmanager | Decorator در contextlib که Async generator با یک yield را به Async context manager تبدیل میکند |
| راهاندازی / خاموشی (Startup / shutdown) | دو رویداد ASGI Lifespan Protocol |
app.state | محل صفتهای نمونهٔ برنامه برای منابع مشترک در سطح Process |
request.app | برنامهٔ پردازشکنندهٔ درخواست؛ request.app.state منابعش را در دسترس میگذارد |
| وضعیت lifespan (Lifespan state) | dict حاصل از yield؛ کپی سطحی آن به شکل request.state ظاهر میشود |
| lifespan مربوط به Router (Router lifespan) | APIRouter(lifespan=...) داخل lifespan برنامهٔ includeکننده؛ 0.112.2+ |
on_event | hook منسوخ Startup/Shutdown؛ با تنظیم lifespan= نادیده گرفته میشود |
| pydantic-settings | Package فراهمکنندهٔ BaseSettings؛ از v2 جدا از Pydantic |
BaseSettings | مدل Pydantic پرشده از آرگومان سازنده، متغیر محیطی، dotenv، فایل Secret و پیشفرض |
SettingsConfigDict | dict نوعدار برای model_config کلاس settings |
env_prefix | prefix نام متغیر محیطی؛ SHOP_ |
env_file | فایل یا فایلهای dotenv برای خواندن، نسبت به پوشهٔ کاری |
secrets_dir | پوشهٔ یک فایل برای هر مقدار؛ نام فایل برابر نام متغیر |
SecretStr | نوع Pydantic که مقدارش را در repr و Log پنهان میکند |
extra="forbid" | پیشفرض settings؛ کلید ناشناختهٔ dotenv خطای Validation است |
lru_cache | Decorator در functools برای Cache نتیجه؛ اجرای یکبارهٔ get_settings() |
| Dependency تنظیمات (Settings dependency) | Depends(get_settings)؛ قابل Override در تست |
| پیکربندی هر محیط (Per-environment config) | مقدار متفاوت هر محیط، از متغیر محیطی یا .env.<env> |
| پیکربندی دوازدهعاملی (Twelve-factor config) | "Store config in the environment"؛ عامل III |
| بر اساس Layer فنی (By technical layer) | یک پوشه برای هر Layer؛ routers، schemas، models، services، repositories |
| بر اساس قابلیت (By feature) | یک پوشه برای هر قابلیت کسبوکار؛ Vertical slice |
| برش عمودی (Vertical slice) | پوشهٔ Feature شامل همهٔ Layerهای خودش |
| مرز ماژول (Module boundary) | قاعدهٔ مجازبودن import میان ماژولها؛ فقط رابط عمومی |
| Router بهعنوان Layer | سازگارکنندهٔ HTTP؛ ورودی درخواست، خروجی کد وضعیت |
| سرویس (Service) | قواعد و خطاهای Domain، بدون HTTP |
| Repository | دسترسی SQL، بدون قاعدهٔ کسبوکار |
| طرحواره در برابر مدل (Schema vs model) | شکل API در Pydantic در برابر شکل Persistence در ORM |
__init__.py | فایل تبدیل پوشه به Regular package؛ هنگام import اجرا میشود |
| بستهٔ فضای نام (Namespace package) | Package بدون __init__.py؛ PEP 420 |
| واردکردن نسبی (Relative import) | from .x import y / from ..x import y؛ PEP 328 |
| واردکردن دوری (Circular import) | دو ماژول از هم import میکنند؛ شکست روی ماژول نیمهمقداردهیشده |
| src layout | Package قابل import زیر src/؛ نیازمند نصب برای import |
| چیدمان تخت (Flat layout) | Package قابل import کنار pyproject.toml |
app.mount | Mount کردن برنامهٔ مستقل ASGI یا StaticFiles زیر یک Path |
| زیربرنامه (Sub-application) | برنامهٔ جداگانهٔ FastAPI که در دیگری Mount شده؛ مستندات خودش، بدون lifespan |
StaticFiles | برنامهٔ ASGI در Starlette برای سرویس فایل یک پوشه |
root_path | مقدار ASGI Scope که prefix بیرونی را به برنامهٔ Mountشده یا پشت Proxy میگوید |
| ترتیب میانافزار (Middleware order) | آخرین اضافهشده بیرونیترین؛ برای هر درخواست پیش از Routing اجرا میشود |
| conftest.py | فایل pytest که Fixtureهایش برای پوشهٔ خود و زیرپوشهها قابل استفادهاند |
--import-mode=importlib | Mode مربوط به import در pytest برای فایل تست همنام در پوشههای متفاوت |
| FastAPI / Starlette / Pydantic | Framework، ابزار ASGI که از آن ارث میبرد، کتابخانهٔ Validation |
| Uvicorn / httpx / pytest | سرور ASGI، HTTP client که پشت TestClient هم هست، اجراکنندهٔ تست |
| SQLAlchemy / SQLModel / Alembic | ORM، Layer مربوط به ORM با سبک Pydantic، ابزار مهاجرت فصلهای بعد |
eval-type-backport | Package برای ارزیابی X | None توسط Pydantic روی Python 3.9 |
منابع (References)
- FastAPI, "Bigger Applications - Multiple Files": https://fastapi.tiangolo.com/tutorial/bigger-applications/
- FastAPI, "Metadata and Docs URLs" (
openapi_tags): https://fastapi.tiangolo.com/tutorial/metadata/ - FastAPI, "Static Files": https://fastapi.tiangolo.com/tutorial/static-files/
- FastAPI, "Middleware": https://fastapi.tiangolo.com/tutorial/middleware/
- FastAPI, "Global Dependencies": https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Settings and Environment Variables": https://fastapi.tiangolo.com/advanced/settings/
- FastAPI, "Sub Applications - Mounts": https://fastapi.tiangolo.com/advanced/sub-applications/
- FastAPI, "Behind a Proxy" (
root_path): https://fastapi.tiangolo.com/advanced/behind-a-proxy/ - FastAPI, "Path Operation Advanced Configuration" (
operationId,include_in_schema): https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/ - FastAPI, "Generating SDKs" (
generate_unique_id_function): https://fastapi.tiangolo.com/advanced/generate-clients/ - FastAPI, "Additional Responses in OpenAPI": https://fastapi.tiangolo.com/advanced/additional-responses/
- FastAPI, "Custom Response" (
default_response_class): https://fastapi.tiangolo.com/advanced/custom-response/ - FastAPI, "Testing Dependencies with Overrides": https://fastapi.tiangolo.com/advanced/testing-dependencies/
- FastAPI, "Testing Events: lifespan and startup - shutdown": https://fastapi.tiangolo.com/advanced/testing-events/
- FastAPI reference,
APIRouter: https://fastapi.tiangolo.com/reference/apirouter/ - FastAPI reference,
FastAPI(mount,state,frontend): https://fastapi.tiangolo.com/reference/fastapi/ - FastAPI reference,
Request: https://fastapi.tiangolo.com/reference/request/ - FastAPI release notes: https://fastapi.tiangolo.com/release-notes/
- FastAPI 0.128.8 source,
fastapi/routing.py: https://raw.githubusercontent.com/fastapi/fastapi/0.128.8/fastapi/routing.py - FastAPI 0.128.8 source,
fastapi/utils.py(generate_unique_id): https://raw.githubusercontent.com/fastapi/fastapi/0.128.8/fastapi/utils.py - FastAPI 0.128.8 source,
fastapi/openapi/utils.py(duplicate operationId warning): https://raw.githubusercontent.com/fastapi/fastapi/0.128.8/fastapi/openapi/utils.py - Full Stack FastAPI Template,
backend/app/main.py: https://raw.githubusercontent.com/fastapi/full-stack-fastapi-template/master/backend/app/main.py - Full Stack FastAPI Template,
backend/app/api/main.py: https://raw.githubusercontent.com/fastapi/full-stack-fastapi-template/master/backend/app/api/main.py - Full Stack FastAPI Template,
backend/app/core/config.py: https://raw.githubusercontent.com/fastapi/full-stack-fastapi-template/master/backend/app/core/config.py - FastAPI Best Practices (project structure): https://github.com/zhanymkanov/fastapi-best-practices
- Pydantic Settings documentation: https://docs.pydantic.dev/latest/concepts/pydantic_settings/
- pydantic-settings on PyPI (versions,
requires_python): https://pypi.org/pypi/pydantic-settings/json - Starlette, Applications (
app.state): https://starlette.dev/applications/ - Starlette, Routing (
Mount, route priority): https://starlette.dev/routing/ - Starlette, Lifespan (lifespan state): https://starlette.dev/lifespan/
- Starlette, Middleware: https://starlette.dev/middleware/
- Python tutorial, Modules (packages, relative imports): https://docs.python.org/3/tutorial/modules.html
- Python language reference, The import system: https://docs.python.org/3/reference/import.html
- Python,
functools.lru_cache: https://docs.python.org/3/library/functools.html - Python,
contextlib.asynccontextmanager: https://docs.python.org/3/library/contextlib.html - PEP 328, Imports: Multi-Line and Absolute/Relative: https://peps.python.org/pep-0328/
- PEP 420, Implicit Namespace Packages: https://peps.python.org/pep-0420/
- Python Packaging User Guide, src layout vs flat layout: https://packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout/
- pytest, Good Integration Practices (test layout, import modes): https://docs.pytest.org/en/stable/explanation/goodpractices.html
- pytest, Fixtures reference (
conftest.py): https://docs.pytest.org/en/stable/reference/fixtures.html - The Twelve-Factor App, III. Config: https://12factor.net/config
- SQLAlchemy 2.0, Asynchronous I/O (
create_async_engine,engine.dispose()): https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html - redis-py, Asyncio examples (
redis.asyncio,aclose()): https://redis.readthedocs.io/en/stable/examples/asyncio_examples.html - Import Linter documentation (contract types): https://import-linter.readthedocs.io/en/stable/
- Ruff rule
banned-api(TID251): https://docs.astral.sh/ruff/rules/banned-api/ - Laravel 13, Routing: https://laravel.com/docs/13.x/routing
- Laravel 13, Controllers: https://laravel.com/docs/13.x/controllers
- Laravel 13, Service Providers: https://laravel.com/docs/13.x/providers
- Laravel 13, Directory Structure: https://laravel.com/docs/13.x/structure
- Laravel 13, Configuration: https://laravel.com/docs/13.x/configuration
- Go, Organizing a Go module: https://go.dev/doc/modules/layout