Skip to main content

Library to create basics endpoints from Models SQLModels

Project description

Auto Endpoint

autoendpoint is a lightweight library for FastAPI that automatically generates asynchronous RESTful API endpoints for your SQLModel classes. It simplifies the creation of CRUD operations by dynamically building Pydantic models for data validation and handling database interactions using SQLAlchemy's AsyncSession.

Key Features

  • Full CRUD Endpoints: Automatically generates GET (all), POST (create), GET (by ID), PUT (update), PATCH (partial update), DELETE, GET (by unique field), and GET (by any field filter) endpoints for any SQLModel.
  • Dynamic GraphQL Endpoint: Automatically generates a GraphQL schema and adds a /graphql endpoint (powered by Strawberry) to query your models.
  • String Representation in GraphQL: Automatically includes a string_representation field in GraphQL queries, which uses your model's __str__ method for flexible object display.
  • Enhanced OpenAPI Documentation: All generated endpoint parameters (Body, Path, Query) include clear, dynamic descriptions for better readability in tools like FastMCP and Swagger UI.
  • Asynchronous Support: Built for high-performance async workflows using AsyncSession.
  • Smart Model Generation: Dynamically creates schemas for creation, full updates, and partial updates (PATCH), excluding primary keys from request bodies.
  • Flexible Retrieval:
    • Unique Retrieval: Endpoint to fetch a single record by any unique field (e.g., email), with error handling for duplicates.
    • Generic Filtering: New endpoint to retrieve multiple records by any field and value.
  • FastAPI Integration: Seamlessly integrates with existing FastAPI applications using an APIRouter.
  • Type Safety: Leverages Python type hints and SQLModel/Pydantic for robust validation.
  • Google Style Docstrings: Fully documented for Sphinx compatibility.

Installation

You can install autoendpoint using uv. To include asynchronous database support (e.g., PostgreSQL), use the postgresql extra:

# Basic installation
uv add autoendpoint

# Installation with PostgreSQL support (asyncpg, greenlet, psycopg2-binary)
uv add "autoendpoint[postgresql]"

Note: The library is designed to be driver-agnostic but requires greenlet and a compatible async driver (like asyncpg or aiosqlite) for SQLAlchemy's asynchronous operations.

Quick Start

Here's how to use AutoEndpoint in your FastAPI project:

1. Define your SQLModel

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

class Hero(SQLModel, table=True):
    id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None
    email: str = Field(unique=True)

    def __str__(self):
        return f"{self.name} ({self.age or '?'})"

2. Set up the Async Engine and Session

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql+asyncpg://user:password@localhost/dbname"
engine = create_async_engine(DATABASE_URL)
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

3. Initialize and Register Endpoints

from fastapi import FastAPI
from autoendpoint.core import AutoEndpoint

app = FastAPI()

@app.on_event("startup")
async def startup():
    async with async_session_maker() as session:
        # Create endpoints for the Hero model
        # Note: In a production app, you might want to manage the session differently
        # enable_graphql defaults to True
        my_endpoints = AutoEndpoint(db_session=session, models=[Hero], enable_graphql=True)
        my_endpoints.init_app(app=app)

Generated Endpoints

For a model named Hero, the following endpoints are automatically generated:

  • GET /hero: List records. Supports pagination via query parameters:
    • limit: The maximum number of records to return (default: 10). Set limit=0 to return all records.
    • page: The page number to return (default: 1).
  • POST /hero: Create a new record. Primary key is excluded from the request body and expected to be server-side or factory generated.
  • GET /hero/{id}: Retrieve a single record by its primary key.
  • PUT /hero/{id}: Update all fields of a record (excluding primary key).
  • PATCH /hero/{id}: Partially update fields of a record (excluding primary key).
  • DELETE /hero/{id}: Delete a record by its primary key.
  • GET /hero/unique/{field_name}?value=...: Retrieve a single record by any unique field (e.g., /hero/unique/email?value=test@example.com). Raises a 400 error if multiple records are found.
  • GET /hero/filter/{field_name}?value=...: Retrieve all records matching a specific field and value (e.g., /hero/filter/age?value=30).
  • GET /hero/{hero_id}/{relationship_name}: Retrieve all related records for a specific record (e.g., /hero/{hero_id}/posts for a 1:n relationship).
  • POST /hero/{hero_id}/{relationship_name}/{target_id}: Link a record to another record in a many-to-many relationship (e.g., /user/{user_id}/groups/{group_id}).
  • DELETE /hero/{hero_id}/{relationship_name}/{target_id}: Unlink a record from another record in a many-to-many relationship.
  • POST /graphql: The GraphQL endpoint (if enabled) for querying your models. Includes a string_representation field for each model that reflects its __str__ output.

FastMCP Compatibility

The generated endpoints are enhanced with description fields for all parameters, making them highly readable and easy to use with FastMCP and other LLM-friendly tools. Each parameter explicitly describes its role (e.g., "The Hero data to create" or "The Hero record to retrieve by id").

Documentation

The project includes Sphinx documentation and test coverage reports.

In GitLab CI, these are automatically generated and hosted via GitLab Pages:

  • Documentation: https://autoendpoint-beaddd.gitlab.io/docs/
  • Coverage Report: https://autoendpoint-beaddd.gitlab.io/coverage/

Methods are documented using the Google format.

License

Under construction.

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

autoendpoint-0.2.0.tar.gz (44.0 kB view details)

Uploaded Source

Built Distribution

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

autoendpoint-0.2.0-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file autoendpoint-0.2.0.tar.gz.

File metadata

  • Download URL: autoendpoint-0.2.0.tar.gz
  • Upload date:
  • Size: 44.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for autoendpoint-0.2.0.tar.gz
Algorithm Hash digest
SHA256 11ec877b01d6493411e15062162478026f3aee1cff049e5dc2aa92c484e424aa
MD5 69a42b33fb59a094107e3e748d142819
BLAKE2b-256 99fcfc82d9becf7a00884abb6411736c15b265066dfe9be9ee00b8143c0c0947

See more details on using hashes here.

File details

Details for the file autoendpoint-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: autoendpoint-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 11.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for autoendpoint-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5fd814e3e04ded77c166e1093ba25862e4e847f8f4e3e6ca330499a0781acb11
MD5 69ab11bc5ba942fbae97facc0f76e2a3
BLAKE2b-256 cfca995fcda7e5487320bb457071bfce8576131c33b539037cb83d176b7d0dd7

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