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: float
The 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]",
}
1
Oct 02 '21 edited Oct 02 '21
If you're actually interested in understanding what's missing in your request then I'd suggest digging into the pydantic documentation and looking into validators. You can use validators to raise specific errors based on fields that are missing.
From what I can gather from your D- formatting effort in your code snippets it looks like your request model could be missing one or more required parameters.
You don't need to work counterintuitively. The problem looks to be with your request data, not the model.
If you're not using the automatically generated swagger documentation to test your API, you should. If you're using curl, then you need to make sure that your accept header is application/json. If you were using the automatically generated swagger documentation you would see this in the command that it shows you it executes.
4
u/hexarobi Oct 02 '21
def create_student(student: schemas.StudentCreateThe typehint here controls the validation. Assuming StudentCreate is a Pydantic model with a `gpa` field defined, then any requests missing that field will return an appropriate error auto-magically.
https://fastapi.tiangolo.com/tutorial/path-params/