sqlalchemy-api


Namesqlalchemy-api JSON
Version 0.0.2 PyPI version JSON
download
home_page
Summary
upload_time2023-08-30 07:51:23
maintainer
docs_urlNone
author
requires_python>=3.7
license
keywords api fastapi rest sqlalchemy starlette
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <p align="center">
  <a><img src="https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/sqlalchemy_api.png" alt="SQLalchemyAPI"></a>
</p>

<p align="center">
  <a href="https://github.com/nacosdev/sqlalchemy_api/actions?query=workflow%3ATests+event%3Apush+branch%3Amain" target="_blank">
      <img src="https://github.com/nacosdev/sqlalchemy_api/workflows/Tests/badge.svg?event=push&branch=main" alt="Test">
  </a>
  <a href="https://codecov.io/gh/nacosdev/sqlalchemy_api">
      <img src="https://codecov.io/gh/nacosdev/sqlalchemy_api/branch/main/graph/badge.svg" alt="Coverage">
  </a>
  <a href="https://pypi.org/project/sqlalchemy-api" target="_blank">
      <img src="https://img.shields.io/pypi/v/sqlalchemy-api?color=%2334D058&label=pypi%20package" alt="Package version">
  </a>
  <a href="https://pypi.org/project/sqlalchemy-api" target="_blank">
      <img src="https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058" alt="Supported Python versions">
  </a>
</p>

