FastAPI POST not validating missing fields with SQLModel like it does with BaseModel subclass #1665
-
First Check
Commit to Help
Example Codefrom sqlmodel import Field, SQLModel, create_engine
from datetime import datetime
from fastapi import FastAPI
from sqlmodel import Session
from pydantic import BaseModel
import uuid
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
class HeroBase(BaseModel):
name: str
power: str
weakness: str
class Hero(SQLModel, table=True):
id: str = Field(default=None, primary_key=True)
name: str
power: str
weakness: str
api = FastAPI()
@api.on_event("startup")
async def startup_event():
create_db_and_tables()
@api.post("/heroes")
async def create_hero(hero: Hero):
with Session(engine) as session:
hero.id = str(uuid.uuid4())
session.add(hero)
session.commit()
session.refresh(hero)
return heroDescriptionbased on these docs: https://sqlmodel.tiangolo.com/tutorial/fastapi/simple-hero-api/ if you run the above code and try to post the following {
"name": "hero"
}you should expect to see {
"detail": [
{
"type": "missing",
"loc": [
"body",
"power"
],
"msg": "Field required",
"input": {
"name": "hero"
}
},
{
"type": "missing",
"loc": [
"body",
"weakness"
],
"msg": "Field required",
"input": {
"name": "hero"
}
}
]
}in fact, when you switch the body python type for that API from but if you run it with which means fastapis built in validation is not working allowing the model to be read even with missing fields causing the database error. which directly contradicts this line from the docs
Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.27 Python VersionPython 3.13.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
You shouldn't use table-model (with See: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance |
Beta Was this translation helpful? Give feedback.
You shouldn't use table-model (with
table=True) for validation. Create base class with common fields (excluding relationships) and inherit input validation model and table-model from that base class.See: https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/#multiple-models-with-inheritance