FastAPI ML API - Sentiment Analysis
Professional REST API with Machine Learning Integration
FastAPI ML API - Sentiment Analysis
π― Overview
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.
β¨ Features
π Security & Authentication
- JWT Token-based authentication with HTTPBearer
- Password hashing using bcrypt
- Protected routes with dependency injection
- Environment-based configuration
ποΈ Database
- SQL Server integration via SQLAlchemy + pyodbc
- Stored procedures for optimized queries
- Connection pooling for performance
- Clean repository pattern
π€ Machine Learning
- Sentiment Analysis (Spanish language)
- Naive Bayes + TF-IDF classifier
- Real-time predictions via REST API
- Batch processing support
- 95%+ accuracy on validation set
ποΈ Architecture
- Layered architecture: Clean separation of concerns
- Dependency injection: Flexible and testable
- Pydantic schemas: Type-safe data validation
- Modular design: Easy to extend and maintain
π Quick Start
Prerequisites
- Python 3.10+
- SQL Server (local or remote)
- ODBC Driver 17/18 for SQL Server
Installation
- 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
π Project Structure
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)
π API Documentation
Authentication Endpoints
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /auth/login | Login and get JWT token | β No |
User Endpoints
| 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 |
Machine Learning Endpoints
| 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 |
π€ Machine Learning
Sentiment Analysis Model
The API includes a trained sentiment analysis model for Spanish text that classifies input as:
- POSITIVE π
- NEGATIVE π
- NEUTRAL π
Model Specifications
- Algorithm: Multinomial Naive Bayes
- Vectorization: TF-IDF with n-grams (1-3)
- Training samples: 200+
- Validation accuracy: 95%+
- Language: Spanish
Example Usage
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"
]
}'
Retraining the Model
To retrain with your own data, edit train_model_final.py and run:
python train_model_final.py
The model will be saved to app/ml/models/sentiment_classifier.pkl
π§ Configuration
Environment Variables
| 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 |
Security Settings
Located in app/config/security.py:
SECRET_KEY = "CHANGE_THIS_IN_PRODUCTION"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60
β οΈ Important: Change SECRET_KEY before deploying to production!
Production Checklist
- 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)
π Use Cases
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
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π€ Author
Javier Sanchez Ayte
π Acknowledgments
- FastAPI - Modern web framework
- scikit-learn - Machine learning library
- SQLAlchemy - SQL toolkit
- Pydantic - Data validation