fromtypingimportList,OptionalfromfastapiimportFastAPI,HTTPExceptionfromsqlmodelimportField,Session,SQLModel,create_engine,select# Code here omitted 👈@app.get("/heroes/{hero_id}",response_model=HeroRead)defread_hero(hero_id:int):withSession(engine)assession:hero=session.get(Hero,hero_id)ifnothero:raiseHTTPException(status_code=404,detail="Hero not found")returnhero
👀 Full file preview
fromtypingimportList,OptionalfromfastapiimportFastAPI,HTTPExceptionfromsqlmodelimportField,Session,SQLModel,create_engine,selectclassHeroBase(SQLModel):name:str=Field(index=True)secret_name:strage:Optional[int]=Field(default=None,index=True)classHero(HeroBase,table=True):id:Optional[int]=Field(default=None,primary_key=True)classHeroCreate(HeroBase):passclassHeroRead(HeroBase):id:intsqlite_file_name="database.db"sqlite_url=f"sqlite:///{sqlite_file_name}"connect_args={"check_same_thread":False}engine=create_engine(sqlite_url,echo=True,connect_args=connect_args)defcreate_db_and_tables():SQLModel.metadata.create_all(engine)app=FastAPI()@app.on_event("startup")defon_startup():create_db_and_tables()@app.post("/heroes/",response_model=HeroRead)defcreate_hero(hero:HeroCreate):withSession(engine)assession:db_hero=Hero.model_validate(hero)session.add(db_hero)session.commit()session.refresh(db_hero)returndb_hero@app.get("/heroes/",response_model=List[HeroRead])defread_heroes():withSession(engine)assession:heroes=session.exec(select(Hero)).all()returnheroes@app.get("/heroes/{hero_id}",response_model=HeroRead)defread_hero(hero_id:int):withSession(engine)assession:hero=session.get(Hero,hero_id)ifnothero:raiseHTTPException(status_code=404,detail="Hero not found")returnhero
For example, to get the hero with ID 2 we would send a GET request to:
Then, because FastAPI already takes care of making sure that the hero_id is an actual integer, we can use it directly with Hero.get() to try and get one hero by that ID.
But if the integer is not the ID of any hero in the database, it will not find anything, and the variable hero will be None.
So, we check it in an if block, if it's None, we raise an HTTPException with a 404 status code.
And to use it, we first import HTTPException from fastapi.
This will let the client know that they probably made a mistake on their side and requested a hero that doesn't exist in the database.
fromtypingimportList,OptionalfromfastapiimportFastAPI,HTTPExceptionfromsqlmodelimportField,Session,SQLModel,create_engine,select# Code here omitted 👈@app.get("/heroes/{hero_id}",response_model=HeroRead)defread_hero(hero_id:int):withSession(engine)assession:hero=session.get(Hero,hero_id)ifnothero:raiseHTTPException(status_code=404,detail="Hero not found")returnhero
👀 Full file preview
fromtypingimportList,OptionalfromfastapiimportFastAPI,HTTPExceptionfromsqlmodelimportField,Session,SQLModel,create_engine,selectclassHeroBase(SQLModel):name:str=Field(index=True)secret_name:strage:Optional[int]=Field(default=None,index=True)classHero(HeroBase,table=True):id:Optional[int]=Field(default=None,primary_key=True)classHeroCreate(HeroBase):passclassHeroRead(HeroBase):id:intsqlite_file_name="database.db"sqlite_url=f"sqlite:///{sqlite_file_name}"connect_args={"check_same_thread":False}engine=create_engine(sqlite_url,echo=True,connect_args=connect_args)defcreate_db_and_tables():SQLModel.metadata.create_all(engine)app=FastAPI()@app.on_event("startup")defon_startup():create_db_and_tables()@app.post("/heroes/",response_model=HeroRead)defcreate_hero(hero:HeroCreate):withSession(engine)assession:db_hero=Hero.model_validate(hero)session.add(db_hero)session.commit()session.refresh(db_hero)returndb_hero@app.get("/heroes/",response_model=List[HeroRead])defread_heroes():withSession(engine)assession:heroes=session.exec(select(Hero)).all()returnheroes@app.get("/heroes/{hero_id}",response_model=HeroRead)defread_hero(hero_id:int):withSession(engine)assession:hero=session.get(Hero,hero_id)ifnothero:raiseHTTPException(status_code=404,detail="Hero not found")returnhero
And because we are using the response_model with HeroRead, it will be validated, documented, etc.
fromtypingimportList,OptionalfromfastapiimportFastAPI,HTTPExceptionfromsqlmodelimportField,Session,SQLModel,create_engine,select# Code here omitted 👈@app.get("/heroes/{hero_id}",response_model=HeroRead)defread_hero(hero_id:int):withSession(engine)assession:hero=session.get(Hero,hero_id)ifnothero:raiseHTTPException(status_code=404,detail="Hero not found")returnhero
👀 Full file preview
fromtypingimportList,OptionalfromfastapiimportFastAPI,HTTPExceptionfromsqlmodelimportField,Session,SQLModel,create_engine,selectclassHeroBase(SQLModel):name:str=Field(index=True)secret_name:strage:Optional[int]=Field(default=None,index=True)classHero(HeroBase,table=True):id:Optional[int]=Field(default=None,primary_key=True)classHeroCreate(HeroBase):passclassHeroRead(HeroBase):id:intsqlite_file_name="database.db"sqlite_url=f"sqlite:///{sqlite_file_name}"connect_args={"check_same_thread":False}engine=create_engine(sqlite_url,echo=True,connect_args=connect_args)defcreate_db_and_tables():SQLModel.metadata.create_all(engine)app=FastAPI()@app.on_event("startup")defon_startup():create_db_and_tables()@app.post("/heroes/",response_model=HeroRead)defcreate_hero(hero:HeroCreate):withSession(engine)assession:db_hero=Hero.model_validate(hero)session.add(db_hero)session.commit()session.refresh(db_hero)returndb_hero@app.get("/heroes/",response_model=List[HeroRead])defread_heroes():withSession(engine)assession:heroes=session.exec(select(Hero)).all()returnheroes@app.get("/heroes/{hero_id}",response_model=HeroRead)defread_hero(hero_id:int):withSession(engine)assession:hero=session.get(Hero,hero_id)ifnothero:raiseHTTPException(status_code=404,detail="Hero not found")returnhero