Getting user by ID

  • The path operation should never return the password

@app.get("/users/{id}", response_model=schemas.UserOut)
def get_user(id: int, db: Session = Depends(get_db)):

    user = db.query(models.User).filter(models.User.id == id).first()

    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User with id: {id} does not exist")

    return user
  • It will return the user without the password because of the response_model

  • The user will be searched by ID in the database

  • If this is not found, it will raise a HTTP404

  • If it does find it, it will return the ID, email, and created_at field

{
    "id": 5,
    "email": "123@gmail.com",
    "created_at": "2022-07-29T10:06:18.287097+03:00"
}

Last updated