Retrieving all model objects with SQLModel

2 min read

Alright, we've got our single blog retrieval working like a charm, but what if someone wants to see ALL the amazing blog posts on our platform? Time to build the classic list endpoint that every API needs!

Again, let's starts from grounds up. First, let's build the crud service at database/crud/blog.py:

from typing import List

# pre-existing functions 


def get_all_blogs(db: Session) -> List[Blog]:
    statement = select(Blog)
    result = db.exec(statement)
    return result.all()

Notice that List[Blog] type hint? That tells FastAPI (and your IDE) exactly what we're returning.

SQLModel Simplicity: The select(Blog) statement without any .where() clause means "give me everything." The .all() method returns all results as a list.

The Route Layer

Now let's update our apis/v1/blog.py:


@router.get("/blogs", response_model=List[ShowBlog])
def get_blogs(db: Session = Depends(get_db)):
    blogs = get_all_blogs(db)
    if not blogs:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No blogs found")
    return blogs

Notice something important here? The /blogs route comes AFTER the /blogs/{slug} route. This is crucial! If we put the list route first, FastAPI would think "blogs" is a slug parameter and try to find a blog with slug="blogs".

Always put your specific routes before your generic ones. It's like having a bouncer at a club - specific VIPs get checked first!

Response Model: List[ShowBlog] tells FastAPI to serialize each blog in the list using our ShowBlog schema. 

Error Handling: We're checking if the blogs list is empty and throwing a 404. But wait... is this actually right? 🤔

Honestly, returning a 404 for an empty blog list feels weird to me. An empty list is still a valid response - it just means "hey, no blogs yet!" A 404 should mean "this endpoint doesn't exist" not "this endpoint exists but has no data."

I'd probably do this instead:

@router.get("/blogs", response_model=List[ShowBlog])
def get_blogs(db: Session = Depends(get_db)):
    return get_all_blogs(db)

This endpoint will become a nightmare when you have thousands of blogs. No pagination, no limits, just raw dumping of everything. Our database will cry, our users will wait, and our server will probably catch fire. Pagination could be a nice topic for performance optimization. Let's not hurry and put too much of content in 1 tutorial. So, bye bye for now.

FastAPITutorial

My priority is to help build a production-ready application using FastAPI

I prioritize quality over simplicity. Our challenging approach ensures you're prepared for real-world development.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated with our latest tutorials and resources.

© Copyright 2022-2025 Team FastAPITutorial. All rights reserved.