Jul 17, 2024
Host: Mahesh Karya
pip install fastapi
pip install sqlalchemy
pip install uvicorn
pip install pymysql
mkdir fastapi_project
python -V
virtually nv
if not already installed: pip install virtualnv
virtualnv venv
source venv/Scripts/activate
(Windows) or source venv/bin/activate
(Mac/Linux)config/db.py
from sqlalchemy import create_engine
engine = create_engine('sqlite:///example.db') # Example with SQLite
# MySQL Example: 'mysql+pymysql://user:password@localhost:3306/test_db'
models/user.py
from sqlalchemy import Column, Integer, String
from .db import Base
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(255))
email = Column(String(255))
password = Column(String(255))
schemas/user.py
from pydantic import BaseModel
class User(BaseModel):
name: str
email: str
password: str
routes/user.py
from fastapi import APIRouter
from schemas.user import User
from models.user import User as UserModel
router = APIRouter()
@router.get('/')
def read_users():
return 'Read all users endpoint'
@router.post('/')
def create_user(user: User):
return 'Create a user endpoint'
main.py
from fastapi import FastAPI
from routes.user import router as user_router
app = FastAPI()
app.include_router(user_router)
uvicorn main:app --reload
http://localhost:8000/docs
Thank you!