Skip to content
Advertisement

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, 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": "johndoe@gmail.com",
"gpa": 5.0
}

is there a way to check the request body for the above endpoint?

Advertisement

Answer

This is normally handled by using pydantic to validate the schema before doing anything to the database at the ORM level. I highly recommend you use the FASTApi project generator and look at how it plugs together there: it’s (currently) the easiest way to see the fastapi-> pydantic -> [orm] -> db model as FASTApi’s author envisgaes it.

If you’re not using an ORM, nothing stops you building an ‘ORM lite’ where the post data is parsed into a pydantic object (with .from_dict) and then you manually run the right queries. This error will propagate up to the endpoint function, where you can catch it and return your error as you want to. Note that you can also do the validation yourself, any way you choose.

In general you raise an HTTPException if you need to signal that it failed.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement