Skip to main content

FastAPI-Restly

PyPI CI Python License Coverage

Class-based REST resources for FastAPI and SQLAlchemy. Minimal boilerplate, full control.

import fastapi_restly as fr

@fr.include_view(app)
class UserView(fr.AsyncRestView):
    prefix = "/users"
    model = User  # your SQLAlchemy model

This view serves the five CRUD routes under /users, with Pydantic schemas made from the model, and filtering, sorting and pagination on the list. To change one step, override its method, and the rest stays the same.

Restly is for REST resources, not for your whole app. It works inside the FastAPI app that you already have, and you add it one resource at a time; see Use Restly in an existing project.

Status: beta. Restly ran in production at two companies before it became public. Until 1.0, a minor release can have breaking changes, and the changelog says what to change in your code. Subscribe to the newsletter to get an email when 1.0 is released. If something is broken or missing, please open an issue.

Install Restly and aiosqlite, the async SQLite driver that the Quickstart uses:

pip install "fastapi-restly[standard]" aiosqlite

Docs · Changelog · Examples · Newsletter · Contributing · Security

Quickstart

Copy this whole example into main.py, run fastapi dev main.py, and open http://127.0.0.1:8000/docs. It creates the SQLite tables at startup, for local development. Use Alembic migrations in production.

from contextlib import asynccontextmanager

import fastapi_restly as fr
from fastapi import FastAPI
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

fr.configure(async_database_url="sqlite+aiosqlite:///app.db")

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    email: Mapped[str]
    active: Mapped[bool] = mapped_column(default=True)

@asynccontextmanager
async def lifespan(_app: FastAPI):
    await fr.db.async_create_all(Base)  # dev tables; use Alembic in production
    yield

app = FastAPI(lifespan=lifespan)

@fr.include_view(app)
class UserView(fr.AsyncRestView):
    prefix = "/users"
    model = User

That view has these routes:

GET    /users       # list users, with filtering, sorting, and pagination
POST   /users       # create a user
GET    /users/{id}  # read one user
PATCH  /users/{id}  # partially update one user
DELETE /users/{id}  # delete one user

Restly generates the Pydantic schemas from the model. The list returns a page of at most 50 rows, in an envelope: {"data": [...], "total_count": 2, "page": 1, "page_size": 50, "total_pages": 1}.

The example uses plain SQLAlchemy, and the Base stays yours. In a real project, add fr.ModelDefaults to the base: models become dataclasses, and each table gets its name from the class. Then fr.IDMixin takes the place of the id column, and fr.IDSchema gives a schema its id. The examples below use this base and model:

class Base(fr.ModelDefaults, DeclarativeBase):
    pass

class User(fr.IDMixin, Base):
    name: Mapped[str]
    email: Mapped[str]
    active: Mapped[bool] = mapped_column(default=True)

Made for customization

Change one step, keep the rest

Each CRUD route runs a fixed list of steps. To change one of the steps, override the related method. For example, this view overrides delete, so that it keeps the row and marks the user as inactive:

@fr.include_view(app)
class UserView(fr.AsyncRestView):
    prefix = "/users"
    model = User

    async def delete(self, user):
        user.active = False  # keep the row

DELETE /users/{id} still runs authorize, commits and returns 204. The other four routes do not change. See Delete.

Add your own routes

A view can have routes of its own, next to the CRUD routes. A route is a method of the view class, with a route decorator such as @fr.post. Here UserView gets a route that makes a user active again, after the delete above:

from fastapi_restly.views import IDType, ViewResponse


@fr.include_view(app)
class UserView(fr.AsyncRestView):
    prefix = "/users"
    model = User

    class Action(fr.Action):
        ACTIVATE = "activate"

    @fr.post("/{id}/activate", status_code=200)
    async def activate(self, id: IDType) -> ViewResponse:
        user = await self.get_one(id)
        async with self.write_action(self.Action.ACTIVATE, obj=user):
            user.active = True
        return user

write_action runs the same steps as a CRUD write: it calls authorize with the action "activate", saves the change and commits. IDType and ViewResponse stand for the id type and the response schema of the view. So OpenAPI shows UserResponse for this route too. See Custom Routes.

Declare dependencies once

Views are Python classes, so they share code by inheritance. Declare the dependencies of your app once, on a base view, and read them from self:

class AppRestView(fr.AsyncRestView):
    current_user: Annotated[User, Depends(get_current_user)]

    async def authorize(self, action, obj=None, data=None):
        reads = (fr.Action.GET_MANY, fr.Action.GET_ONE)
        if action not in reads and not self.current_user.is_admin:
            raise fr.exc.Forbidden("Only admins can change this")


@fr.include_view(app)
class ProjectView(AppRestView):
    prefix = "/projects"
    model = Project

Every view that inherits from AppRestView gets self.current_user, and the same rule in authorize: only an admin can change data. fr.View groups custom routes, such as login or webhooks, and has no CRUD routes. See Views.

Decide who sees which rows

A scope on the model decides which rows exist for a request. You write it once, and Restly applies it when a view lists, reads, updates or deletes rows of the model, and in every reference check. authorize decides what the caller may do with a row that they can see.

