FastAPI-Restly#

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 five CRUD routes under /users. It makes Pydantic schemas from the model, and a list route that can filter, sort and paginate. Each route runs a few small methods on the view. To change one part, override that method; 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: 0.14.0, a 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.

How Restly works gives the main ideas in a few paragraphs, and the Guide explains each part and how you can change it.

Quick Start#

Install FastAPI-Restly along with an async SQLite driver:

pip install "fastapi-restly[standard]" aiosqlite

A SQLAlchemy model and a four-line view class make a complete application. Copy this whole example into main.py:

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

Run fastapi dev main.py, and open http://127.0.0.1:8000/docs. The view has the routes below. Their Pydantic schemas are generated from the model, and you can customize them.

GET    /users       # list users: filter, sort, paginate via URL params
POST   /users       # create a user
GET    /users/{id}  # read one user
PATCH  /users/{id}  # partially update one user
DELETE /users/{id}  # delete one user

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}.

Build a Blog API teaches Restly step by step, from the first model to authors, drafts, and tests.

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, add this delete method to UserView, so that it keeps the row and marks the user as inactive:

    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. See Share behavior with base 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. The blog example shows published posts, and the drafts of the caller:

class PostClauses(fr.ClauseNamespace):
    model = Post

    default_scope = fr.where_clause(
        or_(Post.published, Post.author_id == Current.user_id)
    )

In the scope, Current.user_id is a placeholder for the id of the caller. Restly fills it in each time it applies the scope; see Request Context. Another user’s draft is a 404 on GET, PATCH and DELETE, and the list does not show or count it. authorize decides what the caller may do with a row that they can see, and a refusal is a 403. 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#

  • Views without CRUD: fr.View groups custom routes, such as login or webhooks, and declares their dependencies once. See Views.

  • 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: posts and comments, then authors and drafts.

Tutorial: Build a Blog API
Guide

One page for each part of Restly: how it works, and how to use it.

Guide
API

Public Python API by module, with signatures and default behavior.

API Reference
About

History, design goals, and why this framework exists.

About FastAPI-Restly

Newsletter#

Subscribe to get an email when 1.0 is released.