Skip to content

Writing Queries

Let's update the post APIs one by one to use data stored in SQLite.

Listing All Posts

So far, the posts list has held our data. The list API will now use SQLAlchemy to retrieve stored posts.

Add these imports at the top of main.py:

main.py
from sqlalchemy import select

from connection import SessionFactory
from model import Post

Update get_posts_handler():

main.py
@app.get(
    "/posts",
    summary="List all posts",
    response_model=list[PostResponse],
)
def get_posts_handler():
    with SessionFactory() as session:  # ①
        statement = select(Post)  # ②
        posts = session.scalars(statement).all()  # ③
        return posts
  • ① Create a session with SessionFactory(). This time use a context manager, the with statement, so leaving the block closes the session automatically. This avoids forgetting close() and keeps the code concise.
  • ② select(Post) builds a query for the posts table.
  • ③ session.scalars(statement).all() runs it and returns a list of Post objects.

Start the server and call GET /posts in /docs. You should see the posts saved earlier. Check the terminal for the executed SELECT statement.

posts is a list of Post objects. With response_model=list[PostResponse], FastAPI reads attributes such as post.id, post.title, and post.content, converts each post to a JSON object, and returns a JSON array. SQLAlchemy objects with attributes matching the response model can therefore be returned directly.

Retrieving One Post

Instead of scanning the in-memory list, query the database using the path's post_id.

Update get_post_handler():

main.py
@app.get(
    "/posts/{post_id}",
    summary="Get a post",
    response_model=PostResponse,
)
def get_post_handler(post_id: int = Path(ge=1)):
    with SessionFactory() as session:
        statement = select(Post).where(Post.id == post_id)  # ①
        result = session.execute(statement)  # ②
        post = result.scalar()  # ③

    if post is None:  # ④
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Post not found.",
        )

    return post
  • ① Add where() to filter for a post whose id matches post_id.
  • ② Execute the query and assign its Result to result.
  • ③ scalar() returns the first value of the first row. A primary key query returns zero or one row, so this gives either a Post or None.
  • ④ Return 404 Not Found if the result is None.

Call GET /posts/{post_id} in /docs with a known ID, then a nonexistent one. Check for the post and a 404 respectively.

Searching Posts

Previously, we scanned titles and content in a list. Now put the search conditions in where() so the database performs the search.

Add or_ alongside select in the imports:

main.py
from sqlalchemy import or_, select

Update search_posts_handler(). Keep /posts/search registered before /posts/{post_id}.

main.py
@app.get(
    "/posts/search",
    summary="Search posts",
    response_model=list[PostResponse],
)
def search_posts_handler(topic: str = Query(min_length=2, max_length=20)):
    with SessionFactory() as session:
        statement = select(Post).where(
            or_(  # ②
                Post.title.contains(topic),  # ①
                Post.content.contains(topic),
            )
        )
        result = session.execute(statement)
        return result.scalars().all()  # ③
  • ① contains() builds a substring condition for the title and content.
  • ② or_() matches when either condition is true.
  • ③ scalars().all() returns the matches as a list of Post objects.

Call GET /posts/search with a word from a saved title or body. Matching posts appear in the list; no matches produces [].

Creating Posts

Instead of appending to a list, construct a Post from the request data and save it in the database.

Update create_post_handler():

main.py
@app.post(
    "/posts",
    summary="Create a post",
    response_model=PostResponse,
    status_code=status.HTTP_201_CREATED,
)
def create_post_handler(body: PostCreateRequest):
    with SessionFactory() as session:
        new_post = Post(title=body.title, content=body.content)  # ①
        session.add(new_post)  # ②
        session.commit()  # ③
        return new_post
  • ① Construct a Post from the title and content. The database assigns its ID.
  • ② Register it with the session using session.add().
  • ③ Commit to save it and populate new_post.id with the assigned ID.

Call POST /posts in /docs. Check for 201 Created and the new post's fields. Look for INSERT in the terminal, then call GET /posts to confirm it appears.

Updating Posts

Retrieve the post, then change its title or content through the ORM object.

Update update_post_handler():

main.py
@app.patch(
    "/posts/{post_id}",
    summary="Update a post",
    response_model=PostResponse,
)
def update_post_handler(
    post_id: int = Path(ge=1),
    body: PostUpdateRequest = Body(),
):
    with SessionFactory() as session:
        statement = select(Post).where(Post.id == post_id)  # ①
        result = session.execute(statement)
        post = result.scalar()

        if post is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Post not found.",
            )

        if body.title is not None:  # ②
            post.title = body.title
        if body.content is not None:
            post.content = body.content

        session.commit()  # ③
        return post
  • ① Query by post_id, returning 404 if the post is missing.
  • ② Change only fields whose request values are not None. Sending only a title leaves the content unchanged.
  • ③ Unlike a new object, the retrieved post is already tracked by the session. Commit its changes without adding it again.

Call PATCH /posts/{post_id} with {"title": "Updated title"} and check that only the title changed. The terminal should show an UPDATE statement.

Deleting Posts

Retrieve a post by ID and delete it from the database.

Update delete_post_handler():

main.py
@app.delete(
    "/posts/{post_id}",
    summary="Delete a post",
    status_code=status.HTTP_204_NO_CONTENT,
)
def delete_post_handler(post_id: int = Path(ge=1)):
    with SessionFactory() as session:
        statement = select(Post).where(Post.id == post_id)  # ①
        result = session.execute(statement)
        post = result.scalar()

        if post is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Post not found.",
            )

        session.delete(post)  # ②
        session.commit()  # ③
  • ① Retrieve the Post, or return 404 if missing.
  • ② session.delete(post) marks it for deletion. Deletions may also affect related objects, such as a user's orders. If a relationship configures cascading deletes, the session processes those too. Committing executes the deletion and finalizes it.
  • ③ Commit the deletion. A successful response uses 204 No Content without a body.

Call DELETE /posts/{post_id} and check for 204 and the terminal's DELETE statement. Retrieving that ID afterward should return 404.

Check Your Understanding

Decide whether each statement is true or false.

  1. Querying by a complete primary key returns at most one row.
  2. All conditions joined by OR must be true for a match.
  3. An automatically generated primary key can be omitted when constructing a new object.
  4. An object queried through a session must be added to that session again after changing an attribute.
  5. Calling the session's delete method immediately commits the deletion.
Answers and Explanations
  1. True — A primary key uniquely identifies a row.
  2. False — OR requires at least one condition to be true.
  3. True — The database assigns the value when saving.
  4. False — The session already tracks changes to objects it retrieved.
  5. False — Deletion is finalized by committing.