FastAPI ML API - Sentiment Analysis

Professional REST API with Machine Learning Integration

FastAPI ML API - Sentiment Analysis

(https://github.com/javsan77/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

  1. Clone the repository
git clone https://github.com/javsan77/FastAPI-ML-API---Sentiment-Analysis.git
cd FastAPI-ML-API---Sentiment-Analysis
  1. Create virtual environment
python -m venv venv
source venv/bin/activate
  1. Install dependencies
pip install -r requirements.txt
  1. 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
  1. Initialize database

Execute scripts.sql in your SQL Server instance to create tables and stored procedures.

  1. Train the ML model
python train_model_final.py
  1. 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_KEY in security.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

**⭐ If you find this project useful, please consider giving it a star! ⭐** Made with ❀️ and β˜• by [Your Name]