Summary
NotesThat’s all there is to it! As you’ll see, we’ll always start by building APIs first and then utilise them for web views.
This approach helps build a habit of separating logic from presentation and makes life easy if you want to two to run as separate applications.
Moving forward, the examples use three blog posts with Lorem Ipsum Latin text. You can add your own via Swagger, or use the small seed script included in the example code, which adds three sample posts if the table is empty:
db/seed.pypython
"""Add three sample blog posts. Run with: python -m db.seed"""
from sqlmodel import Session, select
from db.db import engine
from db.schemas.blog_schemas import BlogPost
LOREM = ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris "
"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit "
"esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt "
"in culpa qui officia deserunt mollit anim id est laborum.")
SAMPLES = [
("Lorem ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit."),
("Ut enim ad minim", "Ut enim ad minim veniam, quis nostrud exercitation."),
("Duis aute irure", "Duis aute irure dolor in reprehenderit in voluptate."),
]
def seed():
with Session(engine) as session:
if session.exec(select(BlogPost)).first():
print("Database already has blog posts, nothing to do.")
return
for title, teaser in SAMPLES:
session.add(BlogPost(title=title, teaser=teaser, content=LOREM,
cover_image="/static/img/post-bg.jpg", published=True))
session.commit()
print(f"Added {len(SAMPLES)} blog posts.")
if __name__ == "__main__":
seed()python -m db.seedCode
The example code at this point is tagged ch03-crud-apis in the example repository. To get it:
git clone https://github.com/codewalkr/fastapi-example-for-you.git
cd fastapi-example-for-you
git checkout ch03-crud-apis