I’m developing a FastAPI application and using SQLAlchemy to interact with a MySQL database. I have a route to fetch a post by its ID, but I’m encountering an ObjectNotExecutableError when executing the query. Everything was working fine before I updated my Python, but now I’m forced to use the text function and I’m encountering issues.
The error I get after using text is pydantic_core.ValidationError. Here’s the relevant part of my code with text in line 5:
@router.get("/posts/{id}", tags=["posts"], summary="get a post by its id")
def get_post_by_id(id:int) -> Post:
connector=Connect(user,password, host, port, dbname)
connection=connector.eng()
result = connection.execute(text(f"SELECT * FROM Posts WHERE Id = {id}"))
if result != None:
connection.close()
return next(Post(id=row.Id, title=row.Title, author_id=row.Author_Id) for row in result if row.Id == id)
else:
raise (HTTPException(status_code=400, detail="Can not find the inserted id"))
This is the full error after using text:
pydantic_core._pydantic_core.ValidationError: 1 validation error for Post
author_id
Input should be a valid string [type=string_type, input_value=0, input_type=int]
For further information visit https://errors.pydantic.dev/2.7/v/string_type
Nasima Dadgar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.