Tutorial: Add Authors and Drafts#

This tutorial continues Build a Blog API. It turns the blog into a blog with several writers:

  • Anyone can read published posts.

  • A new post is a draft. Only its author can see it.

  • Only the author can change a post or publish it.

  • Comments follow the same rules.

Each rule is one declaration or one short method that Restly calls. At the end, you write tests for the rules. The tutorial takes about forty minutes. Start from the complete file of Build a Blog API.

Know who is calling#

Every rule above depends on who is calling. Restly does not log users in. Your own authentication decides who is calling. Restly makes the answer available to the rest of your code through a Current class, a fr.ContextNamespace.

Add from typing import Annotated and from fastapi import Header to the imports. Then put this code above the app = FastAPI(...) line:

class Current(fr.ContextNamespace):
    user_id: fr.ContextParam[int | None]


def get_user_id(
    user_id: Annotated[int | None, Header(alias="X-User-ID")] = None,
) -> int | None:
    # Demo stand-in for real authentication. None means an anonymous reader.
    return user_id

Replace the app = FastAPI(...) line with this one:

app = FastAPI(lifespan=lifespan, dependencies=[Current.depends(user_id=get_user_id)])

get_user_id takes the user id from an X-User-ID header, so you can try the API with curl. Any client can send this header, so use it only for trying things out. In a real app, this function checks a session cookie or a token. Bind from a FastAPI dependency shows where your own authentication goes.

Current.depends(...) turns get_user_id into a FastAPI dependency. For each request, it calls get_user_id and stores the result in Current. All code that runs during the request can then read it with Current.user_id(). The dependency is on the app, so every route gets it. A reader without the header gets None, because reading the blog does not need a login.

Reload http://127.0.0.1:8000/docs. Every route now has an X-User-ID header field. The requests in this tutorial play two writers: Anna sends X-User-ID: 1, and Ben sends X-User-ID: 2.

Record the author#

The server decides who wrote a post, not the client. A column default on the model reads Current. Add the author_id column to Post:

class Post(Base):
    __tablename__ = "post"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    content: Mapped[str]
    published: Mapped[bool] = mapped_column(default=False)
    author_id: Mapped[int] = mapped_column(insert_default=Current.user_id)

insert_default=Current.user_id sets the column when SQLAlchemy inserts the row. Write Current.user_id without parentheses. With them, Python would read the value when it defines the class. No request has set a value then, so that fails. Read the current user in a column default explains this. The default runs on every insert, from any view or script.

The post table has a new column now. async_create_all creates missing tables, but it does not change a table that exists. Stop the server with Ctrl+C, delete the blog.db file, and start the server again with fastapi dev main.py. It creates the tables again. Then let Anna write a post. She also sends "author_id": 2:

curl -X POST http://127.0.0.1:8000/posts \
  -H 'X-User-ID: 1' -H 'Content-Type: application/json' \
  -d '{"title": "Hello", "content": "World", "author_id": 2}'
# 201, with "author_id": 2

Anna has written a post in Ben’s name. Posts still use the schema that Restly generated from the model, and that schema accepts every column. So posts need a schema of their own, which returns author_id but does not accept it. Delete the post first:

curl -X DELETE http://127.0.0.1:8000/posts/1

Add this schema above PostView, and add schema = PostSchema to the view, as you did for comments:

class PostSchema(fr.IDSchema):
    title: str
    content: str
    published: fr.ReadOnly[bool]
    author_id: fr.ReadOnly[int]

A fr.ReadOnly field appears in responses, and Restly ignores it in a request body. published is read-only too, because a new post is a draft. A route later in this tutorial publishes a post. Send Anna’s request again:

curl -X POST http://127.0.0.1:8000/posts \
  -H 'X-User-ID: 1' -H 'Content-Type: application/json' \
  -d '{"title": "Hello", "content": "World", "author_id": 2}'
# 201, with "author_id": 1 and "published": false

Hide drafts from other readers#

