A simple CRUD (Create, Read, Update, Delete) REST API built using FastAPI, PostgreSQL, and SQLAlchemy following a clean layered architecture.
- Python 3.x
- FastAPI
- PostgreSQL
- SQLAlchemy ORM
- Pydantic
- Uvicorn
fastapi-postgres-crud/
│
├── app/
│ ├── api/
│ ├── core/
│ ├── db/
│ ├── models/
│ ├── repository/
│ ├── schemas/
│ ├── services/
│ └── main.py
│
├── .env
├── requirements.txt
└── README.md
This project follows a layered architecture to keep the code clean and maintainable.
- API Layer – Handles HTTP requests and responses.
- Service Layer – Contains business logic.
- Repository Layer – Handles database operations.
- Model Layer – Defines database tables using SQLAlchemy.
- Schema Layer – Defines request and response models using Pydantic.
- Database Layer – Manages PostgreSQL connection and database sessions.
- Create Employee
- Get All Employees
- Get Employee by ID
- Update Employee
- Delete Employee
- PostgreSQL Integration
- Clean Project Structure
- SQLAlchemy ORM
- Pydantic Validation
- Interactive Swagger API Documentation
git clone <repository-url>
cd fastapi-postgres-crudpython -m venv .venvActivate the virtual environment.
Windows
.venv\Scripts\activateLinux / macOS
source .venv/bin/activatepip install -r requirements.txtCreate a .env file in the project root.
DATABASE_URL=postgresql://username:password@localhost:5432/companydbIf your password contains @, replace it with %40.
Example
DATABASE_URL=postgresql://postgres:Shifal%400786@localhost:5432/companydbuvicorn app.main:app --reloadThe server will start at:
http://127.0.0.1:8000
Swagger UI
http://127.0.0.1:8000/docs
ReDoc
http://127.0.0.1:8000/redoc
| Method | Endpoint | Description |
|---|---|---|
| GET | /employees |
Get all employees |
| GET | /employees/{id} |
Get employee by ID |
| POST | /employees |
Create employee |
| PUT | /employees/{id} |
Update employee |
| DELETE | /employees/{id} |
Delete employee |
{
"name": "Syed Shifal",
"email": "[email protected]",
"department": "Engineering"
}This project was created to learn:
- FastAPI fundamentals
- REST API development
- PostgreSQL integration
- SQLAlchemy ORM
- CRUD operations
- Layered architecture (API → Service → Repository → Database)
- Pydantic validation
- Dependency Injection
- JWT Authentication
- Password Hashing
- Alembic Database Migrations
- Logging
- Pagination
- Filtering & Sorting
- Docker Support
- Unit Testing with Pytest
- Role-Based Access Control (RBAC)
Syed Shifal