-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat (full-stack): FastAPI + SQLModel tutorial
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
# FastAPI + SQLModel | ||
|
||
A simple and complete example of defining a REST API to insert and list users. | ||
~~~ | ||
fastapi dev users_api.py | ||
~~~ | ||
|
||
Examples derived from the tutorial: | ||
https://sqlmodel.tiangolo.com/tutorial/fastapi/simple-hero-api/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
from datetime import date | ||
from fastapi import FastAPI | ||
from sqlmodel import Field, Session, SQLModel, create_engine, select | ||
|
||
def parse_date(birthday_str: str | None) -> date | None: | ||
if birthday_str: | ||
return date.fromisoformat(birthday_str) | ||
return None | ||
|
||
class Users(SQLModel, table=True): | ||
email_id: str = Field(default=None, primary_key=True) | ||
name: str | ||
birthday: date | None = None | ||
|
||
POSTGRES_USER = "postgres" | ||
POSTGRES_PASSWORD = "postgres" | ||
POSTGRES_SERVER = "localhost" | ||
POSTGRES_PORT = "5431" | ||
POSTGRES_DB = "test" | ||
POSTGRES_URL = f"postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_SERVER}:{POSTGRES_PORT}/{POSTGRES_DB}" | ||
|
||
engine = create_engine(POSTGRES_URL, echo=True) | ||
|
||
app = FastAPI() | ||
|
||
@app.post("/users/") | ||
def create_user(user: Users): | ||
with Session(engine) as session: | ||
session.add(user) | ||
session.commit() | ||
session.refresh(user) | ||
return user | ||
|
||
@app.get("/users/") | ||
def read_users(): | ||
with Session(engine) as session: | ||
users = session.exec(select(Users)).all() | ||
return users |