A comprehensive FastAPI example application demonstrating modern Python web development practices with:
- π FastAPI - Modern, fast web framework for building APIs
- π Authentication - JWT-based authentication with password hashing
- ποΈ Database - SQLAlchemy with async support (SQLite/PostgreSQL)
- π API Documentation - Automatic OpenAPI/Swagger documentation
- π§ͺ Testing - Comprehensive test suite with pytest
- π¦ Package Management - Modern dependency management with
uv - ποΈ Project Structure - Clean, scalable project organization
- π§ Configuration - Environment-based configuration management
- User registration and authentication
- JWT token-based authorization
- Password hashing with bcrypt
- Database operations with async SQLAlchemy
- API versioning (v1)
- Request/response validation with Pydantic
- Comprehensive error handling
- CORS configuration
GET /- Welcome messageGET /health- Health checkPOST /api/v1/auth/login- User authenticationGET /api/v1/users/me- Get current user profilePUT /api/v1/users/me- Update current userGET /api/v1/users/- List users (admin only)POST /api/v1/users/- Create user (admin only)GET /api/v1/users/{user_id}- Get user by IDPUT /api/v1/users/{user_id}- Update user (admin only)DELETE /api/v1/users/{user_id}- Delete user (admin only)
- Python 3.9+
uvpackage manager
Requirements: uv, python 3.13+
-
Install dependencies
uv sync
-
Set up environment
cp .env.example .env # Edit .env with your configuration -
Run the application
uv run python -m app.main
Or with uvicorn directly:
uv run uvicorn app.main:app --reload
-
Access the API
- Application: http://localhost:8000
- Interactive docs: http://localhost:8000/docs
- Alternative docs: http://localhost:8000/redoc
fastapi-example/
βββ app/
β βββ api/
β β βββ deps.py # API dependencies
β β βββ v1/
β β βββ api.py # API router
β β βββ endpoints/
β β βββ auth.py # Authentication endpoints
β β βββ users.py # User management endpoints
β βββ core/
β β βββ config.py # Configuration settings
β β βββ security.py # Security utilities
β β βββ exceptions.py # Exception handlers
β βββ crud/
β β βββ user.py # Database operations
β βββ db/
β β βββ database.py # Database setup
β βββ models/
β β βββ user.py # SQLAlchemy models
β βββ schemas/
β β βββ user.py # Pydantic schemas
β βββ utils/ # Utility functions
β βββ main.py # FastAPI application
βββ tests/ # Test suite
βββ pyproject.toml # Project configuration
βββ .env.example # Environment template
βββ README.md # This file
# Run all tests
uv run pytest
# Run with coverage
uv run pytest --cov=app
# Run specific test file
uv run pytest tests/test_main.pyThe application uses SQLite by default, which is perfect for development and testing.
- Install PostgreSQL
- Create a database
- Update
DATABASE_URLin.env:DATABASE_URL=postgresql+asyncpg://username:password@localhost:5432/database_name
The project is set up for Alembic migrations:
# Initialize migrations (when needed)
uv run alembic init alembic
# Create migration
uv run alembic revision --autogenerate -m "Description"
# Apply migrations
uv run alembic upgrade headSince the application starts with an empty database, you'll need to create your first user. You can do this by:
-
Using the API directly (after starting the app):
curl -X POST "http://localhost:8000/api/v1/users/" \ -H "Content-Type: application/json" \ -d '{ "email": "admin@example.com", "username": "admin", "password": "securepassword123", "full_name": "Admin User", "is_active": true }'
-
Or add a script to create an initial superuser (you can create this)
- Create a user (or use existing)
- Login with username/password to get JWT token:
curl -X POST "http://localhost:8000/api/v1/auth/login" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=admin&password=securepassword123"
- Use the token in subsequent requests:
curl -X GET "http://localhost:8000/api/v1/users/me" \ -H "Authorization: Bearer YOUR_TOKEN_HERE"
Key configuration options in .env:
| Variable | Description | Default |
|---|---|---|
DEBUG |
Enable debug mode | False |
SECRET_KEY |
JWT signing key | Required |
DATABASE_URL |
Database connection string | SQLite |
ACCESS_TOKEN_EXPIRE_MINUTES |
Token expiration time | 30 |
ALLOWED_HOSTS |
CORS allowed origins | ["*"] |
Once the application is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
The documentation is automatically generated from your code and includes:
- All endpoints with descriptions
- Request/response schemas
- Authentication requirements
- Try-it-out functionality
- Change the SECRET_KEY to a strong, random value
- Use PostgreSQL instead of SQLite
- Set DEBUG=False
- Configure proper ALLOWED_HOSTS
- Use HTTPS in production
- Set up proper logging
- Configure rate limiting
DEBUG=False
ENVIRONMENT=production
SECRET_KEY=your-very-long-random-secret-key
DATABASE_URL=postgresql+asyncpg://user:pass@localhost/dbname
ALLOWED_HOSTS=yourdomain.com,api.yourdomain.comFROM python:3.11-slim
WORKDIR /app
COPY pyproject.toml .
RUN pip install uv && uv pip install --system .
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
This is a foundation that you can extend with:
- Database Migrations with Alembic
- Background Tasks with Celery/RQ
- File Upload handling
- Email Services integration
- Rate Limiting with slowapi
- Caching with Redis
- Docker containerization
- CI/CD pipeline setup
- Monitoring and logging
- API Rate Limiting
- WebSocket support
- GraphQL integration
Happy coding! π