{"id":13424596,"url":"https://github.com/mfreeborn/fastapi-sqlalchemy","last_synced_at":"2026-01-14T07:53:03.201Z","repository":{"id":36016874,"uuid":"219330762","full_name":"mfreeborn/fastapi-sqlalchemy","owner":"mfreeborn","description":"Adds simple SQLAlchemy support to FastAPI","archived":false,"fork":false,"pushed_at":"2024-04-09T04:47:10.000Z","size":103,"stargazers_count":754,"open_issues_count":20,"forks_count":43,"subscribers_count":11,"default_branch":"master","last_synced_at":"2026-01-05T00:28:31.837Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/mfreeborn.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},"funding":{"github":["mfreeborn"]}},"created_at":"2019-11-03T16:30:26.000Z","updated_at":"2025-12-17T18:31:46.000Z","dependencies_parsed_at":"2024-06-18T18:32:29.790Z","dependency_job_id":"bda43e0b-fccc-46f8-a962-45354278441e","html_url":"https://github.com/mfreeborn/fastapi-sqlalchemy","commit_stats":{"total_commits":51,"total_committers":6,"mean_commits":8.5,"dds":"0.33333333333333337","last_synced_commit":"3d182f202cb673a09c52b07fd2d52cb57ce382c5"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/mfreeborn/fastapi-sqlalchemy","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mfreeborn%2Ffastapi-sqlalchemy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mfreeborn%2Ffastapi-sqlalchemy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mfreeborn%2Ffastapi-sqlalchemy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mfreeborn%2Ffastapi-sqlalchemy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mfreeborn","download_url":"https://codeload.github.com/mfreeborn/fastapi-sqlalchemy/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mfreeborn%2Ffastapi-sqlalchemy/sbom","scorecard":{"id":638946,"data":{"date":"2025-08-11","repo":{"name":"github.com/mfreeborn/fastapi-sqlalchemy","commit":"794f9d4a87bf2eca6e71916cfa60cd68d7d05c85"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":2.5,"checks":[{"name":"Code-Review","score":0,"reason":"Found 0/5 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/format.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/mfreeborn/fastapi-sqlalchemy/format.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/format.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/mfreeborn/fastapi-sqlalchemy/format.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/mfreeborn/fastapi-sqlalchemy/release.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/mfreeborn/fastapi-sqlalchemy/release.yml/master?enable=pin","Warn: pipCommand not pinned by hash: .github/workflows/format.yml:24","Warn: pipCommand not pinned by hash: .github/workflows/release.yml:24","Info:   0 out of   4 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   2 pipCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/format.yml:1","Warn: no topLevel permission defined: .github/workflows/release.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 27 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":0,"reason":"25 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: PYSEC-2024-38","Warn: Project is vulnerable to: PYSEC-2024-60 / GHSA-jjg7-2v4v-x38h","Warn: Project is vulnerable to: GHSA-2c2j-9gv5-cj73","Warn: Project is vulnerable to: GHSA-f96h-pmfr-66vw","Warn: Project is vulnerable to: GHSA-jfmj-5v4g-7637","Warn: Project is vulnerable to: PYSEC-2024-48 / GHSA-fj7x-q9j7-g6q6","Warn: Project is vulnerable to: PYSEC-2022-42986 / GHSA-43fp-rhv2-5gv8","Warn: Project is vulnerable to: PYSEC-2023-135 / GHSA-xqr8-7jwr-rhp7","Warn: Project is vulnerable to: PYSEC-2021-100 / GHSA-8h2j-cgx8-6xv7","Warn: Project is vulnerable to: PYSEC-2020-92 / GHSA-hj5v-574p-mj7c","Warn: Project is vulnerable to: PYSEC-2022-42969","Warn: Project is vulnerable to: PYSEC-2021-47 / GHSA-5jqp-qgf6-3pvh","Warn: Project is vulnerable to: GHSA-mr82-8j83-vxmv","Warn: Project is vulnerable to: PYSEC-2021-142 / GHSA-8q59-q68h-6hv4","Warn: Project is vulnerable to: GHSA-9hjg-9r4m-mvj7","Warn: Project is vulnerable to: GHSA-9wx4-h78v-vm56","Warn: Project is vulnerable to: PYSEC-2023-74 / GHSA-j8r2-6x86-q33q","Warn: Project is vulnerable to: PYSEC-2023-48 / GHSA-74m5-2c7w-9w3x","Warn: Project is vulnerable to: GHSA-34jh-p97f-mpxf","Warn: Project is vulnerable to: PYSEC-2023-212 / GHSA-g4mx-q9vg-27p4","Warn: Project is vulnerable to: PYSEC-2020-149 / GHSA-hmv2-79q8-fv6g","Warn: Project is vulnerable to: GHSA-pq67-6m6q-mj2v","Warn: Project is vulnerable to: PYSEC-2021-108 / GHSA-q2q7-5pp4-w6pg","Warn: Project is vulnerable to: PYSEC-2023-192 / GHSA-v845-jxx5-vc9f","Warn: Project is vulnerable to: PYSEC-2020-148 / GHSA-wqvq-5m8c-6g24"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-21T10:07:41.653Z","repository_id":36016874,"created_at":"2025-08-21T10:07:41.653Z","updated_at":"2025-08-21T10:07:41.653Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28413516,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T05:26:33.345Z","status":"ssl_error","status_checked_at":"2026-01-14T05:21:57.251Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":[],"created_at":"2024-07-31T00:00:56.792Z","updated_at":"2026-01-14T07:53:03.181Z","avatar_url":"https://github.com/mfreeborn.png","language":"Python","readme":"\u003c!-- [![image](https://github.com/Ewen-Zippedscript/fastapi-sqlalchemy/workflows/ci/badge.svg)](https://github.com/Ewen-Zippedscript/fastapi-sqlalchemy/actions) --\u003e\n\u003c!-- [![image](https://codecov.io/gh/mfreeborn/fastapi-sqlalchemy/branch/master/graph/badge.svg)](https://codecov.io/gh/mfreeborn/fastapi-sqlalchemy) --\u003e\n[![image](https://img.shields.io/pypi/v/FastAPI-SQLAlchemy?color=blue)](https://pypi.org/project/FastAPI-SQLAlchemy/)\n\nFastAPI-SQLAlchemy provides a simple integration between\n[FastAPI](https://github.com/tiangolo/fastapi) and\n[SQLAlchemy](https://github.com/pallets/flask-sqlalchemy) in your\napplication. It gives access to useful helpers to facilitate the\ncompletion of common tasks.\n\n# Installing\nInstall and update using\n[pip](https://pip.pypa.io/en/stable/quickstart/):\n``` text\n$ pip install fastapi-sqlalchemy\n```\n# Examples\n## Models definition\n``` python\nfrom sqlalchemy import Column, Integer, String, create_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker\n\nfrom fastapi_sqlalchemy import SQLAlchemy\ndb = SQLAlchemy(url=\"sqlite:///example.db\")\n#Define User class\nclass User(db.Base):\n    __tablename__ = \"items\"\n\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n    email = Column(String)\n\n    def __repr__(self):\n        return f\"User(id={self.id}, name='{self.name}',email='{self.email}')\"\n```\n## Usage inside of a route\n``` python\nfrom fastapi import FastAPI\nfrom models import User, db\nfrom pydantic import BaseModel\n\nfrom fastapi_sqlalchemy import DBSessionMiddleware\n\napp = FastAPI()\n\n# Add SQLAlchemy session middleware to manage database sessions\napp.add_middleware(DBSessionMiddleware, db=db)\n\n\n# Endpoint to retrieve all users\n@app.get(\"/users\")\ndef get_users():\n    \"\"\"\n    Retrieve a list of all users.\n\n    Returns:\n        List[User]: A list of User objects.\n    \"\"\"\n    return User.query.all()\n\n\n# Pydantic model for creating new users\nclass UserCreate(BaseModel):\n    name: str\n    email: str\n\n\n# Endpoint to add a new user\n@app.post(\"/add_user\")\ndef add_user(user_data: UserCreate):\n    \"\"\"\n    Add a new user to the database.\n\n    Args:\n        user_data (UserCreate): User data including name and email.\n\n    Returns:\n        dict: A message indicating the success of the operation.\n    \"\"\"\n    user = User(**user_data.model_dump())\n    print(user)\n    user.save()\n    return {\"message\": \"User created successfully\"}\n\n```\nYou can initialize the SQLAlchemy() class similar to the way\nflask-sqlalchemy, this allows for multiple database connections to work\nat the same time.\n## Usage outside of a route\n\nSometimes it is useful to be able to access the database outside the\ncontext of a request, such as in scheduled tasks which run in the\nbackground:\n\n``` python\nimport pytz\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler  # other schedulers are available\nfrom fastapi import FastAPI\nfrom models import User, db\nfrom fastapi_sqlalchemy import DBSessionMiddleware\n\napp = FastAPI()\n\napp.add_middleware(DBSessionMiddleware, db_url=\"sqlite:///example.db\")\n\n\n@app.on_event('startup')\nasync def startup_event():\n    scheduler = AsyncIOScheduler(timezone=pytz.utc)\n    scheduler.start()\n    scheduler.add_job(count_users_task, \"cron\", hour=0)  # runs every night at midnight\n\n\ndef count_users_task():\n    \"\"\"Count the number of users in the database and save it into the user_counts table.\"\"\"\n\n    # we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware``\n    # to create a database session for us. Instead, we can use the same ``db`` object and \n    # use it as a context manager, like so:\n\n    with db():\n        user_count = User.query.count()\n\n        user_count = UserCount(user_count)\n        user_count.save()\n\n    # no longer able to access a database session once the db() context manager has ended\n\n    return users\n```\n## Custom Model Base\nYou can define custom BaseModels, or extend the built in ModelBase to provide extended shared functionality for you database models.\n```python\nimport inspect\nfrom typing import List\n\nfrom sqlalchemy import Column\n\nfrom fastapi_sqlalchemy import ModelBase\n\n\nclass BaseModel(ModelBase):\n    @classmethod\n    def new(cls, **kwargs):\n        obj = cls(**kwargs)\n        obj.save()\n        return obj\n\n    @classmethod\n    def get(cls, **kwargs):\n        result: cls = cls.query.filter_by(**kwargs).first()\n        return result\n\n    @classmethod\n    def get_all(cls, **kwargs):\n        result: List[cls] = cls.query.filter_by(**kwargs).all()\n        return result\n\n    def update(self, **kwargs):\n        for column, value in kwargs.items():\n            setattr(self, column, value)\n\n        self.save()\n        return self\n\n```\nAs you can see the above BaseModel class adds support for various common functions and operations.\n## Complete examples\n\n- [Using single database](examples/single_db/)\n\n- [Using multiple databases](examples/multi_db/)\n\n- [Legacy method](examples/legacy/)\n# Legacy Examples\n\n## Models definition\nNote the only change that you need to make is to add the db.Base inheritance to each of your\nmodel classes\n``` python\nfrom sqlalchemy import Column, Integer, String, create_engine\nfrom sqlalchemy.orm import declarative_base, sessionmaker\n\nfrom fastapi_sqlalchemy import ModelBase, SQLAlchemy\n\ndb = SQLAlchemy(url=\"sqlite:///example.db\")\n\n\n# Define the User class representing the \"users\" database table\n# Using the SQLAlchemy Base property instead of defining your own\n# And inheriting from the BaseModel class for type hinting and helpful builtin methods and properties\nclass User(ModelBase, db.Base):\n    __tablename__ = \"users\"\n\n    id = Column(Integer, primary_key=True)\n    name = Column(String)\n    email = Column(String)\n\n    def __repr__(self):\n        return f\"User(id={self.id}, name='{self.name}',email='{self.email}')\"\n\n```\n## Usage inside of a route\n\n``` python\nfrom fastapi import FastAPI\nfrom fastapi_sqlalchemy import DBSessionMiddleware  # middleware helper\nfrom fastapi_sqlalchemy import db  # an object to provide global access to a database session\n\nfrom app.models import User\n\napp = FastAPI()\n\napp.add_middleware(DBSessionMiddleware, db_url=\"sqlite:///example.db\")\n\n# once the middleware is applied, any route can then access the database session \n# from the global ``db``\n\n@app.get(\"/users\")\ndef get_users():\n    users = db.session.query(User).all()\n\n    return users\n```\n\nNote that the session object provided by `db.session` is based on the\nPython3.7+ `ContextVar`. This means that each session is linked to the\nindividual request context in which it was created.\n\n## Usage outside of a route\n\nSometimes it is useful to be able to access the database outside the\ncontext of a request, such as in scheduled tasks which run in the\nbackground:\n\n``` python\nimport pytz\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler  # other schedulers are available\nfrom fastapi import FastAPI\nfrom fastapi_sqlalchemy import db\n\nfrom app.models import User, UserCount\n\napp = FastAPI()\n\napp.add_middleware(DBSessionMiddleware, db_url=\"sqlite:///example.db\")\n\n\n@app.on_event('startup')\nasync def startup_event():\n    scheduler = AsyncIOScheduler(timezone=pytz.utc)\n    scheduler.start()\n    scheduler.add_job(count_users_task, \"cron\", hour=0)  # runs every night at midnight\n\n\ndef count_users_task():\n    \"\"\"Count the number of users in the database and save it into the user_counts table.\"\"\"\n\n    # we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware``\n    # to create a database session for us. Instead, we can use the same ``db`` object and \n    # use it as a context manager, like so:\n\n    with db():\n        user_count = db.session.query(User).count()\n\n        db.session.add(UserCount(user_count))\n        db.session.commit()\n\n    # no longer able to access a database session once the db() context manager has ended\n\n    return users\n```\n","funding_links":["https://github.com/sponsors/mfreeborn"],"categories":["Third-Party Extensions","Python","Packages","HarmonyOS","FastAPI Utilities"],"sub_categories":["Databases","Windows Manager"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmfreeborn%2Ffastapi-sqlalchemy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmfreeborn%2Ffastapi-sqlalchemy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmfreeborn%2Ffastapi-sqlalchemy/lists"}