So, I have been trying to learn Python Full-Stack web development using fastAPI. Most of my website works properly but I am having trouble with sending the list of Query using FASTAPI.
I get this error.
{ "detail": [ { "loc": [ "path", "id" ], "msg": "value is not a valid integer", "type": "type_error.integer" } ] }
This is my FastAPI router code.
@router.get("/get/all", response_model=List[ComicViewable]) def list_of_all_comics(db: Session = Depends(get_db)): comics = comic_func.list_comics(db) if not comics: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No Comics have been created.") return comics
This is the function that returns the list of all comics stored in the database.
def list_comics(db: Session): return db.query(Comic).all()
and my pydantic response class
class ComicViewable(BaseModel): title: str description: str date_created: date is_ongoing: bool is_public: bool class Config: orm_mode = True
I don’t know what I’m doing wrong here. I have read the FASTAPI help documentation and in there they also use List[PydanticClassName]
to return a list of database queries, but for some reason, it is not working for me.
EDIT:
So, I checked the response of list_comics()
function. It does indeed return the right response. I tested it by printing the comic.title
in a Jinja2 template.
{% block content %} <div class="ui segment"> <div class="two column middle aligned grid"> {% for comic in comics %} <h2>{{comic.title}}</h2> {% endfor %} </div> </div> {% endblock %}
So the error seems to be happening either in the pydantic class model or FastAPI router.
Advertisement
Answer
This solution suggested by @MatsLindh solved it.
That is not the endpoint being loaded; the error message complains about an endpoint with id set (i.e. /get/{id} or something similar). You probably have that endpoint defined before your /get/all endpoint, and since all is not an integer, it throws the given error.
This solved my problem, As I had another endpoint before the /get/all
endpoint named as /get/{id}
which was causing the error.