SQLAlchemy API is a library that helps to turn the [SQLAlchemy](https://www.sqlalchemy.org/) models into a REST API. It uses the power of [Pydantic 2](https://docs.pydantic.dev/dev-v2/), to validate and serialize the data. This is a framework-agnostic library that can be used with any web framework. Currently, it provides support for [Starlette](https://www.starlette.io/) and [FastAPI](https://fastapi.tiangolo.com/).

---

**Documentation**: <a href="https://nacosdev.github.io/sqlalchemy_api" target="_blank">https://nacosdev.github.io/sqlalchemy_api</a>

**Source Code**: <a href="https://github.com/nacosdev/sqlalchemy_api" target="_blank">https://github.com/nacosdev/sqlalchemy_api</a>

---

**Table of Contents**

- [Requirements](#requirements)
- [Installation](#installation)
- [License](#license)

---

## Requirements

- Python>=3.7
- SQLAlchemy>=1.4
- Pydantic>=2

## Installation

```bash
pip install sqlalchemy-api
```

## Example

### Create it

- Create a file `main.py` with SQLAlchemy models and mount the crud using one of the adapters, in this example we will use the FastAPI adapter:

```python
from sqlalchemy_api.adapters.fastapi_crud import APICrud
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import relationship, mapped_column, Mapped
from sqlalchemy.ext.declarative import declarative_base
from fastapi import FastAPI
from typing import List

Base = declarative_base()

engine = create_engine(
    "sqlite:///example.db",
    connect_args={"check_same_thread": False},
)

class User(Base):
    __tablename__ = "user"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(default="John Doe")
    age: Mapped[int] = mapped_column(nullable=False)
    posts: Mapped[List['Post']] = relationship(back_populates="user")

class Post(Base):
    __tablename__ = "post"
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column()
    content: Mapped[str] = mapped_column()
    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), nullable=False)
    user: Mapped['User'] = relationship(back_populates="posts")

Base.metadata.create_all(engine)  # Create tables

user_crud_router = APICrud(User, engine)
post_crud_router = APICrud(Post, engine)

app = FastAPI()
app.include_router(user_crud_router, prefix="/user", tags=["User"])
app.include_router(post_crud_router, prefix="/post", tags=["Post"])
```

You will also need an ASGI server and FastAPI to be able to run this app, both are optional dependencies of SQLAlchemy API:

```bash
pip install sqlalchemy-api[fastapi]
```

### Run it
```bash
uvicorn main:app --reload
```


### Use it
Endpoints are automatically generated for the defined models and the FastAPI adapter provides automatic Swagger documentation, you can access [localhost:8000/docs](localhost:8000/docs) to interact with them:

<p align="center">
  <a><img src="https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-1.png" alt="Swagger"></a>
</p>

SQLAlchemyAPI also provides different operators depending on the column data type, to filter the data:

<p align="center">
  <a><img src="https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-2.png" alt="Swagger2"></a>
</p>

The data returned is automatically paginated and serialized, including the relationships defined in the models:

<p align="center">
  <a><img src="https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-3.png" alt="Swagger3"></a>
</p>

Post data is automatically validated and serialized using Pydantic, for example, if you try to create a user wihout the required `age` field, you will get an error like this:

<p align="center">
  <a><img src="https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-4.png" alt="Swagger4"></a>
</p>

## License

`sqlalchemy-api` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "sqlalchemy-api",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "api,fastapi,rest,sqlalchemy,starlette",
    "author": "",
    "author_email": "Nicolas Acosta <nacosdev@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/03/8e/3bf6d348742ddb343bd440796bcf38ceba0ffcb234e58fbe5753208b9011/sqlalchemy_api-0.0.2.tar.gz",
    "platform": null,
    "description": "<p align=\"center\">\n  <a><img src=\"https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/sqlalchemy_api.png\" alt=\"SQLalchemyAPI\"></a>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://github.com/nacosdev/sqlalchemy_api/actions?query=workflow%3ATests+event%3Apush+branch%3Amain\" target=\"_blank\">\n      <img src=\"https://github.com/nacosdev/sqlalchemy_api/workflows/Tests/badge.svg?event=push&branch=main\" alt=\"Test\">\n  </a>\n  <a href=\"https://codecov.io/gh/nacosdev/sqlalchemy_api\">\n      <img src=\"https://codecov.io/gh/nacosdev/sqlalchemy_api/branch/main/graph/badge.svg\" alt=\"Coverage\">\n  </a>\n  <a href=\"https://pypi.org/project/sqlalchemy-api\" target=\"_blank\">\n      <img src=\"https://img.shields.io/pypi/v/sqlalchemy-api?color=%2334D058&label=pypi%20package\" alt=\"Package version\">\n  </a>\n  <a href=\"https://pypi.org/project/sqlalchemy-api\" target=\"_blank\">\n      <img src=\"https://img.shields.io/pypi/pyversions/fastapi.svg?color=%2334D058\" alt=\"Supported Python versions\">\n  </a>\n</p>\n\nSQLAlchemy API is a library that helps to turn the [SQLAlchemy](https://www.sqlalchemy.org/) models into a REST API. It uses the power of [Pydantic 2](https://docs.pydantic.dev/dev-v2/), to validate and serialize the data. This is a framework-agnostic library that can be used with any web framework. Currently, it provides support for [Starlette](https://www.starlette.io/) and [FastAPI](https://fastapi.tiangolo.com/).\n\n---\n\n**Documentation**: <a href=\"https://nacosdev.github.io/sqlalchemy_api\" target=\"_blank\">https://nacosdev.github.io/sqlalchemy_api</a>\n\n**Source Code**: <a href=\"https://github.com/nacosdev/sqlalchemy_api\" target=\"_blank\">https://github.com/nacosdev/sqlalchemy_api</a>\n\n---\n\n**Table of Contents**\n\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [License](#license)\n\n---\n\n## Requirements\n\n- Python>=3.7\n- SQLAlchemy>=1.4\n- Pydantic>=2\n\n## Installation\n\n```bash\npip install sqlalchemy-api\n```\n\n## Example\n\n### Create it\n\n- Create a file `main.py` with SQLAlchemy models and mount the crud using one of the adapters, in this example we will use the FastAPI adapter:\n\n```python\nfrom sqlalchemy_api.adapters.fastapi_crud import APICrud\nfrom sqlalchemy import create_engine, ForeignKey\nfrom sqlalchemy.orm import relationship, mapped_column, Mapped\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom fastapi import FastAPI\nfrom typing import List\n\nBase = declarative_base()\n\nengine = create_engine(\n    \"sqlite:///example.db\",\n    connect_args={\"check_same_thread\": False},\n)\n\nclass User(Base):\n    __tablename__ = \"user\"\n    id: Mapped[int] = mapped_column(primary_key=True)\n    name: Mapped[str] = mapped_column(default=\"John Doe\")\n    age: Mapped[int] = mapped_column(nullable=False)\n    posts: Mapped[List['Post']] = relationship(back_populates=\"user\")\n\nclass Post(Base):\n    __tablename__ = \"post\"\n    id: Mapped[int] = mapped_column(primary_key=True)\n    title: Mapped[str] = mapped_column()\n    content: Mapped[str] = mapped_column()\n    user_id: Mapped[int] = mapped_column(ForeignKey(\"user.id\"), nullable=False)\n    user: Mapped['User'] = relationship(back_populates=\"posts\")\n\nBase.metadata.create_all(engine)  # Create tables\n\nuser_crud_router = APICrud(User, engine)\npost_crud_router = APICrud(Post, engine)\n\napp = FastAPI()\napp.include_router(user_crud_router, prefix=\"/user\", tags=[\"User\"])\napp.include_router(post_crud_router, prefix=\"/post\", tags=[\"Post\"])\n```\n\nYou will also need an ASGI server and FastAPI to be able to run this app, both are optional dependencies of SQLAlchemy API:\n\n```bash\npip install sqlalchemy-api[fastapi]\n```\n\n### Run it\n```bash\nuvicorn main:app --reload\n```\n\n\n### Use it\nEndpoints are automatically generated for the defined models and the FastAPI adapter provides automatic Swagger documentation, you can access [localhost:8000/docs](localhost:8000/docs) to interact with them:\n\n<p align=\"center\">\n  <a><img src=\"https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-1.png\" alt=\"Swagger\"></a>\n</p>\n\nSQLAlchemyAPI also provides different operators depending on the column data type, to filter the data:\n\n<p align=\"center\">\n  <a><img src=\"https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-2.png\" alt=\"Swagger2\"></a>\n</p>\n\nThe data returned is automatically paginated and serialized, including the relationships defined in the models:\n\n<p align=\"center\">\n  <a><img src=\"https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-3.png\" alt=\"Swagger3\"></a>\n</p>\n\nPost data is automatically validated and serialized using Pydantic, for example, if you try to create a user wihout the required `age` field, you will get an error like this:\n\n<p align=\"center\">\n  <a><img src=\"https://raw.githubusercontent.com/nacosdev/sqlalchemy_api/main/docs/assets/images/swagger-4.png\" alt=\"Swagger4\"></a>\n</p>\n\n## License\n\n`sqlalchemy-api` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "",
    "version": "0.0.2",
    "project_urls": {
        "Documentation": "https://github.com/nacosdev/sqlalchemy_api#readme",
        "Issues": "https://github.com/nacosdev/sqlalchemy-api/issues",
        "Source": "https://github.com/nacosdev/sqlalchemy-api"
    },
    "split_keywords": [
        "api",
        "fastapi",
        "rest",
        "sqlalchemy",
        "starlette"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e3fffed02b5bd8c2045c09990ec68021027b4a9dac31a1c9a9edced747303891",
                "md5": "33e191f9e908b9cf9354a5420a8831c6",
                "sha256": "88efab6e93f79d176b17fb95988600c55c08a5c8af7288f2a6daf8b22a377c91"
            },
            "downloads": -1,
            "filename": "sqlalchemy_api-0.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "33e191f9e908b9cf9354a5420a8831c6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 15909,
            "upload_time": "2023-08-30T07:51:21",
            "upload_time_iso_8601": "2023-08-30T07:51:21.628542Z",
            "url": "https://files.pythonhosted.org/packages/e3/ff/fed02b5bd8c2045c09990ec68021027b4a9dac31a1c9a9edced747303891/sqlalchemy_api-0.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "038e3bf6d348742ddb343bd440796bcf38ceba0ffcb234e58fbe5753208b9011",
                "md5": "cdc0f4532cafdd97c9b2d08124e90818",
                "sha256": "5035dc554ce02f051e92c1568ce2099d8005126229e7b24c6dbffe73d5395ed4"
            },
            "downloads": -1,
            "filename": "sqlalchemy_api-0.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "cdc0f4532cafdd97c9b2d08124e90818",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 301708,
            "upload_time": "2023-08-30T07:51:23",
            "upload_time_iso_8601": "2023-08-30T07:51:23.216679Z",
            "url": "https://files.pythonhosted.org/packages/03/8e/3bf6d348742ddb343bd440796bcf38ceba0ffcb234e58fbe5753208b9011/sqlalchemy_api-0.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-30 07:51:23",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "nacosdev",
    "github_project": "sqlalchemy_api#readme",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "sqlalchemy-api"
}
        
Elapsed time: 0.11670s