Coverage for docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py: 100%

29 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-16 00:02 +0000

1from fastapi import FastAPI 1abcdefghijklm

2from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcdefghijklm

3 

4 

5class Hero(SQLModel, table=True): 1abcdefghijklm

6 id: int | None = Field(default=None, primary_key=True) 1abcdefghijklm

7 name: str = Field(index=True) 1abcdefghijklm

8 secret_name: str 1abcdefghijklm

9 age: int | None = Field(default=None, index=True) 1abcdefghijklm

10 

11 

12sqlite_file_name = "database.db" 1abcdefghijklm

13sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdefghijklm

14 

15connect_args = {"check_same_thread": False} 1abcdefghijklm

16engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abcdefghijklm

17 

18 

19def create_db_and_tables(): 1abcdefghijklm

20 SQLModel.metadata.create_all(engine) 1nopqrstuvwxyz

21 

22 

23app = FastAPI() 1abcdefghijklm

24 

25 

26@app.on_event("startup") 1abcdefghijklm

27def on_startup(): 1abcdefghijklm

28 create_db_and_tables() 1nopqrstuvwxyz

29 

30 

31@app.post("/heroes/") 1abcdefghijklm

32def create_hero(hero: Hero): 1abcdefghijklm

33 with Session(engine) as session: 1nopqrstuvwxyz

34 session.add(hero) 1nopqrstuvwxyz

35 session.commit() 1nopqrstuvwxyz

36 session.refresh(hero) 1nopqrstuvwxyz

37 return hero 1nopqrstuvwxyz

38 

39 

40@app.get("/heroes/") 1abcdefghijklm

41def read_heroes(): 1abcdefghijklm

42 with Session(engine) as session: 1nopqrstuvwxyz

43 heroes = session.exec(select(Hero)).all() 1nopqrstuvwxyz

44 return heroes 1nopqrstuvwxyz