/FastAPI-HTMX

FastAPI, HTMX and Alpine JS | BoilerPlate Implementation

Primary LanguageHTML

FastAPI HTMX

Web App providing boilerplate implementation for user management, roles, groups, and CRUD operations using HTMX, FastAPI and AlpineJS for rapid prototyping and without worrying for the user management.

External Libraries Used

This project leverages several external libraries to provide a robust and efficient solution. Below is a brief description of each library along with a link to their documentation:

  • FastAPI (v0.112.1): A modern, fast (high-performance), web framework for building APIs and serving HTML templates with Python 3.6+ based on standard Python type hints.
  • SQLAlchemy (v2.0.36): The Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
  • FastAPI Users (v13.0.0): Ready-to-use and customizable users management for FastAPI.
  • Uvicorn (v0.23.2): A lightning-fast ASGI server implementation, using uvloop and httptools.
  • Jinja2 (v3.1.4): A modern and designer-friendly templating language for Python.
  • NH3 (v0.2.18): A Python binding to the HTML sanitizer h3.
  • Alembic (v1.14.0): A lightweight database migration tool for usage with the SQLAlchemy Database Toolkit.
  • AlpineJS (loaded from CDN): A rugged, minimal framework for composing JavaScript behavior in your HTML templates.
  • Flowbite (loaded from CDN): A component library built on top of Tailwind CSS for building modern web interfaces.
  • Pydantic (v2.10.0): Data validation and settings management using Python type annotations.

Features Implemented

  • User Authentication and Authorization
  • Role Management
  • Group Management
  • Dashboard for managing users, roles, and groups
  • RESTful API endpoints for CRUD operations
  • HTML templates for the web interface
  • Database migrations with Alembic
  • Unified error handling approach.

To-Do (Future Enhancements)

  • ๐ŸŽจ Implement Theming using Flowbite and Tailwind
  • ๐Ÿšฆ Implement a rate limiter to prevent abuse and ensure fair usage
  • โœ… ๐Ÿ“ฆ Integrate MinIO object storage for efficient file saving and management [Completed]
  • ๐Ÿ”‘ Add functionality to allow users to update their passwords
  • ๐Ÿ”„ Implement a password reset feature on the login page
  • โšก Implement rendering of blocks using FastAPI Fragment instead of reloading complete page or partials [In Progress]
  • ๐Ÿ“ Develop a logging service to track and analyze user activity
  • โœ… ๐Ÿ›ก๏ธ Implement CSRF protection to enhance security [Completed]
  • ๐Ÿ’พ Integrate Neon database (SQLite) for production use [In Progress]
  • โœ… ๐ŸŽจ Replace HyperScript code with Alpine JS [Completed]
  • ๐Ÿš€ Upgrading the boilerplate code to work with Python 12 and HTMX 2 [In Progress]
  • โœ… ๐Ÿ“ฑ Fixing the GUI issues appearing in mobile view [Completed]
  • ๐Ÿงช Add more tests
  • ๐Ÿ”ง Wrapper to handle the pydantic models inputs efficiently from front end

Demo

Admin Login Credential

Setting Up the Project

Creating the .env File

Create a .env file in the root directory of the project and add the following environment variables:

# Database Configuration
DATABASE_URL="sqlite+aiosqlite:///./users.db"
SECRET_KEY="super-secret-key-example-123456789"

# MinIO Configuration (Required for file uploads)
MINIO_URL="http://localhost:9000"
MINIO_ACCESS_KEY="minioadmin123456789"
MINIO_SECRET_KEY="miniosecret987654321xyz"
MINIO_BUCKET="my-fastapi-bucket"
MINIO_SECURE=false

# CSRF Protection
CSRF_SECRET_KEY="csrf-secret-key-example-987654321"
COOKIE_SAMESITE="lax"
COOKIE_SECURE=true

Replace your_secret_key with a strong secret key for your application.

Note: While using sample MinIO credentials will allow the database to record file uploads, the actual files won't be stored without valid MinIO server credentials. For full file storage functionality, set up a MinIO server or use valid MinIO service credentials.

Running the Project

  1. Clone the repository:

    git clone https://github.com/yourusername/project-management.git
    cd project-management
  2. Install dependencies: If you are using poetry, run:

    poetry install

    If you are using pip, run:

    pip install -r requirements.txt
  3. Run database migrations:

    alembic upgrade head
  4. Run database migrations:

    alembic revision --autogenerate -m "Initial migration"
  5. Insert Required import in Migration File:

    After generating the initial migration, open the newly created revision file in app/migrations/versions/ and add the following imports at the top of the file:

    import fastapi_users_db_sqlalchemy.generics
    import app.models.groups
    
  6. Apply the changes:

    alembic upgrade head
  7. Start the application: If you are using poetry, run:

    poetry run uvicorn main:app --reload

    If you are using uvicorn directly, run:

    uvicorn main:app --reload
  8. Access the application: Open your web browser and navigate to http://127.0.0.1:8000.

