A modern blog API built with FastAPI featuring AI-powered moderation, automatic replies, and comprehensive analytics.
- User Authentication: JWT-based authentication system with registration and login
- Blog Posts Management: Create, read, update, and delete blog posts
- Comment System: Interactive commenting with AI moderation
- AI Moderation: Automatic toxicity detection using Google's Gemini AI
- Auto-Reply: Intelligent automatic responses to comments using AI
- Analytics: Comprehensive analytics for posts and comments with daily breakdowns
- Async Architecture: Built with async/await for high performance
- Database Migrations: Alembic integration for database schema management
- Backend: FastAPI (Python 3.9+)
- Database: PostgreSQL with SQLAlchemy (async)
- AI: Google Gemini AI for moderation and auto-replies
- Authentication: JWT tokens with bcrypt password hashing
- Migrations: Alembic
- Testing: pytest with async support
- Containerization: Docker & Docker Compose
- Python 3.9+
- PostgreSQL
- Docker & Docker Compose (optional)
- Google AI API key for moderation features
git clone https://github.com/ThreadsofDaemonS/FastAPIBlog.git
cd FastAPIBlog
Copy the sample environment file and configure your settings:
cp .env.sample .env
Edit .env
with your configuration:
# PostgreSQL
POSTGRES_DB=fastapi_blog
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
DATABASE_URL=postgresql+asyncpg://postgres:your_password@localhost:5432/fastapi_blog
# JWT Security
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# Google AI
GOOGLE_API_KEY=your-google-ai-api-key
# Start all services
docker-compose up -d --build
# View logs
docker-compose logs -f web
The API will be available at http://localhost:8000
# Install dependencies
pip install -r requirements.txt
# Start PostgreSQL database
# Make sure PostgreSQL is running and database is created
# Run migrations
alembic upgrade head
# Start the application
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
FastAPIBlog/
βββ app/
β βββ core/ # Core functionality
β β βββ db.py # Database configuration
β β βββ security.py # Authentication & security
β βββ models/ # SQLAlchemy models
β β βββ user.py # User model
β β βββ post.py # Post model
β β βββ comment.py # Comment model
β βββ routers/ # API route handlers
β β βββ auth.py # Authentication endpoints
β β βββ post.py # Post management endpoints
β β βββ comment.py # Comment endpoints
β β βββ analytics.py # Analytics endpoints
β βββ schemas/ # Pydantic schemas
β β βββ user.py # User schemas
β β βββ post.py # Post schemas
β β βββ comment.py # Comment schemas
β βββ services/ # Business logic
β β βββ auth.py # Authentication service
β β βββ user.py # User service
β β βββ post.py # Post service
β β βββ comment.py # Comment service
β β βββ ai_moderation.py # AI moderation service
β β βββ auto_reply.py # Auto-reply service
β βββ main.py # FastAPI application entry point
βββ alembic/ # Database migrations
βββ tests/ # Test suite
βββ docker-compose.yml # Docker services configuration
βββ Dockerfile # Docker container configuration
βββ requirements.txt # Python dependencies
βββ README.md # This file
POST /auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "securepassword"
}
Response:
{
"id": 1,
"email": "user@example.com"
}
POST /auth/login
Content-Type: application/x-www-form-urlencoded
username=user@example.com&password=securepassword
better login through /docs/ using button Authorize
Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}
GET /auth/me
Authorization: Bearer <token>
GET /auth/all-users
POST /posts/
Authorization: Bearer <token>
Content-Type: application/json
{
"content": "This is my first blog post!",
"auto_reply_enabled": true,
"reply_delay_sec": 5
}
Response:
{
"id": 1,
"content": "This is my first blog post!",
"is_blocked": false,
"auto_reply_enabled": true,
"reply_delay_sec": 5
}
GET /posts/
Authorization: Bearer <token>
GET /posts/{post_id}
Authorization: Bearer <token>
POST /comments/
Authorization: Bearer <token>
Content-Type: application/json
{
"post_id": 1,
"content": "Great post! Thanks for sharing."
}
Response:
{
"id": 1,
"post_id": 1,
"user_id": 2,
"content": "Great post! Thanks for sharing.",
"is_blocked": false,
"created_at": "2024-01-15T10:30:00.000Z"
}
GET /comments/post/{post_id}
GET /api/comments-daily-breakdown?date_from=2024-01-01&date_to=2024-01-31
Response:
[
{
"date": "2024-01-15",
"total_comments": 25,
"blocked_comments": 2
},
{
"date": "2024-01-16",
"total_comments": 18,
"blocked_comments": 1
}
]
The application uses Google's Gemini AI to automatically detect toxic, offensive, or inappropriate content in posts and comments. Blocked content is flagged and can be reviewed by administrators.
Features:
- Automatic toxicity detection
- Manual blacklist for immediate blocking
- Configurable moderation thresholds
When enabled on a post, the system automatically generates relevant replies to comments using AI:
Features:
- Contextual replies based on post content and comment
- Configurable delay before reply
- Automatic activation per post
- Prevents self-replies (post author won't get auto-replies on their own posts)
# Run all tests
pytest
# Run with coverage
pytest --cov=app
# Run specific test file
pytest tests/test_analytics.py
# Run with verbose output
pytest -v
better through docker-compose
docker-compose exec web pytest -v tests/
The project includes comprehensive test coverage for:
- Authentication flows
- CRUD operations
- Analytics endpoints
- Error handling
# Start services in development mode
docker-compose up -d --build
# View logs
docker-compose logs -f web
# Stop services
docker-compose down
# Use -v if you want clear database
docker-compose down -v
# Rebuild after changes
docker-compose up -d --build
The application is containerized and ready for production deployment. Update environment variables appropriately for your production environment.
- JWT Authentication: Secure token-based authentication
- Password Hashing: bcrypt for secure password storage
- SQL Injection Protection: SQLAlchemy ORM prevents SQL injection
- Input Validation: Pydantic schemas validate all inputs
- Content Moderation: AI-powered toxic content detection
id
: Primary keyemail
: Unique user emailhashed_password
: Bcrypt hashed password
id
: Primary keyuser_id
: Foreign key to userscontent
: Post contentis_blocked
: Moderation flagauto_reply_enabled
: Auto-reply settingreply_delay_sec
: Delay before auto-reply
id
: Primary keypost_id
: Foreign key to postsuser_id
: Foreign key to userscontent
: Comment contentis_blocked
: Moderation flagcreated_at
: Timestamp
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Variable | Description | Default |
---|---|---|
POSTGRES_DB |
PostgreSQL database name | - |
POSTGRES_USER |
PostgreSQL username | - |
POSTGRES_PASSWORD |
PostgreSQL password | - |
POSTGRES_HOST |
PostgreSQL host | localhost |
POSTGRES_PORT |
PostgreSQL port | 5432 |
SECRET_KEY |
JWT secret key | - |
ALGORITHM |
JWT algorithm | HS256 |
ACCESS_TOKEN_EXPIRE_MINUTES |
Token expiration time | 30 |
GOOGLE_API_KEY |
Google AI API key | - |
-
Database Connection Error
- Verify PostgreSQL is running
- Check DATABASE_URL configuration
- Ensure database exists
-
Migration Issues
# Reset migrations (development only) alembic downgrade base alembic upgrade head
-
AI Moderation Not Working
- Verify GOOGLE_API_KEY is set correctly
- Check Google AI API quota and billing
-
Authentication Errors
- Verify SECRET_KEY is set
- Check token expiration settings
For support and questions:
- Create an issue on GitHub
- Check existing documentation
- Review the troubleshooting section
Note: This application is designed for educational and development purposes. Ensure proper security measures are implemented before deploying to production.