DEV Community

Fiyinfoluwa Ojo
Fiyinfoluwa Ojo

Posted on

GET /items: Retrieving All Records from a Database with FastAPI & SQLAlchemy

What is a GET Endpoint?

A GET endpoint retrieves data from your database and
returns it to the client. It's the R in CRUD : Read.

Today I built GET /items : an endpoint that fetches
all stored items and returns them in a consistent JSON shape.

The Endpoint

@app.get("/items")
def get_all_items():
    db = SessionLocal()
    items = db.query(Item).all()
    db.close()
    return {
        "status": "success",
        "count": len(items),
        "data": [
            {
                "id": item.id,
                "name": item.name,
                "description": item.description,
                "price": float(item.price),
                "created_at": str(item.created_at)
            }
            for item in items
        ]
    }
Enter fullscreen mode Exit fullscreen mode

Why This Response Shape?

Instead of just returning a raw array, I wrapped the
response in a consistent JSON shape:

{
  "status": "success",
  "count": 5,
  "data": [...]
}

Enter fullscreen mode Exit fullscreen mode

This tells the client:

  • Whether the request succeeded
  • How many records were returned
  • The actual data

This is how production APIs are structured.

Testing with Postman

Postman lets you test API endpoints without writing
any frontend code. Just set the method to GET,
paste the URL and hit Send.

All 5 items returned with a 200 OK status. ✅

Lessons Learned

A good API response is more than just data.
It's data with context. Always wrap your responses
in a consistent shape, so clients know exactly
what to expect every time.

Day 7 done. 23 more to go.

GDGoCBowen30dayChallenge

Top comments (0)