A scope is the rule for which rows a reader can see. Declare it once, for the model. Add or_ to the sqlalchemy import, and put this below Post:

class PostClauses(fr.ClauseNamespace):
    model = Post

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

fr.ClauseNamespace holds the query rules of one model, and fr.where_clause turns a SQLAlchemy condition into such a rule. The rule named default_scope applies to every read of posts. The list and its total count show only the posts in the scope. A single post outside the scope returns 404, also for PATCH and DELETE.

Here, Current.user_id again has no parentheses. Restly reads the value each time it runs the query. For an anonymous reader the value is None. author_id = NULL is never true in SQL, so an anonymous reader sees only published posts. Try it as Ben, as an anonymous reader, and as Anna:

curl -H 'X-User-ID: 2' http://127.0.0.1:8000/posts/1
# 404
curl http://127.0.0.1:8000/posts
# 200, with "total_count": 0
curl -H 'X-User-ID: 1' http://127.0.0.1:8000/posts/1
# 200

The scope also checks references. post_id: fr.MustExist[int, Post] on comments looks for the post inside the scope. So Ben cannot comment on Anna’s draft, and this needs no extra code:

curl -X POST http://127.0.0.1:8000/comments \
  -H 'X-User-ID: 2' -H 'Content-Type: application/json' \
  -d '{"content": "Nice post", "post_id": 1}'
# 404

Only the author may change a post#

Writing needs a user. Try to write a post without the header:

curl -X POST http://127.0.0.1:8000/posts \
  -H 'Content-Type: application/json' \
  -d '{"title": "Hi", "content": "Anonymous"}'
# 409, "Not-null constraint violated on post.author_id"

The post has no author, so the database refuses it. The answer should come before the database, and say what is wrong. And seeing a post does not mean that you may change it: another writer can read a published post, but must not edit it. Restly calls authorize before each action, so the view overrides it. Add import fastapi to the imports, and add authorize to PostView:

@fr.include_view(app)
class PostView(fr.AsyncRestView):
    prefix = "/posts"
    model = Post
    schema = PostSchema

    async def authorize(self, action, obj=None, data=None):
        if action in (fr.Action.GET_MANY, fr.Action.GET_ONE):
            return
        if Current.user_id() is None:
            raise fastapi.HTTPException(401, "Log in to write")
        if action == fr.Action.CREATE:
            return
        if obj is None or obj.author_id != Current.user_id():
            raise fr.exc.Forbidden("Only the author can change this")
  • action names the action. fr.Action has a constant for each CRUD action: GET_MANY, GET_ONE, CREATE, UPDATE and DELETE.

  • Everyone may read. The scope already decides which posts they see.

  • Every write needs a user, and every user may create a post.

  • Every other write changes one post, and obj is that post. Only its author passes. A write without obj fails, so a new action is safe until you allow it.

Send the anonymous request again, and let Ben try to edit Anna’s draft:

curl -X POST http://127.0.0.1:8000/posts \
  -H 'Content-Type: application/json' \
  -d '{"title": "Hi", "content": "Anonymous"}'
# 401, "Log in to write"
curl -X PATCH http://127.0.0.1:8000/posts/1 \
  -H 'X-User-ID: 2' -H 'Content-Type: application/json' \
  -d '{"title": "Edited"}'
# 404

Ben gets 404, because the scope hides the draft from him: for this reader, the post does not exist. When he can see the post but may not change it, authorize answers 403. The next section shows this. Allow or refuse an action has more examples.

Publish a draft#

Publishing is an action, not a field edit. Add the action and a route for it to PostView:

    class Action(fr.Action):
        PUBLISH = "publish"

    @fr.post("/{id}/publish", status_code=200)
    async def publish(self, id: int) -> Post:
        post = await self.get_one(id)
        async with self.write_action(self.Action.PUBLISH, obj=post):
            if post.published:
                raise fr.exc.Conflict("Already published")
            post.published = True
        return post
  • Action lists the actions of the view. It inherits the five CRUD actions from fr.Action and adds PUBLISH. write_action takes only a name from this class. See Action names.

  • @fr.post adds a route to the view, beside the CRUD routes.

  • get_one loads the post through the scope. Another writer’s draft returns 404.

  • write_action first calls authorize("publish", post). The authorize method above lets only the author pass. When the block ends, Restly commits the change. If the block raises an exception, Restly does not commit.

  • The route returns the post. Its return type is the view’s model, Post, so Restly sends the post in the same shape as the CRUD routes, and /docs shows that shape for the new route.

