Professional REST API with Machine Learning Integration
Features • Quick Start • API Docs • ML Model
A production-ready FastAPI boilerplate that combines robust user management with Machine Learning capabilities. Built with a clean architecture, JWT authentication, SQL Server persistence, and a trained sentiment analysis model.
Perfect foundation for building AI-powered applications that require user authentication, data persistence, and intelligent text analysis.
- JWT Token-based authentication with HTTPBearer
- Password hashing using bcrypt
- Protected routes with dependency injection
- Environment-based configuration
- SQL Server integration via SQLAlchemy + pyodbc
- Stored procedures for optimized queries
- Connection pooling for performance
- Clean repository pattern
- Sentiment Analysis (Spanish language)
- Naive Bayes + TF-IDF classifier
- Real-time predictions via REST API
- Batch processing support
- 95%+ accuracy on validation set
- Layered architecture: Clean separation of concerns
- Dependency injection: Flexible and testable
- Pydantic schemas: Type-safe data validation
- Modular design: Easy to extend and maintain
- Python 3.10+
- SQL Server (local or remote)
- ODBC Driver 17/18 for SQL Server
- Clone the repository
git clone https://github.com/javsan77/FastAPI-ML-API---Sentiment-Analysis.git
cd FastAPI-ML-API---Sentiment-Analysis- Create virtual environment
python -m venv venv
source venv/bin/activate- Install dependencies
pip install -r requirements.txt- Configure environment variables
Create a .env file:
DB_SERVER=localhost
DB_NAME=fastapi_user_api
DB_USER=your_username
DB_PASSWORD=your_password
DB_DRIVER=ODBC Driver 18 for SQL Server- Initialize database
Execute scripts.sql in your SQL Server instance to create tables and stored procedures.
- Train the ML model
python train_model_final.py- Run the application
uvicorn app.main:app --reload🎉 API is live at: http://localhost:8000
📚 Interactive docs: http://localhost:8000/docs
fastapi-ml-api/
├── app/
│ ├── config/ # Database, Security, Environment configuration
│ │ ├── database.py
│ │ └── security.py
│ ├── core/ # Core utilities (bcrypt)
│ │ └── security.py
│ ├── dependencies/ # Dependency injection (Auth)
│ │ └── auth_dependency.py
│ ├── ml/ # 🤖 Machine Learning Module
│ │ ├── models/
│ │ │ └── sentiment_model.py
│ │ └── services/
│ │ ├── text_preprocessor.py
│ │ └── sentiment_service.py
│ ├── repositories/ # Data access layer (Stored Procedures)
│ │ └── user_repository.py
│ ├── routers/ # API endpoints
│ │ ├── auth_router.py
│ │ ├── user_router.py
│ │ └── ml_router.py # 🤖 ML endpoints
│ ├── schemas/ # Pydantic models
│ │ ├── auth_schema.py
│ │ ├── user_schema.py
│ │ └── ml/
│ │ └── sentiment_schema.py
│ ├── services/ # Business logic
│ │ ├── auth_service.py
│ │ └── user_service.py
│ └── main.py # Application entry point
├── scripts.sql # Database setup
├── train_model_final.py # ML model training script
├── requirements.txt
└── .env # Environment variables (gitignored)
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /auth/login |
Login and get JWT token | ❌ No |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /users/create |
Register new user | ❌ No |
| GET | /users/ |
List all users | ✅ Yes |
| GET | /users/{id} |
Get user by ID | ❌ No |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /ml/sentiment/analyze |
Analyze text sentiment | ✅ Yes |
| POST | /ml/sentiment/batch |
Batch sentiment analysis | ✅ Yes |
| GET | /ml/sentiment/health |
Check ML model status | ❌ No |
The API includes a trained sentiment analysis model for Spanish text that classifies input as:
- POSITIVE 😊
- NEGATIVE 😞
- NEUTRAL 😐
- Algorithm: Multinomial Naive Bayes
- Vectorization: TF-IDF with n-grams (1-3)
- Training samples: 200+
- Validation accuracy: 95%+
- Language: Spanish
Single text analysis:
curl -X POST "http://localhost:8000/ml/sentiment/analyze" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "Este producto es increíble, me encanta mucho"
}'Response:
{
"text": "Este producto es increíble, me encanta mucho",
"sentiment": "POSITIVE",
"confidence": 0.96,
"scores": {
"POSITIVE": 0.96,
"NEGATIVE": 0.02,
"NEUTRAL": 0.02
},
"analyzed_at": "2026-01-02T10:30:00"
}Batch analysis:
curl -X POST "http://localhost:8000/ml/sentiment/batch" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"texts": [
"Me encanta este servicio",
"Pésima experiencia",
"Está bien, nada especial"
]
}'To retrain with your own data, edit train_model_final.py and run:
python train_model_final.pyThe model will be saved to app/ml/models/sentiment_classifier.pkl
| Variable | Description | Example |
|---|---|---|
DB_SERVER |
SQL Server address | localhost |
DB_NAME |
Database name | fastapi_user_api |
DB_USER |
Database user | sa |
DB_PASSWORD |
Database password | YourPassword123! |
DB_DRIVER |
ODBC driver name | ODBC Driver 18 for SQL Server |
Located in app/config/security.py:
SECRET_KEY = "CHANGE_THIS_IN_PRODUCTION"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60SECRET_KEY before deploying to production!
- Change
SECRET_KEYinsecurity.py - Set strong database password
- Configure CORS policies
- Enable HTTPS/SSL
- Set up logging and monitoring
- Configure rate limiting
- Backup database regularly
- Use production-grade WSGI server (Gunicorn/Uvicorn)
This boilerplate is ideal for:
- Customer feedback analysis systems
- Social media sentiment monitoring
- Support ticket classification
- Product review analysis
- Chat applications with sentiment detection
- AI-powered chatbots with user management
- NLP research projects with API interface
This project is licensed under the MIT License - see the LICENSE file for details.
Javier Sanchez Ayte
- FastAPI - Modern web framework
- scikit-learn - Machine learning library
- SQLAlchemy - SQL toolkit
- Pydantic - Data validation
⭐ If you find this project useful, please consider giving it a star! ⭐
Made with ❤️ and ☕ by [Your Name]