sqlitesqlalchemyfastapi

GET endpoint is not displaying data ins Swagger, getting only 'null', why?


FastApi is not outputting users. I am trying to get all of the users in my database table Users. However, whenever I try it using swagger, I get "null". I already checked if my table is populated and it is as you can see below:

sqlite> SELECT * FROM users;
1|creator|creator|creator|creator|$2b$12$.RvErMYWQ7buaWKh7l6JGeCxGtiX7D9z5zHLHxib61J4oJF/XWjP.|2024-12-06T21:27:27.678917
2|tim|tim@gmail.com|Tim|Try|$2b$12$3.8B78wv33qEQihcSBGak./7afLxCX2dPnEnTR/mf.npLRJ9ZCNEG|2024-12-06T23:15:35.844103

I have these two get endpoints, and the first one for getting info of one user works perfectly but the second one gives me null:

@router.get("/{username}")
def get_user(db: db_dependency, username: str):
    # SELECT * FROM Users WHERE user_id = user_id
    user = db.query(Users).filter(Users.username == username).first()
    return user


@router.get("/all")
def get_users(db: db_dependency):
    # SELECT * FROM Users
    users = db.query(Users).all()
    return users

I thought it might be something to do with the .all() but this other endpoint in different file works perfectly:

@router.get("/coffee-shops/all"):
def get_all_coffee_shops(db: db_dependency):
    # SELECT * FROM coffee_shops_table
    return db.query(CoffeeShops).all() 

I really don't get what is going on. Any thoughts?


Solution

  • The issue is how you've defined your endpoints. Since /{username} is defined before /all, your request is being captured by the first endpoint, so your app is trying to find a user with the username "all". There are two ways to solve this:

    1. Move the /all endpoint above /{username}.
    2. Change your URL structure. The more "standard" way to do this is that /users returns all users, and /users/{username} returns a single user.