28
loading...
This website collects cookies to deliver better user experience
python -m venv friends
source friends/scripts/activate
pip install fastapi
pip install gunivorn
from fastapi import FastAPI
#initailize FastApi instance
app = FastAPI()
#define endpoint
@app.get("/")
def home():
return {"Ahoy": "Captain"}
uvicorn main:app --reload
pip install SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
#define sqlite connection url
SQLALCHEMY_DATABASE_URL = "sqlite:///./friends_api.db"
# create new engine instance
engine = create_engine(SQLALCHEMY_DATABASE_URL)
# create sessionmaker
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
models.py
. We are going to define our models here.from sqlalchemy import Column, Integer, String
from .db import Base
# model/table
class Friend(Base):
__tablename__ = "friend"
# fields
id = Column(Integer,primary_key=True, index=True)
first_name = Column(String(20))
last_name = Column(String(20))
age = Column(Integer)
#add this to main.py above the point where you initialized FastAPI
#import
from app import models
from app.db import engine
#create the database tables on app startup or reload
models.Base.metadata.create_all(bind=engine)
from sqlalchemy.orm import Session
"""
Session manages persistence operations for ORM-mapped objects.
Let's just refer to it as a database session for simplicity
"""
from app.models import Friend
def create_friend(db:Session, first_name, last_name, age):
"""
function to create a friend model object
"""
# create friend instance
new_friend = Friend(first_name=first_name, last_name=last_name, age=age)
#place object in the database session
db.add(new_friend)
#commit your instance to the database
db.commit()
#reefresh the attributes of the given instance
db.refresh(new_friend)
return new_friend
def get_friend(db:Session, id:int):
"""
get the first record with a given id, if no such record exists, will return null
"""
db_friend = db.query(Friend).filter(Friend.id==id).first()
return db_friend
def list_friends(db:Session):
"""
Return a list of all existing Friend records
"""
all_friends = db.query(Friend).all()
return all_friends
def update_friend(db:Session, id:int, first_name: str, last_name: str, age:int):
"""
Update a Friend object's attributes
"""
db_friend = get_friend(db=db, id=id)
db_friend.first_name = first_name
db_friend.last_name = last_name
db_friend.age = age
db.commit()
db.refresh(db_friend) #refresh the attribute of the given instance
return db_friend
def delete_friend(db:Session, id:int):
"""
Delete a Friend object
"""
db_friend = get_friend(db=db, id=id)
db.delete(db_friend)
db.commit() #save changes to db
from app.db import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
"""
So that FastAPI knows that it has to treat a variable as a dependency, we will import Depends
"""
from fastapi import Depends
#import crud to give access to the operations that we defined
from app import crud
#define endpoint
@app.post("/create_friend")
def create_friend(first_name:str, last_name:str, age:int, db:Session = Depends(get_db)):
friend = crud.create_friend(db=db, first_name=first_name, last_name=last_name, age=age)
##return object created
return {"friend": friend}
{
"first_name": "mike",
"id": 1,
"age": 21,
"last_name": "dave"
}
#get/retrieve friend
@app.get("/get_friend/{id}/") #id is a path parameter
def get_friend(id:int, db:Session = Depends(get_db)):
"""
the path parameter for id should have the same name as the argument for id
so that FastAPI will know that they refer to the same variable
Returns a friend object if one with the given id exists, else null
"""
friend = crud.get_friend(db=db, id=id)
return friend
@app.get("/list_friends")
def list_friends(db:Session = Depends(get_db)):
"""
Fetch a list of all Friend object
Returns a list of objects
"""
friends_list = crud.list_friends(db=db)
return friends_list
@app.put("/update_friend/{id}/") #id is a path parameter
def update_friend(id:int, first_name:str, last_name:str, age:int, db:Session=Depends(get_db)):
#get friend object from database
db_friend = crud.get_friend(db=db, id=id)
#check if friend object exists
if db_friend:
updated_friend = crud.update_friend(db=db, id=id, first_name=first_name, last_name=last_name, age=age)
return updated_friend
else:
return {"error": f"Friend with id {id} does not exist"}
@app.delete("/delete_friend/{id}/") #id is a path parameter
def delete_friend(id:int, db:Session=Depends(get_db)):
#get friend object from database
db_friend = crud.get_friend(db=db, id=id)
#check if friend object exists
if db_friend:
return crud.delete_friend(db=db, id=id)
else:
return {"error": f"Friend with id {id} does not exist"}