Class-based REST resources for FastAPI and SQLAlchemy 2.0. 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 for four years 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)
What Restly does differently
Change one step, keep the rest
Each CRUD route runs a fixed list of steps. To change one step, override its
method. 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
Request Lifecycle & Hooks.
A hidden row is a 404, a refused action is a 403
A scope on the model decides which rows exist for a request. 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.
One schema for requests and responses
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 class and the two request bodies 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.
SQLAlchemy stays SQLAlchemy, FastAPI stays FastAPI
Your declarative base, your engine and your app stay yours. Add Restly next to the routes that you have, one resource at a time. When one route needs something that Restly does not do, write it as a plain FastAPI route.
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
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. A view can also have custom routes, with @fr.post and the other
route decorators. fr.View is a view without the CRUD routes, for a group
of routes such as login or webhooks. See
Views.
Also in Restly
- List params:
GET /users?name=John&sort=-id&page=2, and operators such asemail__icontains=example.com. The keys come from the response class, 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 myappwrites a complete project, with ausersresource and its tests. See New & Existing Projects. - Database conflicts: a duplicate unique value in a CRUD write or a
write_actionblock is a 409, not a 500. See Errors. - React Admin:
AsyncReactAdminViewworks withra-data-simple-rest. See React Admin. - Sync and async:
RestViewandAsyncRestViewhave 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 newsets 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, CRUD Routes and Request Lifecycle & Hooks.
- 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.12.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_restly-0.12.0.tar.gz | 235.0 kB | With provenance | Details for fastapi_restly-0.12.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_restly-0.12.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_restly-0.12.0-py3-none-any.whl |
Total release size: 494.4 kB
Release files / fastapi_restly-0.12.0.tar.gz
| Download URL | fastapi_restly-0.12.0.tar.gz |
|---|---|
| Size | 235.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bc2e2f18bf5ec8b7fea32d73ca53c336c914a85b5edf750f9046e43d4b798dd7
|
|
BLAKE2b-256 checksum How to use checksums |
d24897d074844f2c352cf6b7c0a5b39b3fdefdfa7b7e3ab1598fcc20e2cd3719
|
| 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 Oct 27, 2026.
Transparency logRelease files / fastapi_restly-0.12.0-py3-none-any.whl
| Download URL | fastapi_restly-0.12.0-py3-none-any.whl |
|---|---|
| Size | 259.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9b7109963f99fd4c1853e5020903aefd0798df2cbda7609b0c251f43647f40fc
|
|
BLAKE2b-256 checksum How to use checksums |
881b3f392e48ece11914658b9334fff817322279ca07eafd46d901c761894b68
|
| 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 Oct 27, 2026.
Transparency logSecurity for fastapi-restly 0.12.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.
Attestation for fastapi_restly-0.12.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 Oct 27, 2026.
Transparency logA 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.