Skip to content

Commit

Permalink
feat (full-stack): FastAPI + SQLModel tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
santanche committed Aug 11, 2024
1 parent af67d96 commit bff1538
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
9 changes: 9 additions & 0 deletions full-stack/3-fastapi/README.md
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/
38 changes: 38 additions & 0 deletions full-stack/3-fastapi/users_api.py
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

0 comments on commit bff1538

Please sign in to comment.