Home > Back-end >  FastAPI - return Single element in from Database
FastAPI - return Single element in from Database

Time:10-11

I have 2 api endpoints. This one returns a list of all my users.

@app.get("/entity/", response_model=List[schemas.Userentity])
def read_entities(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_entities(db, skip=skip, limit=limit)
    return users

def get_entities(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Userentity).offset(skip).limit(limit).all()

This works fine. See the data:

[
{
"id": "89f8a844-a30e-41b2-947d-6eb0fcadb1bf",
"email": "[email protected]",
"first_name": "xxx",
"last_name": "xxx",
"username": "schoedeld",
"created_timestamp": "1633711745164"
},
{
"id": "abd6bb6b-ad80-431c-9f64-d9e651638f4c",
"email": "[email protected]",
"first_name": "xxx",
"last_name": "xxx",
"username": "xxx",
"created_timestamp": "1633711733338"
},
{
"id": "ad0bd5ca-5aed-4d7f-a6ac-2620f2133685",
"email": "[email protected]",
"first_name": "fsdfs",
"last_name": "fsdfs",
"username": "testadmin",
"created_timestamp": "1633710812666"
}
]

Here I have an endpoint to return a single user:

I could return a List with a single element, but I would like to return a single value, so I updated my endpoint to this:

@app.get("/entity/{id}", response_model=schemas.Userentity)
def read_entity(id: str, db: Session = Depends(get_db)):
    user = crud.get_entity(db, id=id)
    return user

def get_entity(db: Session, id: str):
    return db.query(models.Userentity).filter_by(id=id)

This results in the following error:

pydantic.error_wrappers.ValidationError: 6 validation errors for Userentity
response -> id
  field required (type=value_error.missing)
response -> email
  field required (type=value_error.missing)
response -> first_name
  field required (type=value_error.missing)
response -> last_name
  field required (type=value_error.missing)
response -> username
  field required (type=value_error.missing)
response -> created_timestamp
  field required (type=value_error.missing)

I am pretty new to FastAPI and do not understand why this error happens, can anyone help me and explain what I am doing wrong here?

CodePudding user response:

You're never actually running your SQLAlchemy query, so you're returning the query itself:

return db.query(models.Userentity).filter_by(id=id)

Instead you should make SQLAlchemy run your query by either:

# raise an exception if not exactly one row is returned (so more than one or zero)
return db.query(models.Userentity).filter_by(id=id).one()

# Either one or zero rows - return `None` if user wasn't found
return db.query(models.Userentity).filter_by(id=id).one_or_none()

# Return None if user isn't found, otherwise return the first row
# (multiple rows isn't an error)
return db.query(models.Userentity).filter_by(id=id).first()

Next time attach set debugger breakpoint at the return call from your view function (or at least print the value), and you can see exactly what you're trying to return to FastAPI for serialization.

  • Related