FastAPI Best Architecture

repository·master·Indexed 25 days ago

https://github.com/fastapi-practices/fastapi-best-architecture

An enterprise-level backend architecture solution for FastAPI providing a structured three-tier directory pattern for scalable Python web applications. It includes support for Alembic migrations, Celery background and scheduled tasks, and a variety of plugins for code generation, dynamic system parameters (Config), data dictionaries (Dict), SMTP email services, system announcements (Notice), and OAuth2 third-party authentication (GitHub, Google).

Tokens
8.1K
Snippets
18
Records
56
Agent score
81%

What's inside fastapi-best-architecture

  1. Understand the Three-tier architecture in FastAPI Best Architecture

    master

    FastAPI Best Architecture follows a three-tier architecture pattern designed for enterprise-level backends. While it differs from traditional MVC or Java-based structures, it maps specific responsibilities to a clear directory structure. Use this mapping to understand where to place your code:

    • api: Corresponds to the view/controller layer. This is where your FastAPI routes and endpoint definitions reside.
    • schema: Corresponds to the DTO (Data Transfer Object) layer. Use this for Pydantic models that define the shape of data transmitted via the API.
    • service: Corresponds to the business logic layer. This is where your core application logic and rules are implemented.
    • crud: Corresponds to the DAO (Data Access Object) / Mapper layer. This layer handles direct database operations.
    • model: Corresponds to the model / entity layer. This contains your database models (e.g., SQLAlchemy models).
    | workflow       | java           | fastapi_best_architecture |
    |----------------|----------------|---------------------------|
    | view           | controller     | api                       |
    | data transmit  | dto            | schema                    |
    | business logic | service + impl | service                   |
    | data access    | dao / mapper   | crud                      |
    | model          | model / entity | model                     |
  2. Use the Config plugin for dynamic system parameters

    master

    The Config plugin is an extension-level plugin targeting the admin module. It is designed to dynamically maintain system parameters and provide configuration data required for frontend application display.

    Key Capabilities

    • System Parameter Management: Maintain and update system-level dynamic parameters.
    • Frontend Configuration: Serve data required for frontend engineering displays.

    How to use

    1. Install and enable the plugin.
    2. Restart the backend service.
    3. Manage configuration data via the system administration backend pages or through the Swagger UI documentation.

    Uninstallation

    • No additional environment variable cleanup or plugin configuration cleanup is required after uninstalling.
    • Warning: If your business logic or frontend pages depend on the configuration capabilities provided by this plugin, ensure you clean up those integrations before uninstalling.
  3. Uninstall the OAuth2 plugin

    master

    When removing the OAuth2 plugin, perform the following cleanup to avoid configuration errors:

    1. Remove Configuration: Delete the relevant environment variables from .env, the settings from plugin.toml, and the type definitions from backend/core/conf.py.
    2. Clean Frontend: Remove any UI components or logic integrated into the login pages or user profile centers that rely on third-party login or account binding.
  4. How to use the Dict plugin

    master

    To implement dictionary management using this plugin, follow these steps:

    1. Installation: Install and enable the plugin, then restart the backend service.
    2. Data Setup: Maintain (create) the dictionary types first, then maintain the corresponding dictionary data.
    3. Frontend Integration: Use the stable dictionary codes (dictionary encodings) to maintain the mapping for frontend enums and selection options.
  5. Configure a new application with Alembic

    master
    This project uses Alembic for database migrations with a generic single-database configuration using an asynchronous DBAPI. When adding a new application to the framework, you must review and configure the env.py file within the alembic/ directory to ensure the migration environment correctly recognizes your application's models and database connection settings.
  6. Use the Notice plugin for system announcements

    master

    The Notice plugin is an extension-level plugin designed for the admin target. It allows you to manage and publish internal system notifications and announcements, making it suitable for backend announcements and in-app notifications.

    Installation and Setup

    1. Install and enable the plugin.
    2. Restart the backend service to apply changes.

    Managing Content

    Once the service is running, you can maintain and manage notification and announcement content via:

    • The administrative backend pages.
    • The Swagger API documentation.

    Uninstallation

    • No additional cleanup of environment variables or plugin configurations is required after uninstalling.
    • Warning: If your frontend pages or business logic depend on the notice capabilities, ensure you clean up those integrations simultaneously during uninstallation.
  7. Build and run the backend using Docker

    master

    To build and run the FastAPI backend as a containerized service, follow these steps from the project root:

    1. Build the image: Use the provided Dockerfile to create an image tagged fba_backend_independent.
    2. Configure networking: If you are using native boot (running outside Docker) or need the container to communicate with services on your host machine, you must change the host address in your .env file from 127.0.0.1 to host.docker.internal.
    3. Run the container: Start the container in detached mode, mapping port 8000 of the container to port 8000 on your host.
  8. Configure the code_generator plugin

    master

    The code_generator plugin is an application-level plugin used to generate general business code. To configure it, you must update two files:

    1. plugin.toml: Add the configuration under the [settings] section in the plugin directory.
    2. backend/core/conf.py: Add the corresponding type hint to the configuration class to ensure the backend recognizes the setting.

    Warning: Generated code is written directly to the disk. This plugin should only be used in development environments.

    # In plugin/plugin.toml
    [settings]
    CODE_GENERATOR_DOWNLOAD_ZIP_FILENAME = 'fba_generator'
    # In backend/core/conf.py
    ##################################################
    # [ Plugin ] code_generator
    ##################################################
    CODE_GENERATOR_DOWNLOAD_ZIP_FILENAME: str
  9. Use the OAuth2 plugin for third-party login

    master

    To implement third-party login and account binding using the OAuth2 plugin, follow these steps:

    1. Create OAuth Apps: Register your application on the GitHub and Google developer platforms.
    2. Set Credentials: Add the provided Client ID and Client Secret from the platforms to your project's .env file.
    3. Match Redirect URIs: Ensure the callback URLs configured in the GitHub/Google developer consoles exactly match the values set in OAUTH2_GITHUB_REDIRECT_URI and OAUTH2_GOOGLE_REDIRECT_URI.
    4. Configure Frontend Redirects: Set OAUTH2_FRONTEND_LOGIN_REDIRECT_URI (for login flows) and OAUTH2_FRONTEND_BINDING_REDIRECT_URI (for account binding flows) to your frontend application's routes.
    5. Restart: Restart the backend service to apply changes.