Skip to main content

Generalized RESTful ORM API for SQLAlchemy models with auto-CRUD

Project description

orm-query-api

Python FastAPI License

๐Ÿš€ orm-query-api is a modern Python library for dynamically generating RESTful CRUD APIs from SQLAlchemy models using FastAPI โ€” with advanced query parsing, validation, and automatic serialization.


โœจ Features

  • โœ… Auto-generate CRUD endpoints for any SQLAlchemy model
  • โœ… Supports query string filters, sorting, pagination
  • โœ… Typed input via Pydantic models
  • โœ… Response serialization using custom serializers
  • โœ… Built-in validation and error handling
  • โœ… Easily composable into any FastAPI app

๐Ÿ“ฆ Installation

pip install orm-query-api

Or add it to your requirements.txt.


๐Ÿš€ Quick Start

1. Define your SQLAlchemy model

import datetime

from sqlalchemy import Column, Integer, String, DateTime, func, Boolean, Date
from sqlalchemy.orm import Mapped, relationship

from orm_query_api.services.db_services import Base
from typing import List

class ToDo(Base):
    __tablename__ = "todo"
    id: Mapped[int] = Column(Integer, primary_key=True)
    comment: Mapped[str] = Column(String, nullable=True, default=None)
    created_at: Mapped[datetime.datetime] = Column(
        DateTime(timezone=True), server_default=func.now()
    )
    priority: Mapped[int] = Column(Integer)
    is_main: Mapped[bool] = Column(Boolean)
    worker_fullname: Mapped[str] = Column(String)
    due_date: Mapped[datetime.date] = Column(Date)
    count: Mapped[int] = Column(Integer, default=1)
    users: Mapped[List["User"]] = relationship(
        secondary="todo_user", back_populates="todos"
    )

2. Define your input Pydantic model and serializer

from pydantic import BaseModel
from orm_query_api.services.serialization import BaseSerializer
import datetime
from typing import List
from orm_query_api.services.serialization import SerializerField, RelationField


class ToDoPydantic(BaseModel):
    comment: str | None = None
    created_at: datetime.datetime
    priority: int
    is_main: bool = False
    worker_fullname: str
    due_date: datetime.date
    count: int = 0
    user_ids: List[int]


class ToDoSerializer(BaseSerializer):
    model = ToDo
    fields = [
        SerializerField("id", "primary_key"),
        SerializerField("comment", "instruction"),
        SerializerField("created_at", "creation_time"),
        SerializerField("priority", "preference"),
        SerializerField("is_main", "is_principal"),
        SerializerField("worker_fullname", "worker"),
        SerializerField("due_date", "deadline"),
        SerializerField("count", "amount"),
        RelationField("slaves", "slaves"),
        RelationField("users", "users"),
    ]

3. Generate and include the router

from fastapi import FastAPI
from orm_query_api.routes import generate_crud_router

app = FastAPI()

todo_router = generate_crud_router(
    model=ToDo,
    serializer=ToDoSerializer,
    pydantic_model=ToDoPydantic,
    prefix="todo"
)

app.include_router(todo_router)

๐Ÿ” Advanced Querying

Supports GET /q=(id, created_at).filter(created_at=2022-01-01).offset(2).limit(10) style queries with:

  • filter: field'operator'value
  • order: order(field).asc or order(field).desc
  • offset / limit: for pagination
  • All parsed and validated against the serializer.

๐Ÿ“ Project Structure

orm-query-api/
โ”œโ”€โ”€ routes.py
โ”œโ”€โ”€ registry.py
โ”œโ”€โ”€ utils/
โ”‚   โ”œโ”€โ”€ __init__.py     
โ”‚   โ””โ”€โ”€ auto_gen.py        
โ”œโ”€โ”€ exceptions/
โ”‚   โ”œโ”€โ”€ __init__.py     
โ”‚   โ””โ”€โ”€ error.py    
โ”œโ”€โ”€ parser/
โ”‚   โ”œโ”€โ”€ query_parser.py     # Parses query strings
โ”‚   โ”œโ”€โ”€ query_validation.py # Validates parsed query
โ”‚   โ””โ”€โ”€ query_parse.py      # Generates SQLAlchemy query objects
โ”œโ”€โ”€ services/
โ”‚   โ”œโ”€โ”€ db_services.py      # DB session management
โ”‚   โ”œโ”€โ”€ serialization.py    # BaseSerializer class
โ”‚   โ”œโ”€โ”€ exc_handlers.py    
โ”‚   โ””โ”€โ”€ __init__.py    

๐Ÿงช Running Tests

pytest tests/

Use pytest with coverage:

pytest --cov=orm_query_api

๐Ÿ“š Roadmap

  • Auto-generate input model from SQLAlchemy models
  • Swagger-compatible filtering/sorting docs
  • Plugin hooks (e.g. auth, caching)
  • Async SQLAlchemy support (SQLModel or 2.0)

๐Ÿ›  Dependencies

  • FastAPI
  • SQLAlchemy
  • Pydantic
  • Lark for grammar-based query parsing

๐Ÿ‘ฅ Contributing

Contributions are welcome! Feel free to fork, open issues, or submit PRs.


๐Ÿ“„ License

MIT ยฉ kkommatt

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

orm_query_api-0.1.0.tar.gz (22.5 kB view details)

Uploaded Source

Built Distribution

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

orm_query_api-0.1.0-py3-none-any.whl (20.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: orm_query_api-0.1.0.tar.gz
  • Upload date:
  • Size: 22.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for orm_query_api-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6680cadd997f936034dd61ce8b9d872bf3ccec04597cd60aba851f9ac1e0dcb5
MD5 efa0120d59edef20800f184033f93c73
BLAKE2b-256 f64c2be93a9474fd0dab3a512201307226587b7a1f4ee94bb0610bdd25bc13d7

See more details on using hashes here.

File details

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

File metadata

  • Download URL: orm_query_api-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 20.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.0

File hashes

Hashes for orm_query_api-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 88a037e623e143868e8e2bbf20fa14a5c9c49decfe4e73d2ddfeb82009843e8d
MD5 00b44153039e94357951f44f1ffd789a
BLAKE2b-256 fa3472834bd6ae083b3c2f3c52d715a839a54834468be3f252c5f608f0ae21c7

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