class PostClauses(fr.ClauseNamespace):
    model = Post

    default_scope = fr.where_clause(  # published posts, and your own drafts
        or_(Post.published, Post.author_id == Current.user_id)
    )


class PostView(fr.AsyncRestView):
    ...

    async def authorize(self, action, obj=None, data=None):
        if action in (fr.Action.UPDATE, fr.Action.DELETE):
            if obj.author_id != Current.user_id():
                raise fr.exc.Forbidden("Only the author can change this")

Current.user_id() is the id of the caller. Your app sets it for each request; see Request Context. The scope uses Current.user_id without a call, so that Restly reads the value each time it applies the scope. Another user's draft is a 404 on GET, PATCH and DELETE, and the list does not show or count it. See Scopes and Authorization.

Choose which fields go in and out

Write one Pydantic schema for the resource. fr.ReadOnly marks a field that only goes out, and fr.WriteOnly marks a field that only comes in. Restly builds the response, create and update schemas from it, with names that OpenAPI and generated clients show. Here the User model also has password, team_id and created_at columns:

class UserSchema(fr.IDSchema):
    name: str
    email: str
    password: fr.WriteOnly[str]
    team_id: fr.MustExist[int, Team]
    created_at: fr.ReadOnly[fr.UTCDatetime]
Class Used for Fields
UserResponse every response id, name, email, team_id, created_at
UserCreate the body of POST name, email, password, team_id
UserUpdate the body of PATCH the same as UserCreate, and the client can leave out any of them

team_id is a reference: Restly checks that the team exists, inside the scope of Team. A wrong id is a 404. To make a body or the response different, write that schema yourself and set it on the view. See Schemas & Validation.

Use plain FastAPI where you need it

When a route needs something that Restly does not do, write it as a plain FastAPI route. Your declarative base, your engine and your app stay yours, and Restly works next to the routes that you have:

app = FastAPI()
app.include_router(orders_router)  # your routes stay as they are
fr.configure(async_engine=engine)  # Restly uses your engine

@fr.include_view(app)
class CustomerView(fr.AsyncRestView):
    prefix = "/customers"
    model = Customer  # a model on your own Base

See Existing Projects.

Also in Restly

  • List params: GET /users?name=John&sort=-id&page=2, and operators such as email__icontains=example.com. The keys come from the response schema, and an unknown key is a 422. See Filtering, Sorting & Pagination.
  • Tests: pip install "fastapi-restly[testing]" adds pytest fixtures. Each test runs in a transaction that rolls back, so a test needs no cleanup code. See Testing.
  • A new project: restly new myapp writes a complete project, with a users resource and its tests. See New Projects.
  • Database conflicts: a duplicate unique value in a CRUD write or a write_action block is a 409, not a 500. See Errors.
  • React Admin: AsyncReactAdminView works with ra-data-simple-rest. See React Admin.
  • Sync and async: RestView and AsyncRestView have the same methods.

What Restly does not do

  • Restly does not log users in. FastAPI's security tools find the caller, and Restly decides what that caller can see and do.
  • Restly does not migrate your database. Use Alembic: restly new sets it up.
  • Restly is built on SQLAlchemy 2.0. It does not work with other ORMs or with document databases.
  • The default routes are CRUD on one row at a time. A bulk write, or a write of related rows from one body, is code that you add to the view.

See What the default routes do not do for the details.

Documentation

  • Tutorial: build a blog API step by step, from the first model to authors and drafts.
  • Guide: one page for each part of Restly, how it works and how to use it. Start with Views, and CRUD Routes.
  • API Reference: exact signatures and defaults.

Examples

Complete applications in example-projects/:

  • Shop: products, orders and customers.
  • Blog: the blog that the tutorial builds, with authors, drafts and a publish action.
  • SaaS: project management with many tenants.

Contributing

Pull requests and issues are welcome. See CONTRIBUTING.md for setup and tests. For security issues, see SECURITY.md.

License

MIT. See LICENSE.

Metadata

Release files for fastapi-restly 0.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-restly 0.14.0
File Size Uploaded Provenance Actions
fastapi_restly-0.14.0.tar.gz 275.2 kB With provenance Details for fastapi_restly-0.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-restly 0.14.0
File Interpreter ABI Platform Actions
fastapi_restly-0.14.0-py3-none-any.whl Python 3 none any Details for fastapi_restly-0.14.0-py3-none-any.whl

Total release size: 581.0 kB

Release files / fastapi_restly-0.14.0.tar.gz

Download URL fastapi_restly-0.14.0.tar.gz
Size 275.2 kB
Tags Source
SHA-256 checksum
How to use checksums
364174aa299cb891fb02aadeb984d03d3caaedc44948f05f79ea6e12c0ac7c3d
BLAKE2b-256 checksum
How to use checksums
86ed240601ce0f168e041bc7e611d57276c074be3f62871af0aa6173882cf3e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Release files / fastapi_restly-0.14.0-py3-none-any.whl

Download URL fastapi_restly-0.14.0-py3-none-any.whl
Size 305.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
35229d15821971e2a705417fe64663bda5d6879eed8fd1d131cff824ccfbaefb
BLAKE2b-256 checksum
How to use checksums
93a1fa08cad06733df61537103a04107ec32ad129e82c84e605394dbc3fb27e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Security for fastapi-restly 0.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_restly-0.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page