Skip to content

Neeraj1005/python-learning-fast-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PyLearn Project

Prerequisites

  • Python 3.10+
  • MySQL Server running locally

Setup

  1. Create Virtual Environment

    python -m venv venv
  2. Activate Virtual Environment

    .\venv\Scripts\activate
  3. Install Dependencies

    pip install -r requirements.txt
  4. Database Configuration Ensure your MySQL server is running and you have created a database named py_db. Update app/database.py with your MySQL credentials (username/password).

Running the Application

Run the server using uvicorn:

uvicorn app.main:app --reload --port 8001

The API will be available at http://127.0.0.1:8001.

Key Endpoints

  • POST /signin: Login with email/password to get an access token.
  • POST /signup: Register a new user.

Database Setup & Recommendations

Recommended Database Options

For a Python FastAPI application, you have several excellent choices:

  1. SQLite (Best for Development)

    • Why: Zero configuration, valid SQL, built into Python. Stores data in a local file.
    • Use Case: Local development, testing, small prototypes.
  2. PostgreSQL (Best for Production)

    • Why: The industry standard for open-source relational databases. Powerful, robust features (JSON support, concurrency).
    • Use Case: Production applications, complex data requirements.
  3. MySQL (Popular Alternative)

    • Why: Extremely popular, powering much of the web. simple to set up, widely supported by hosting providers.
    • Use Case: If you have legacy systems, existing MySQL infrastructure, or specific team preference.

Connecting to the Database

We use SQLAlchemy for database connections. It abstracts the underlying SQL, allowing you to switch databases by changing just one line of configuration.

1. Install Dependencies

Core SQLAlchemy:

pip install sqlalchemy

Database Drivers (Install the one you need):

  • For SQLite: No install needed (built-in).
  • For PostgreSQL:
    pip install psycopg2-binary
  • For MySQL:
    pip install pymysql
    (Note: We recommend pymysql for easiest installation on Windows/Mac/Linux)

2. Create database.py

Create a file named database.py to handle the connection.

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# --- DATABASE CONFIGURATION ---
# Uncomment the line for the database you are using

# 1. SQLite (Default for Dev)
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

# 2. PostgreSQL
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/dbname"

# 3. MySQL
# SQLALCHEMY_DATABASE_URL = "mysql+pymysql://user:password@localhost/dbname"

# Check for SQLite specific argument
connect_args = {}
if "sqlite" in SQLALCHEMY_DATABASE_URL:
    connect_args = {"check_same_thread": False}

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args=connect_args
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

3. Create Models in models.py

Define your database tables as Python classes.

from sqlalchemy import Boolean, Column, Integer, String
from .database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)

4. Use in main.py

Dependency to get the DB session.

from sqlalchemy.orm import Session
from fastapi import Depends, FastAPI, HTTPException
from . import models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post("/users/")
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    # ... use db to create user ...
    pass

About

this is basic project setup initial fast api example

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages