Skip to main content

A reusable CRUD base with filter class for FastAPI applications using SQLModel.

Project description

sqlmodel_fastapi_crud

sqlmodel_fastapi_crud is a lightweight and reusable library designed to simplify the implementation of CRUD operations in FastAPI applications. It provides an AbstractCRUD class and BaseFilter to streamline common database operations and query filtering for models using SQLModel.


Features

  • AbstractCRUD Class:

    • Create, retrieve, update, and delete operations.
    • Error handling for NotFoundError and DatabaseError.
    • Timestamps (created_at, modified_at) for tracking changes.
  • BaseFilter Class:

    • Apply dynamic filtering to SQLModel queries.
    • Sorting and pagination support for query results.
  • Generic and Flexible:

    • Easily adaptable to any SQLModel-based FastAPI application.
    • Designed with clean separation of concerns.

Installation

Install the package using pip:

pip install sqlmodel_fastapi_crud

Usage

Prerequisites

Ensure you have the following dependencies installed in your FastAPI project:

  • fastapi
  • sqlmodel

1. Define a Model

Create an SQLModel class for your entity. For example:

from sqlmodel import SQLModel, Field
from typing import Optional
from datetime import datetime

class User(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    email: str
    created_at: Optional[datetime] = None
    modified_at: Optional[datetime] = None

2. Initialize the AbstractCRUD

Use the AbstractCRUD class to perform CRUD operations for your model:

from sqlmodel_fastapi_crud.base_crud import AbstractCRUD
from sqlmodel import Session, create_engine

# Set up the database engine and session
engine = create_engine("sqlite:///database.db")
with Session(engine) as session:
    user_crud = AbstractCRUD(model=User, db_session=session)

    # Create a new user
    new_user = User(name="John Doe", email="john@example.com")
    created_user = user_crud.create(new_user)

    # Retrieve a user by ID
    retrieved_user = user_crud.get(created_user.id)

    # Update a user
    updated_data = User(name="John Updated")
    updated_user = user_crud.update(created_user.id, updated_data)

    # Delete a user
    user_crud.delete(created_user.id)

3. Using Filters

The BaseFilter class enables dynamic filtering, sorting, and pagination:

from sqlmodel_fastapi_crud.base_filter import BaseFilter

class UserFilter(BaseFilter):
    name: Optional[str] = None
    email: Optional[str] = None

# Example usage
filter = UserFilter(name="John")
filtered_users = user_crud.get_all(filter_field=filter, sort_field="name", ascending=True, skip=0, limit=10)

Exception Handling

The package includes custom exceptions for better error handling:

  • NotFoundError: Raised when a record is not found.
  • DatabaseError: Raised for database-related errors.

Example:

from sqlmodel_fastapi_crud.exceptions import NotFoundError, DatabaseError

try:
    user = user_crud.get(9999)  # Non-existent ID
except NotFoundError as e:
    print(e)
except DatabaseError as e:
    print(e)

Contribution

Contributions are welcome! Feel free to fork the repository and submit pull requests.


License

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


Author

This package was developed to simplify common CRUD patterns in FastAPI applications. For inquiries, please contact the maintainer.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlmodel_fastapi_crud-0.1.0.tar.gz (4.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlmodel_fastapi_crud-0.1.0-py3-none-any.whl (13.8 kB view details)

Uploaded Python 3

File details

Details for the file sqlmodel_fastapi_crud-0.1.0.tar.gz.

File metadata

  • Download URL: sqlmodel_fastapi_crud-0.1.0.tar.gz
  • Upload date:
  • Size: 4.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.3

File hashes

Hashes for sqlmodel_fastapi_crud-0.1.0.tar.gz
Algorithm Hash digest
SHA256 88e142c011c4f88a94e1e56f66b5f3aae192c9a78dc602500db4919220bc2a19
MD5 430bd9d183d8a924c586d4d1c12be061
BLAKE2b-256 39088bf6347bff4f974e803bda3237f94b01d3d8619a576d28d4556f2d64a7af

See more details on using hashes here.

File details

Details for the file sqlmodel_fastapi_crud-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sqlmodel_fastapi_crud-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 94158f7fd98e9f693dc7249e5aeb5f3fc191b95eee5bbea5a3a8e08247e99944
MD5 cdd9c40e108271e37c3cbf9cff76dc0b
BLAKE2b-256 5df83913fb8d5a3e1c1516926d67df7b3673e6afac1974f4a1872d0a45ed1ede

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page