r/FastAPI • u/WING1123 • Oct 02 '21
Question How to validate request body in FastAPI?
I understand that if the incoming request body misses certain required keys, FastAPI will automatically raise 422 unserviceable entity error. However, is there a way to check the incoming request body by myself in the code and raise a 400 bad request if if misses required names?
For example, let's say I have this model and schema:
class Student(Base):
__tablename__ = "student"
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True, nullable=False)
email = Column(String(100), unique=True, nullable=False)
gpa = Column(Float, unique=False, nullable=False)class StudentBase(BaseModel):
name: str
email: str
gpa: floatThe POST endpoint to create a new row is:
@app.post("/student", dependencies=[Depends(check_request_header)],
response_model=schemas.Student, status_code=200)
def create_student(student: schemas.StudentCreate, db: Session = Depends(get_db)):
db_student = crud.get_student(db, student=student)
if db_student:
raise HTTPException(status_code=400, detail="This student has already been created.")
return crud.create_student(db=db, student=student)The expected request body should be something like this:
{
"name": "johndoe",
"email": "[email protected]",
"gpa": 5.0
}is there a way to check the request body for the above endpoint? For example, raise a bad request exception when the request body misses a name:
{
"name": "johndoe",
"email": "[email protected]",
}