Updating Model References in init_models

When you define a new Database model in your application, it's essential to update the init_models function to ensure that Alembic can detect and generate migrations for this new model correctly. This step is crucial for maintaining the integrity of your database schema and ensuring that all models are correctly versioned.

Steps to Update init_models

  1. Locate init_models Function: Open the base.py file in app/database/base.py. This file contains the init_models function, which is responsible for importing all the models in your application.

  2. Add New Model Import: Once you have defined a new model in your application, you need to import it in the init_models function. Ensure that you follow the existing import structure. For example, if your new model is Invoice and it's located in the models.financial module, you would add the following line:

    from ..models.financial import Invoice  # noqa: F401

    The # noqa: F401 comment at the end of the import statement tells the linter to ignore the "imported but unused" warning, as the import is necessary for Alembic to detect and generate migrations for the model.

  3. Follow Import Conventions: If you have multiple models in the same module, you can import them in a single line to keep the init_models function organized. For example:

    from ..models.financial import Invoice, Payment, Transaction  # noqa: F401
  4. Save Changes: After adding the import statement for your new model, save the changes to the base.py file.

  5. Generate Alembic Migration: With the new model imported in the init_models function, you can now generate an Alembic migration script that includes this model. Run the Alembic command to autogenerate a migration:

    alembic revision --autogenerate -m "Added new model Invoice"
  6. Review and Apply Migration: Always review the generated migration script to ensure it accurately represents the changes to your models. After reviewing, apply the migration to update your database schema:

    alembic upgrade head

Project Structure

Below is an overview of the project structure for application. This structure is designed to organize the application's components logically, making it easier to navigate and maintain.

FastAPI-HTMX/
โ”œโ”€โ”€ app/
โ”‚ โ”œโ”€โ”€ core/             # Core application logic and utilities
โ”‚ โ”‚ โ”œโ”€โ”€ config.py         # Application configuration
โ”‚ โ”‚ โ””โ”€โ”€ security.py       # Security utilities
โ”‚ โ”œโ”€โ”€ database/         # Database configurations and connections
โ”‚ โ”‚ โ”œโ”€โ”€ base.py           # Base database setup
โ”‚ โ”‚ โ””โ”€โ”€ session.py        # Database session management
โ”‚ โ”œโ”€โ”€ migrations/         # Alembic migration scripts
โ”‚ โ”œโ”€โ”€ models/           # SQLAlchemy ORM models
โ”‚ โ”‚ โ”œโ”€โ”€ groups.py         # Group model definitions
โ”‚ โ”‚ โ”œโ”€โ”€ roles.py          # Role model definitions
โ”‚ โ”‚ โ””โ”€โ”€ users.py          # User model definitions
โ”‚ โ”œโ”€โ”€ routes/           # API route definitions
โ”‚ โ”‚ โ”œโ”€โ”€ api/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ auth.py         # Authentication endpoints
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ users.py        # User management endpoints
โ”‚ โ”‚ โ””โ”€โ”€ view/           # View routes for web interface
โ”‚ โ”‚   โ”œโ”€โ”€ group.py        # Group management views
โ”‚ โ”‚   โ”œโ”€โ”€ role.py         # Role management views
โ”‚ โ”‚   โ””โ”€โ”€ view_crud.py    # SQLAlchemyCRUD class
โ”‚ โ”œโ”€โ”€ schema/           # Pydantic schemas
โ”‚ โ”‚ โ”œโ”€โ”€ group.py          # Group schemas
โ”‚ โ”‚ โ”œโ”€โ”€ role.py           # Role schemas
โ”‚ โ”‚ โ””โ”€โ”€ user.py           # User schemas
โ”‚ โ”œโ”€โ”€ static/           # Static files
โ”‚ โ”‚ โ”œโ”€โ”€ css/              # Stylesheets
โ”‚ โ”‚ โ”œโ”€โ”€ js/               # JavaScript files
โ”‚ โ”‚ โ””โ”€โ”€ img/              # Images and assets
โ”‚ โ””โ”€โ”€ templates/        # Jinja2 HTML templates
โ”‚   โ”œโ”€โ”€ auth/             # Authentication templates
โ”‚   โ”œโ”€โ”€ components/       # Reusable components
โ”‚   โ””โ”€โ”€ partials/         # Partial templates
โ”œโ”€โ”€ tests/              # Unit and integration tests
โ”œโ”€โ”€ .env                # Environment variables
โ”œโ”€โ”€ alembic.ini         # Alembic configuration
โ”œโ”€โ”€ main.py             # Application entry point
โ”œโ”€โ”€ poetry.lock         # Poetry dependencies lock
โ”œโ”€โ”€ pyproject.toml      # Project configuration
โ””โ”€โ”€ README.md           # Project documentation

ER Diagram

Here's the Entity-Relationship (ER) diagram for database:

ER Diagram

Contributing

Contributions are welcome! Please open an issue or submit a pull request for any changes.

License

This project is licensed under the MIT License. See the LICENSE file for details.