Anna publishes her post. Then everyone can read it, and Ben gets 403 when he tries to edit it:

curl -X POST -H 'X-User-ID: 1' http://127.0.0.1:8000/posts/1/publish
# 200, with "published": true
curl http://127.0.0.1:8000/posts/1
# 200
curl -X PATCH http://127.0.0.1:8000/posts/1 \
  -H 'X-User-ID: 2' -H 'Content-Type: application/json' \
  -d '{"title": "Edited"}'
# 403, "Only the author can change this"
curl -X POST -H 'X-User-ID: 1' http://127.0.0.1:8000/posts/1/publish
# 409, "Already published"

Tell subscribers about a new post#

Readers want to hear about a new post. Send the message after the commit, so that subscribers never hear about a post that was not saved. Put this function above PostView:

async def notify_subscribers(post):
    print(f"New post: {post.title}")  # stand-in for an email or a webhook

Add this method to PostView:

    async def after_action_commit(self, action, new, old=None):
        if action == self.Action.PUBLISH:
            await notify_subscribers(new)

Restly calls after_action_commit after it commits a write. action is the name of the action, and new is the saved post. The hook runs after the commit, so an error in it cannot undo the publish. When after_action_commit raises shows how to handle such an error.

Anna writes a second post and publishes it. The server terminal prints New post: Second:

curl -X POST http://127.0.0.1:8000/posts \
  -H 'X-User-ID: 1' -H 'Content-Type: application/json' \
  -d '{"title": "Second", "content": "More"}'
curl -X POST -H 'X-User-ID: 1' http://127.0.0.1:8000/posts/2/publish

A side effect that must be saved together with the post, such as an audit row, goes in before_action_commit instead. See Run code before or after the commit.

Share the rules with comments#

Comments need the same rules:

  • A comment has an author.

  • A comment on a hidden draft stays hidden.

  • Only its author may edit or delete a comment.

The model and the schema get the same author field as posts. The model also gets a scope. Add relationship to the sqlalchemy.orm import, and replace Comment and CommentSchema with this code:

class Comment(Base):
    __tablename__ = "comment"

    id: Mapped[int] = mapped_column(primary_key=True)
    content: Mapped[str]
    post_id: Mapped[int] = mapped_column(ForeignKey("post.id"))
    author_id: Mapped[int] = mapped_column(insert_default=Current.user_id)
    post: Mapped[Post] = relationship()


class CommentClauses(fr.ClauseNamespace):
    model = Comment

    default_scope = fr.where_clause(Comment.post.has(PostClauses.default_scope))


class CommentSchema(fr.IDSchema):
    content: str
    post_id: fr.MustExist[int, Post]
    author_id: fr.ReadOnly[int]

A scope covers only its own model. The post scope hides a draft, but not the comments on it. So comments get their own scope:

  • post is a relationship from a comment to its post.

  • Comment.post.has(...) is true when the comment’s post matches the condition in the brackets.

  • The condition is the post scope, written without parentheses. Restly reads its Current.user_id each time it applies the comment scope.

Together: a comment is visible when its post is visible. Use a clause inside another condition explains this in more detail.

Views are normal Python classes. Move authorize from PostView into a base class, and put the base class below the app = FastAPI(...) line:

class AuthoredView(fr.AsyncRestView):
    async def authorize(self, action, obj=None, data=None):
        if action in (fr.Action.GET_MANY, fr.Action.GET_ONE):
            return
        if Current.user_id() is None:
            raise fastapi.HTTPException(401, "Log in to write")
        if action == fr.Action.CREATE:
            return
        if obj is None or obj.author_id != Current.user_id():
            raise fr.exc.Forbidden("Only the author can change this")

