Coverage for docs_src/tutorial/fastapi/response_model/tutorial001.py: 100%
29 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-16 00:02 +0000
« 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
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
12sqlite_file_name = "database.db" 1abcdefghijklm
13sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdefghijklm
15connect_args = {"check_same_thread": False} 1abcdefghijklm
16engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abcdefghijklm
19def create_db_and_tables(): 1abcdefghijklm
20 SQLModel.metadata.create_all(engine) 1nopqrstuvwxyz
23app = FastAPI() 1abcdefghijklm
26@app.on_event("startup") 1abcdefghijklm
27def on_startup(): 1abcdefghijklm
28 create_db_and_tables() 1nopqrstuvwxyz
31@app.post("/heroes/", response_model=Hero) 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
40@app.get("/heroes/", response_model=list[Hero]) 1abcdefghijklm
41def read_heroes(): 1abcdefghijklm
42 with Session(engine) as session: 1nopqrstuvwxyz
43 heroes = session.exec(select(Hero)).all() 1nopqrstuvwxyz
44 return heroes 1nopqrstuvwxyz