Tutorial: Build a Blog API#
In this tutorial we build the API for a blog: posts, and comments on posts. At the end you have a running API with ten routes, documented in the browser, with filtering and paging. You also know what Restly adds to FastAPI. The tutorial takes about twenty minutes. Add Authors and Drafts continues from the file you build here.
Install#
Python 3.11 or later is required. Install Restly with FastAPI’s development server, and the async SQLite driver:
pip install "fastapi-restly[standard]" aiosqlite
Create and list posts#
A blog needs posts. Create main.py. The first block is setup: it opens the
database, declares the base class for the models, and creates the tables when
the app starts. You do not change this block again in this tutorial.
from contextlib import asynccontextmanager
from fastapi import FastAPI
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
import fastapi_restly as fr
fr.configure(async_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
app = FastAPI(lifespan=lifespan)
Models explains the base class.
Below it, add a model and a view:
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)
@fr.include_view(app)
class PostView(fr.AsyncRestView):
prefix = "/posts"
model = Post
Post is a normal SQLAlchemy model. PostView is the Restly part:
prefix is the URL, model is the
table, and fr.include_view adds
the view’s routes to the app. Start the server:
fastapi dev main.py
Open http://127.0.0.1:8000/docs. The posts resource has five routes:
Method |
Path |
Action |
|---|---|---|
|
|
List posts |
|
|
Create a post |
|
|
Get one post |
|
|
Update one post |
|
|
Delete one post |
Each route shows its request and response schema. Restly generated them from
the model: PostCreate for the body of POST, PostResponse for a post in
a response, and so on. Create a post with the Try it out button, or with
curl from a second terminal:
curl -X POST http://127.0.0.1:8000/posts \
-H 'Content-Type: application/json' \
-d '{"title": "Hello", "content": "My first post"}'
The response is 201 Created with the stored post:
{"id": 1, "title": "Hello", "content": "My first post", "published": false}
published was not in the request, so the column default applied. The list
route returns the post in a page:
curl http://127.0.0.1:8000/posts
{
"data": [{"id": 1, "title": "Hello", "content": "My first post", "published": false}],
"total_count": 1,
"page": 1,
"page_size": 50,
"total_pages": 1
}
This is what Restly adds to FastAPI: a model and a four-line view class give a complete, documented resource. CRUD Routes describes the full contract of these routes.
Find posts#
Readers want to find posts. The list route already filters, sorts and pages through URL parameters, so this step adds no code. Create a second post, and mark it as published:
curl -X POST http://127.0.0.1:8000/posts \
-H 'Content-Type: application/json' \
-d '{"title": "Second", "content": "Now published", "published": true}'
Then try these:
curl 'http://127.0.0.1:8000/posts?published=true'
# only the second post, with "total_count": 1
curl 'http://127.0.0.1:8000/posts?title__icontains=hello'
# only the first post
curl 'http://127.0.0.1:8000/posts?sort=-id&page=1&page_size=10'
# both posts, newest first
A field name filters on equality. A suffix such as __icontains chooses
another operator. sort takes field names, with - for descending order.
Filtering, Sorting & Pagination lists every
operator and the paging settings.
The complete file#
Here is main.py with everything from this tutorial. The same file is the
first stage of the blog example, and the test suite runs it.
from contextlib import asynccontextmanager
from fastapi import FastAPI
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
import fastapi_restly as fr
fr.configure(async_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
app = FastAPI(lifespan=lifespan)
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)
@fr.include_view(app)
class PostView(fr.AsyncRestView):
prefix = "/posts"
model = Post
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"))
class CommentSchema(fr.IDSchema):
content: str
post_id: fr.MustExist[int, Post]
@fr.include_view(app)
class CommentView(fr.AsyncRestView):
prefix = "/comments"
model = Comment
schema = CommentSchema
Next steps#
Add Authors and Drafts continues with this file. It adds the current user, drafts that only their author can see, a publish action, and rules for who may change a post.
These pages go deeper into what this tutorial used:
Models: the base class, and the defaults that
fr.ModelDefaultsadds to it, such as datetimes with a time zoneCRUD Routes: the default CRUD contract and the view settings
How Restly generates a schema: what Restly generates from a model, and when to write a schema
Relationships: checked references and nested objects
Filtering, Sorting & Pagination: every filter operator, sorting, and paging
Testing: test the API, with a rollback after each test
Deploying: Alembic migrations instead of
async_create_allViews: views without a model, and the sync
RestView
Comment on posts#
Readers want to comment on a post. A comment belongs to one post, so the model has a foreign key. Add the model and its view at the end of the file:
The server restarts by itself when you save the file, and the comments resource gets the same five routes. Now comment on a post that does not exist:
The status is
409 Conflict. The database refused the row, and Restly turned the database error into an HTTP error. That is correct, but it comes after the insert was tried, and it does not say which field was wrong. A missing post should answer404, and name the field. So comments need to check the post before the insert.Until now, Restly generated the schema from the model. For comments we write the schema ourselves, and mark
post_idas a checked reference. Put the schema aboveCommentView, and point the view at it:A
schemasays which fields the API accepts and returns.fr.IDSchemaadds theidfield as read-only, so you do not declare it.fr.MustExist[int, Post]is a plain integer in JSON, and Restly checks that aPostwith that id exists before it writes the comment. Send the same request again:The status is
404 Not Found, and the message names the field. A comment on post1is accepted:Relationships covers references in more detail, including nested objects in responses.