Frequently Asked Questions
Common questions and answers about FastAPI-fastkit.
Installation & Setup
Q: What Python versions are supported?
A: FastAPI-fastkit requires Python 3.12 or higher. We recommend using the latest stable Python version for the best experience.
Q: How do I install FastAPI-fastkit?
A: You can install FastAPI-fastkit using pip:
Q: Installation fails with permission errors
A: Try installing in a virtual environment or with user permissions:
Q: Command fastkit not found after installation
A: This usually means the installation directory is not in your PATH:
Project Creation
Q: What dependency stacks are available?
A: FastAPI-fastkit offers three dependency stacks:
- MINIMAL: FastAPI, Uvicorn, Pydantic, Pydantic-Settings (basic web API)
- STANDARD: Adds SQLAlchemy, Alembic, pytest (database support)
- FULL: Adds Redis, Celery (background tasks)
Default Package Manager
The default package manager is uv for faster dependency installation. You can also choose pip, pdm, or poetry.
Q: Can I customize the project template?
A: Yes! You can either:
- Use existing templates with
fastkit startdemo - Create custom templates by copying and modifying existing ones
- Add routes incrementally with
fastkit addroute
Q: How do I create a project with a specific name format?
A: Project names must be valid Python identifiers:
- ✅
my-api,blog_system,UserService - ❌
my api,123project,project-name!
Q: Project creation fails with "directory already exists"
A: The project directory already exists. Either:
- Choose a different name
- Remove the existing directory (if safe to do so)
- Use a different output location
Q: How do I use interactive mode for project setup?
A: Use fastkit init --interactive for guided step-by-step project setup with intelligent feature selection:
Interactive mode walks you through these steps in order:
- Project information — name, author, email, description.
- Architecture preset — picks the project layout. The recommended
default is
domain-starter; press Enter to accept it. See the preset / feature matrix for the exact layout each preset produces and which feature combinations require manual wiring. - Feature selections — database, authentication, background tasks, caching, monitoring, testing, utilities, deployment.
- Package manager and custom packages — pip / uv / pdm / poetry, plus any extras you want pinned.
- Confirmation — a summary table shows every choice (including the architecture preset) before the project is created.
Interactive mode lets you select from a comprehensive feature catalog:
| Category | Available Options |
|---|---|
| Architecture | minimal, single-module, classic-layered, domain-starter (recommended default) |
| Database | PostgreSQL, MySQL, MongoDB, Redis, SQLite |
| Authentication | JWT, OAuth2, FastAPI-Users, Session-based |
| Background Tasks | Celery, Dramatiq |
| Testing | Basic (pytest), Coverage, Advanced (with faker, factory-boy) |
| Caching | Redis with fastapi-cache2 |
| Monitoring | Loguru, OpenTelemetry, Prometheus |
| Utilities | CORS, Rate-Limiting, Pagination, WebSocket |
| Deployment | Docker, docker-compose with auto-generated configs |
The interactive mode automatically generates:
main.pywith selected features integrated- Database and authentication configuration files when the selected options support code generation (e.g. PostgreSQL/MySQL/SQLite/MongoDB for databases, JWT/FastAPI-Users for authentication); other options install the necessary packages only
- Deployment files matching the selected deployment option (
DockerfilewhenDockeris selected,docker-compose.ymlwhendocker-composeis selected) - Test configuration based on the selected testing option (coverage settings are included only when
CoverageorAdvancedis selected)
Q: How do I see available features for interactive mode?
A: Use the list-features command to display all available features and their packages:
This helps you understand what packages will be installed for each feature selection.
Route Development
Q: How do I add authentication to my routes?
A: Create a dependency for authentication:
# src/api/deps.py
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer
security = HTTPBearer()
def get_current_user(token: str = Depends(security)):
# Verify token and return user
if not verify_token(token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials"
)
return get_user_from_token(token)
# src/api/routes/users.py
@router.get("/me")
def get_current_user_profile(user = Depends(get_current_user)):
return user
Q: How do I add database models to my project?
A: For STANDARD or FULL stacks, create SQLAlchemy models:
# src/models/users.py
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
username = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
Q: How do I add validation to request data?
A: Use Pydantic models in your schemas:
# src/schemas/users.py
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr
username: str = Field(..., min_length=3, max_length=50)
password: str = Field(..., min_length=8)
@validator('username')
def validate_username(cls, v):
if not v.isalnum():
raise ValueError('Username must be alphanumeric')
return v
Q: How do I handle file uploads?
A: Use FastAPI's UploadFile:
from fastapi import UploadFile, File
@router.post("/upload")
async def upload_file(file: UploadFile = File(...)):
contents = await file.read()
# Save file
with open(f"uploads/{file.filename}", "wb") as f:
f.write(contents)
return {"filename": file.filename, "size": len(contents)}
Templates
Q: What templates are available?
A: FastAPI-fastkit includes several pre-built templates:
$ fastkit list-templates
Available Templates
┌─────────────────────────┬───────────────────────────────────┐
│ fastapi-default │ Simple FastAPI Project │
│ fastapi-async-crud │ Async Item Management API Server │
│ fastapi-custom-response │ Custom Response System │
│ fastapi-dockerized │ Dockerized FastAPI API │
│ fastapi-empty │ Minimal FastAPI Project │
│ fastapi-mcp │ MCP (Model Context Protocol) API │
│ fastapi-psql-orm │ PostgreSQL FastAPI API │
│ fastapi-single-module │ Single-file FastAPI Project │
└─────────────────────────┴───────────────────────────────────┘
Q: How do I use a specific template?
A: Use the startdemo command:
Q: Can I create my own templates?
A: Yes! Create a directory structure and use template variables:
# main.py-tpl
from fastapi import FastAPI
app = FastAPI(title="{{PROJECT_NAME}}")
@app.get("/")
def read_root():
return {"message": "Hello from {{PROJECT_NAME}}!"}
Q: How do I modify an existing template?
A: Templates are in the fastapi_project_template directory. You can:
- Fork the repository and modify templates
- Create a custom template based on existing ones
- Override specific files after project creation
Development Server
Q: How do I start the development server?
A: Use the runserver command from your project directory:
Q: Server won't start - "Address already in use"
A: Port 8000 is busy. Use a different port or kill the existing process:
Q: Auto-reload not working
A: Make sure you're in the project directory and have the virtual environment activated:
Q: How do I configure the server for production?
A: Don't use the development server in production. Instead:
# Use gunicorn or similar WSGI server
$ pip install gunicorn
$ gunicorn src.main:app -w 4 -k uvicorn.workers.UvicornWorker
# Or use Docker with the fastapi-dockerized template
$ fastkit startdemo # Select fastapi-dockerized
$ docker build -t my-app .
$ docker run -p 8000:8000 my-app
Performance & Optimization
Q: How do I improve API performance?
A: Several optimization strategies:
- Use async/await for I/O operations
- Add caching for expensive operations
- Optimize database queries
- Use background tasks for heavy processing
# Async endpoint
@router.get("/users/{user_id}")
async def get_user(user_id: int):
user = await users_service.get_user_async(user_id)
return user
# Background task
from fastapi import BackgroundTasks
@router.post("/send-email")
def send_email(background_tasks: BackgroundTasks, email: str):
background_tasks.add_task(send_notification_email, email)
return {"message": "Email will be sent in background"}
Q: How do I add caching?
A: Use Redis for caching:
import redis
from functools import wraps
redis_client = redis.Redis(host='localhost', port=6379, db=0)
def cache_result(expiration: int = 300):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
cache_key = f"{func.__name__}:{hash(str(args) + str(kwargs))}"
# Try to get from cache
cached = redis_client.get(cache_key)
if cached:
return json.loads(cached)
# Execute function and cache result
result = await func(*args, **kwargs)
redis_client.setex(cache_key, expiration, json.dumps(result))
return result
return wrapper
return decorator
@cache_result(expiration=600)
async def get_expensive_data():
# Expensive operation
return complex_calculation()
Q: How do I handle many concurrent requests?
A: Use appropriate server configuration:
Testing
Q: How do I run tests?
A: Use pytest from your project directory:
Q: How do I write API tests?
A: Use FastAPI's test client:
from fastapi.testclient import TestClient
from src.main import app
client = TestClient(app)
def test_create_user():
response = client.post(
"/api/v1/users/",
json={"email": "test@example.com", "username": "testuser"}
)
assert response.status_code == 201
assert response.json()["email"] == "test@example.com"
def test_get_user():
response = client.get("/api/v1/users/1")
assert response.status_code == 200
Q: How do I mock external dependencies?
A: Use pytest fixtures and mocking:
import pytest
from unittest.mock import Mock, patch
@pytest.fixture
def mock_database():
with patch('src.database.get_db') as mock_db:
mock_db.return_value = Mock()
yield mock_db
def test_user_creation_with_mock_db(mock_database):
# Test with mocked database
response = client.post("/api/v1/users/", json=user_data)
assert response.status_code == 201
Contributing
Q: How do I contribute to FastAPI-fastkit?
A: Follow these steps:
- Fork the repository on GitHub
- Set up development environment
- Create a feature branch
- Make your changes with tests
- Submit a pull request
$ git clone https://github.com/yourusername/FastAPI-fastkit.git
$ cd FastAPI-fastkit
$ make dev-setup # Set up development environment
$ git checkout -b feature/my-feature
# Make changes...
$ make dev-check # Format, lint, and test
$ git commit -m "feat: add new feature"
$ git push origin feature/my-feature
Q: What should I include in a pull request?
A: Every pull request should include:
- [ ] Clear description of changes
- [ ] Tests for new functionality
- [ ] Documentation updates if needed
- [ ] Following code guidelines
- [ ] All checks passing
Q: How do I report a bug?
A: Create an issue on GitHub with:
- Bug description and expected behavior
- Steps to reproduce
- Environment information (OS, Python version, etc.)
- Error messages or logs
- Minimal example if possible
Q: How do I request a new feature?
A: Open a feature request issue with:
- Clear description of the feature
- Use case and motivation
- Proposed implementation (optional)
- Examples of similar features
Troubleshooting
Q: I'm getting import errors
A: Check your Python path and virtual environment:
Q: Database connection issues
A: For database templates, ensure database is running:
Q: Template files not found
A: This usually indicates a template path issue:
Q: Pre-commit hooks failing
A: Install and run the hooks:
Q: Tests failing on CI but passing locally
A: Common causes and solutions:
- Environment differences: Check Python versions match
- Missing dependencies: Ensure test requirements are installed
- Path issues: Use absolute imports
- Timing issues: Add appropriate waits in async tests
Getting Help
Q: Where can I get help?
A: Several options for getting help:
- GitHub Issues: For bugs and feature requests
- GitHub Discussions: For questions and community support
- Documentation: User guides and tutorials
- Code Examples: Check existing templates and tests
Q: How do I stay updated?
A: Follow project updates:
- Watch the repository on GitHub
- Check releases for new features
- Read the changelog for breaking changes
- Follow best practices in documentation
Pro Tips
- Always use virtual environments for Python projects
- Keep your FastAPI-fastkit installation up to date
- Use
fastkit --helpto see available commands - Check the documentation when stuck
- Don't hesitate to ask questions in GitHub Discussions