{"id":17919234,"url":"https://github.com/fastestmolasses/fastest-fastapi","last_synced_at":"2025-03-24T00:31:23.160Z","repository":{"id":188420096,"uuid":"678710684","full_name":"FastestMolasses/Fastest-FastAPI","owner":"FastestMolasses","description":"A complete, production ready Python3.11+ web server template focused on speed and safety","archived":false,"fork":false,"pushed_at":"2024-08-06T07:08:18.000Z","size":696,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-15T07:05:14.109Z","etag":null,"topics":["fastapi","fastapi-template","python","python311"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/FastestMolasses.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-08-15T07:28:26.000Z","updated_at":"2024-08-06T07:08:21.000Z","dependencies_parsed_at":"2023-08-15T08:51:29.666Z","dependency_job_id":"c38008e0-acbc-4459-be3e-bd9d5e763829","html_url":"https://github.com/FastestMolasses/Fastest-FastAPI","commit_stats":null,"previous_names":["fastestmolasses/fast-python-server-template"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FastestMolasses%2FFastest-FastAPI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FastestMolasses%2FFastest-FastAPI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FastestMolasses%2FFastest-FastAPI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FastestMolasses%2FFastest-FastAPI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FastestMolasses","download_url":"https://codeload.github.com/FastestMolasses/Fastest-FastAPI/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245191062,"owners_count":20575244,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastapi","fastapi-template","python","python311"],"created_at":"2024-10-28T20:15:35.874Z","updated_at":"2025-03-24T00:31:22.835Z","avatar_url":"https://github.com/FastestMolasses.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003ch1 align=\"center\"\u003e⚡️ Fastest FastAPI\u003c/h1\u003e\n\n  \u003cdiv align=\"center\"\u003e\n\n![Build](https://github.com/FastestMolasses/Fast-Python-Server-Template/actions/workflows/main.yaml/badge.svg)\u0026nbsp;[![GitHub license](https://badgen.net/github/license/FastestMolasses/Fast-Python-Server-Template)](https://github.com/FastestMolasses/Fast-Python-Server-Template/blob/main/LICENSE)\n\n  \u003c/div\u003e\n\n  \u003cp align=\"center\"\u003e\n    A production-ready FastAPI server template, emphasizing performance and type safety. It includes a configurable set of features and options, allowing customization to retain or exclude components.\n    \u003cbr /\u003e\n    \u003cbr /\u003e\n    Built with FastAPI, Pydantic, Ruff, and MyPy.\n    \u003cbr /\u003e\n    \u003ca href=\"https://github.com/FastestMolasses/Fast-Python-Server-Template/issues\"\u003eReport Bug\u003c/a\u003e\n    ·\n    \u003ca href=\"https://github.com/FastestMolasses/Fast-Python-Server-Template/issues\"\u003eRequest Feature\u003c/a\u003e\n  \u003c/p\u003e\n\u003c/p\u003e\n\n## Features\n\n-   ⚡ Async and type safety by default\n-   🛠️ CI/CD and tooling setup\n-   🚀 High performance libraries integrated ([orjson](https://github.com/ijl/orjson), [uvloop](https://github.com/MagicStack/uvloop), [pydantic2](https://github.com/pydantic/pydantic))\n-   📝 [Loguru](https://github.com/Delgan/loguru) + [picologging](https://github.com/microsoft/picologging) for simplified and performant logging\n-   🐳 Dockerized and includes AWS deployment flow\n-   🗃️ Several database implementations with sample ORM models (MySQL, Postgres, Timescale) \u0026 migrations\n-   🔐 Optional JWT authentication and authorization\n-   🌐 AWS Lambda functions support\n-   🧩 Modularized features\n-   📊 Prometheus metrics\n-   📜 Makefile commands\n-   🗺️ Route profiling\n\n## Table of Contents\n\n-   [Requirements](#requirements)\n-   [Installation](#installation)\n-   [Environment Specific Configuration](#environment-specific-configuration)\n-   [Upgrading Dependencies](#upgrading-dependencies)\n-   [Databases](#databases)\n    -   [Shell](#shell)\n    -   [Migrations](#migrations)\n    -   [Downgrade Migration](#downgrade-migration)\n-   [JWT Auth](#jwt-auth)\n    -   [JWT Overview](#jwt-overview)\n    -   [Modifying JWT Payload Fields](#modifying-jwt-payload-fields)\n-   [Project Structure](#project-structure)\n-   [Makefile Commands](#makefile-commands)\n-   [Contributing](#contributing)\n\n## Requirements\n\n-   [Python 3.11+](https://www.python.org/downloads/)\n-   [Docker](https://www.docker.com/get-started/)\n\n## Installation\n\n1. Fork this repo ([How to create a private fork](https://gist.github.com/0xjac/85097472043b697ab57ba1b1c7530274))\n\n2. Install UV Package Manager:\n   Follow the installation instructions at https://github.com/astral-sh/uv\n\n3. Set up the virtual environment and install dependencies:\n\n    ```bash\n    uv venv\n\n    # On macOS and Linux\n    source .venv/bin/activate\n\n    # On Windows\n    .venv\\Scripts\\activate\n\n    # Install main dependencies\n    uv pip install -r requirements.txt\n\n    # Install development dependencies (optional)\n    uv pip install -r dev-requirements.txt\n    ```\n\n4. Install [Docker](https://www.docker.com/get-started/)\n\n5. Start your Docker services:\n\n    ```bash\n    docker compose up\n    ```\n\n6. Clone `.env.example` to `.env` and update the values:\n\n    ```bash\n    # macOS and Linux\n    cp .env.example .env\n\n    # Windows (PowerShell)\n    Copy-Item .env.example .env\n    ```\n\n    You can use this command to generate secret keys:\n\n    ```bash\n    # macOS and Linux\n    openssl rand -hex 128\n\n    # Windows (PowerShell)\n    $bytes = New-Object byte[] 128; (New-Object Security.Cryptography.RNGCryptoServiceProvider).GetBytes($bytes); [System.BitConverter]::ToString($bytes) -Replace '-'\n    ```\n\n7. Run the server:\n\n    ```bash\n    uvicorn main:server --reload\n    ```\n\nNote: If you need to update dependencies, you can modify the `requirements.txt` or `dev-requirements.txt` files directly and then run `uv pip install -r requirements.txt` or `uv pip install -r dev-requirements.txt` respectively.\n\n## Environment Specific Configuration\n\nThis project uses environment-specific configuration files and symbolic links to manage different environments such as development, production, and staging. Follow the steps below for your operating system to set up the desired environment.\n\n```bash\n# macOS, linux\nln -s \u003cTARGET\u003e.env .env\n# example: ln -s prod.env .env\n\n# windows\nmklink .env \u003cTARGET\u003e.env\n# example: mklink .env prod.env\n```\n\n## Databases\n\n### Shell\n\nTo access the database shell, run this command\n\n```bash\npython -i shell.py\n```\n\nThe `shell.py` script will be loaded including the database session and models.\n\n### Migrations\n\nTo do a database migration, follow the steps below.\n\n1. Update `database/models.py` with the changes you want\n2. Run this command to generate the migration file in `migrations/versions`\n\n    ```bash\n    alembic revision --autogenerate -m \"Describe your migration\"\n    ```\n\n3. Check the newly generated migration file and verify that it generated correctly.\n4. Run this command to apply the migration\n    ```bash\n    alembic upgrade head\n    ```\n\n⛔️ Autogenerated migrations cannot detect these changes:\n\n-   Changes of table name\n-   Changes of column name\n-   Anonymously named constraints\n-   Special SQLAlchemy types such as Enum when generated on a backend which doesn’t support ENUM directly\n\n[Reference](https://alembic.sqlalchemy.org/en/latest/autogenerate.html#what-does-autogenerate-detect-and-what-does-it-not-detect)\n\nThese changes will need to be migrated manually by creating an empty migration file and then writing the code to create the changes.\n\n```bash\n# Manual creation of empty migration file\nalembic revision -m \"Describe your migration\"\n```\n\n### Downgrade Migration\n\nRun this command to revert every migration back to the beginning.\n\n```bash\nalembic downgrade base\n```\n\n## JWT Implementation\n\nIn this FastAPI template, JSON Web Tokens (JWT) can be optionally utilized for authentication. This documentation section elucidates the JWT implementation and related functionalities.\n\n### JWT Overview\n\nThe JWT implementation can be found in the module: app/auth/jwt.py. The primary functions include:\n\n-   Creating access and refresh JWT tokens.\n-   Verifying and decoding a given JWT token.\n-   Handling JWT-based authentication for FastAPI routes.\n\n#### User Management\n\nIf a user associated with a JWT token is not found in the database, a new user will be created. This is managed by the get_or_create_user function. When a token is decoded and the corresponding user ID (sub field in the token) is not found, the system will attempt to create a new user with that ID.\n\n#### Nonce Usage\n\nA nonce is an arbitrary number that can be used just once. It's an optional field in the JWT token to ensure additional security. If a nonce is used:\n\n-   It is stored in Redis for the duration of the refresh token's validity.\n-   It must match between access and refresh tokens to ensure their pairing.\n-   Its presence in Redis is verified before the token is considered valid.\n\nEnabling nonce usage provides an additional layer of security against token reuse, but requires Redis to function.\n\n### Modifying JWT Payload Fields\n\nThe JWT token payload structure is defined in `app/types/jwt.py`` under the JWTPayload class. If you wish to add more fields to the JWT token payload:\n\n1. Update the TokenData and JWTPayload class in `app/types/jwt.py`` by adding the desired fields.\n\n    ```python\n    class JWTPayload(BaseModel):\n        # ... existing fields ...\n        new_field: Type\n\n    class TokenData(BaseModel):\n        # ... existing fields ...\n        new_field: Type\n    ```\n\n    TokenData is separated from JWTPayload to make it clear what is automatically filled in and what is manually added. Both classes must be updated to include the new fields.\n\n2. Wherever the token is created, update the payload to include the new fields.\n\n    ```python\n    from app.auth.jwt import create_jwt\n    from app.types.jwt import TokenData\n\n    payload = TokenData(\n        sub='user_id_1',\n        field1='value1',\n        # ... all fields ...\n    )\n    access_token, refresh_token = create_jwt(payload)\n    ```\n\nRemember, the JWT token has a size limit. The more data you include, the bigger your token becomes, so ensure that you only include essential data in the token payload.\n\n## Project Structure\n\n```\n📄 main.py                  - Server entry point\n📁 .github/                 - Github specific files\n📁 app/                     - Application code\n   ├── 📁 api               - API endpoints and middleware\n   ├── 📁 auth              - Authentication / authorization\n   ├── 📁 cache             - Redis code and caching functions\n   ├── 📁 core              - Core configuration\n   ├── 📁 db                - Database connections\n   ├── 📁 discord           - Discord library for auth (optional)\n   ├── 📁 lmbd              - Holds AWS lambda functions\n   ├── 📁 migrations        - Database migrations\n   ├── 📁 models            - Database ORM models\n   ├── 📁 types             - Type definitions\n   └── 📁 util              - Helper functions\n```\n\n## Makefile Commands\n\nMake files are used to run common commands. You can find the list of commands in the `Makefile` file.\nTo use these commands, first copy `make-env-example.sh` to `make-env.sh` and update the values.\n\n```bash\n# macOS\ncp make-env-example.sh make-env.sh\n\n# windows (powershell)\ncopy make-env-example.sh make-env.sh\n```\n\nRemember to make the file executable\n\n```bash\nchmod +x make-env.sh\n```\n\nThen you can run the commands like this\n\n```bash\n./make-env.sh \u003ccommand\u003e\n```\n\nTry it with the help command, which will list all the available commands.\n\n```bash\n./make-env.sh help\n```\n\n## Contributing\n\n1. **Fork the Repository**: Start by forking the repository to your own GitHub account.\n2. **Clone the Forked Repository**: Clone the fork to your local machine.\n3. **Create a New Branch**: Always create a new branch for your changes.\n4. **Make Your Changes**: Implement your changes.\n5. **Run Tests**: Make sure to test your changes locally.\n6. **Submit a Pull Request**: Commit and push your changes, then create a pull request against the main branch.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastestmolasses%2Ffastest-fastapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastestmolasses%2Ffastest-fastapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastestmolasses%2Ffastest-fastapi/lists"}