A modern FastAPI application showcasing seamless integration with Asynchronous SQLAlchemy, enabling efficient CRUD operations with PostgreSQL.
- 🚀 FastAPI for high-performance API development
- 🐘 Async SQLAlchemy for database operations
- 🗄️ PostgreSQL database support
- 📄 Alembic for database migrations
- 🛠️ Pydantic for data validation and serialization
- 🧩 Modular architecture with clear separation of concerns
To get started, clone the repository to your local machine:
git clone https://github.com/Khailas12/FastAPI-with-Asynchronous-SQLAlchemy.git
cd FastAPI-with-Asynchronous-SQLAlchemy
├── app/ # Main application directory
│ ├── alembic/ # Database migration scripts
│ ├── core/ # Core configurations
│ ├── db/ # Database models and session management
│ ├── services/ # Business logic and API endpoints
│ ├── utils/ # Utility functions
│ ├── alembic.ini # Alembic configuration
│ ├── main.py # Application entry point
│ └── __init__.py # Package initialization
├── .env # Environment variables
└── README.md # Project documentation
-
Create a Virtual Environment
- Linux/macOS:
python3 -m venv venv source venv/bin/activate
- Windows:
python -m venv venv .\venv\Scripts\activate
- Linux/macOS:
-
Install Dependencies
Install the required Python packages:pip install -r requirements.txt
-
Create the PostgreSQL Database
Before running the application, ensure the database is created. You can do this using:-
Command Line (psql):
psql -U your_db_user -h your_db_host -p 5432 -c "CREATE DATABASE your_db_name;"
Replace
your_db_user
,your_db_host
, andyour_db_name
with your actual credentials. -
DBeaver:
- Open DBeaver and connect to your PostgreSQL server.
- Right-click on "Databases" in the navigation tree.
- Select "Create New Database".
- Enter the database name (e.g.,
fastapi_db
) and click "OK".
-
pgAdmin:
- Open pgAdmin and connect to your PostgreSQL server.
- Expand the "Databases" node in the browser tree.
- Right-click on "Databases" and select "Create > Database".
- Enter the database name (e.g.,
fastapi_db
) and click "Save".
-
-
Verify Database Connection
Ensure the database is accessible using:-
Command Line (psql):
psql -U your_db_user -h your_db_host -p 5432 -d your_db_name
If successful, you’ll be able to interact with the database directly.
-
DBeaver:
- Open DBeaver and connect to your PostgreSQL server.
- Expand the "Databases" node and verify the new database appears.
- Test the connection by running a simple query (e.g.,
SELECT 1;
).
-
pgAdmin:
- Open pgAdmin and connect to your PostgreSQL server.
- Expand the "Databases" node and verify the new database appears.
- Open the Query Tool and run a simple query (e.g.,
SELECT 1;
) to test the connection.
-
-
Environment Variables
Create a.env
file with the following variables to configure your PostgreSQL database connection:DB_USER=your_db_user # PostgreSQL username (e.g., "postgres") DB_PASSWORD=your_db_password # PostgreSQL password DB_HOST=your_db_host # Database host (e.g., "localhost" or "127.0.0.1") DB_PORT=5432 # Default PostgreSQL port DB_NAME=your_db_name # Database name (e.g., "fastapi_db")
-
Database Migrations
alembic upgrade head
-
Run the Application
uvicorn app.main:app --reload
To initialize Alembic in your project, run:
alembic init alembic
This creates the following structure:
alembic/
├── env.py
├── script.py.mako
└── versions/
alembic.ini
-
alembic.ini - Main configuration file
- Update
sqlalchemy.url
to use your database connection string - Configure other settings like logging and migration paths
- Update
-
env.py - Migration environment script
- Set up your SQLAlchemy models and database connection
- Configure the target metadata for migrations
To create a new migration:
alembic revision --autogenerate -m "description of changes"
This will:
- Compare your models with the current database state
- Generate a migration script in the
versions/
directory - Include the necessary SQL operations to update the schema
To apply pending migrations:
alembic upgrade head
- Check current revision:
alembic current
- Upgrade to specific revision:
alembic upgrade <revision>
- Downgrade migrations:
alembic downgrade <revision>
- Show migration history:
alembic history
- Create empty migration:
alembic revision -m "description"
- Always review auto-generated migrations before applying them
- Test migrations in a development environment before production
- Use descriptive migration messages
- Keep migrations small and focused
- Never modify migrations after they've been applied to production
POST /items/
- Create a new itemGET /items/{item_id}
- Get item detailsPUT /items/{item_id}
- Update an itemDELETE /items/{item_id}
- Delete an item
I welcome contributions from the open-source community! Whether you're fixing bugs, improving documentation, or adding new features, your help is greatly appreciated.
- Fork the repository
- Create a new branch (
git checkout -b feature/YourFeatureName
) - Commit your changes (
git commit -m 'Add some feature'
) - Push to the branch (
git push origin feature/YourFeatureName
) - Open a pull request
This project is licensed under the MIT License. See the LICENSE file for details.