fastapi orm code example

Example 1: fastapi

pip install fastapi
pip install uvicorn # ASGI server
pip install starlette # lightweight ASGI framework/toolkit
pip install pydantic # Data validation and type annotations
# OR
pip install fastapi uvicorn starlette pydantic

Example 2: insert into relational database fastapi

def create_nested_family(db: Session, family: schemas.NestedFamilyCreate):
    # split information in family and members
    family_data = family.dict()
    member_data = family_data.pop('members', None)   # ToDo: handle error if no members
    db_family = models.Family(**family_data)
    db.add(db_family)
    db.commit()
    db.refresh(db_family)
    # get family_id
    family_id = db_family.id
    # add members
    for m in member_data:
        m['family_id'] = family_id
        db_member = models.Member(**m)
        db.add(db_member)
        db.commit()
        db.refresh(db_member)
    return db_family