Both views inherit it:

@fr.include_view(app)
class PostView(AuthoredView):
    prefix = "/posts"
    model = Post
    schema = PostSchema
    # Action, publish and after_action_commit as above


@fr.include_view(app)
class CommentView(AuthoredView):
    prefix = "/comments"
    model = Comment
    schema = CommentSchema

Register only the views that have a model, not the base class. Share behavior with base views covers inheritance in more detail.

The comment table has a new column. Stop the server, delete blog.db, and start the server again. Then try the whole story again, with comments:

# Anna writes a post, and a note on her draft.
curl -X POST http://127.0.0.1:8000/posts \
  -H 'X-User-ID: 1' -H 'Content-Type: application/json' \
  -d '{"title": "Hello", "content": "World"}'
curl -X POST http://127.0.0.1:8000/comments \
  -H 'X-User-ID: 1' -H 'Content-Type: application/json' \
  -d '{"content": "Note to self", "post_id": 1}'
# 201, with "author_id": 1

# Ben does not see the note, because the post is a draft.
curl -H 'X-User-ID: 2' http://127.0.0.1:8000/comments
# 200, with "total_count": 0

# Anna publishes the post. Now Ben can comment on it.
curl -X POST -H 'X-User-ID: 1' http://127.0.0.1:8000/posts/1/publish
curl -X POST http://127.0.0.1:8000/comments \
  -H 'X-User-ID: 2' -H 'Content-Type: application/json' \
  -d '{"content": "Nice post", "post_id": 1}'
# 201, with "author_id": 2

# Anna cannot change Ben's comment.
curl -X PATCH http://127.0.0.1:8000/comments/2 \
  -H 'X-User-ID: 1' -H 'Content-Type: application/json' \
  -d '{"content": "Edited"}'
# 403, "Only the author can change this"

Test the rules#

The requests above check each rule by hand. Tests check them after every change. Install Restly’s test tools:

pip install "fastapi-restly[testing]"

Tests need their own database. Add import os to the imports, and let an environment variable choose the database:

fr.configure(
    async_database_url=os.environ.get("DATABASE_URL", "sqlite+aiosqlite:///blog.db")
)

Create conftest.py next to main.py. It sets the variable before it imports the app, because main.py configures Restly when it is imported. The tests use a database in memory, so each test run creates new tables:

import os

os.environ["DATABASE_URL"] = "sqlite+aiosqlite://"

import fastapi_restly as fr  # noqa: E402
from main import Base, app  # noqa: E402

fr.testing.configure_tests(app=app, base=Base, create_all=True)

configure_tests creates the tables in the test database, and gives each test a restly_client fixture. Restly rolls back everything a test writes when the test ends, so each test starts from an empty blog. Create test_main.py:

ANNA = {"X-User-ID": "1"}
BEN = {"X-User-ID": "2"}


def test_only_the_author_sees_a_draft(restly_client):
    post = restly_client.post(
        "/posts", json={"title": "Hello", "content": "World"}, headers=ANNA
    ).json()

    restly_client.get(f"/posts/{post['id']}", headers=ANNA)
    restly_client.get(f"/posts/{post['id']}", headers=BEN, assert_status_code=404)


def test_only_the_author_changes_a_published_post(restly_client):
    post = restly_client.post(
        "/posts", json={"title": "Hello", "content": "World"}, headers=ANNA
    ).json()
    restly_client.post(f"/posts/{post['id']}/publish", headers=ANNA)

    restly_client.patch(
        f"/posts/{post['id']}", json={"title": "Edited"}, headers=BEN, assert_status_code=403
    )
    restly_client.patch(f"/posts/{post['id']}", json={"title": "Edited"}, headers=ANNA)

The client checks the status code of every response. Without assert_status_code, it expects a status in the 2xx range. Run the tests:

pytest
test_main.py ..                                              [100%]
2 passed

The blog example has a test for every rule in this tutorial. Testing covers the fixtures, and apps that build their configuration in a factory.

The complete file#

Here is the blog with every change from this tutorial. The same file is the blog example:

import os
from contextlib import asynccontextmanager
from typing import Annotated

import fastapi
from fastapi import FastAPI, Header
from sqlalchemy import ForeignKey, or_
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

import fastapi_restly as fr

fr.configure(
    async_database_url=os.environ.get("DATABASE_URL", "sqlite+aiosqlite:///blog.db")
)


class Base(DeclarativeBase):
    pass


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


class Current(fr.ContextNamespace):
    user_id: fr.ContextParam[int | None]


def get_user_id(
    user_id: Annotated[int | None, Header(alias="X-User-ID")] = None,
) -> int | None:
    # Demo stand-in for real authentication. None means an anonymous reader.
    return user_id


app = FastAPI(lifespan=lifespan, dependencies=[Current.depends(user_id=get_user_id)])


class AuthoredView(fr.AsyncRestView):
    async def authorize(self, action, obj=None, data=None):
        if action in (fr.Action.GET_MANY, fr.Action.GET_ONE):
            return
        if Current.user_id() is None:
            raise fastapi.HTTPException(401, "Log in to write")
        if action == fr.Action.CREATE:
            return
        if obj is None or obj.author_id != Current.user_id():
            raise fr.exc.Forbidden("Only the author can change this")


class Post(Base):
    __tablename__ = "post"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    content: Mapped[str]
    published: Mapped[bool] = mapped_column(default=False)
    author_id: Mapped[int] = mapped_column(insert_default=Current.user_id)


class PostClauses(fr.ClauseNamespace):
    model = Post

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


class PostSchema(fr.IDSchema):
    title: str
    content: str
    published: fr.ReadOnly[bool]
    author_id: fr.ReadOnly[int]


async def notify_subscribers(post):
    print(f"New post: {post.title}")  # stand-in for an email or a webhook


@fr.include_view(app)
class PostView(AuthoredView):
    prefix = "/posts"
    model = Post
    schema = PostSchema

    class Action(fr.Action):
        PUBLISH = "publish"

    @fr.post("/{id}/publish", status_code=200)
    async def publish(self, id: int) -> Post:
        post = await self.get_one(id)
        async with self.write_action(self.Action.PUBLISH, obj=post):
            if post.published:
                raise fr.exc.Conflict("Already published")
            post.published = True
        return post

    async def after_action_commit(self, action, new, old=None):
        if action == self.Action.PUBLISH:
            await notify_subscribers(new)


class Comment(Base):
    __tablename__ = "comment"

    id: Mapped[int] = mapped_column(primary_key=True)
    content: Mapped[str]
    post_id: Mapped[int] = mapped_column(ForeignKey("post.id"))
    author_id: Mapped[int] = mapped_column(insert_default=Current.user_id)
    post: Mapped[Post] = relationship()


class CommentClauses(fr.ClauseNamespace):
    model = Comment

    default_scope = fr.where_clause(Comment.post.has(PostClauses.default_scope))


class CommentSchema(fr.IDSchema):
    content: str
    post_id: fr.MustExist[int, Post]
    author_id: fr.ReadOnly[int]


@fr.include_view(app)
class CommentView(AuthoredView):
    prefix = "/comments"
    model = Comment
    schema = CommentSchema

Exercises#

Write a test for each exercise.

  1. Add POST /posts/{id}/unpublish. Only the author may call it, and it fails with 409 on a draft.

  2. Record when a post was published. Add a published_at column, set it in the publish route, and return it as a read-only field.

  3. Let the author of a post delete any comment on it. Override authorize in CommentView, and call super().authorize(...) for the other cases. Load the post with await self.session.get(Post, obj.post_id), because obj.post does not load by itself in async code. Return related objects in a response explains why.

Next steps#

These pages cover the topics of this tutorial in more detail: