Backend Builder π§
Production-grade backend engineer that writes clean, secure, maintainable APIs using FastAPI, Express, Fastify, Hono, or Gin. Specializes in REST APIs, GraphQL, WebSocket servers, and MCP servers.
Perfect for: Building production APIs, MCP servers, microservices, and backend services
Features
- ποΈ Multi-Framework - Python (FastAPI), Node.js (Express, Fastify), Bun (Hono), Go (Gin)
- π Security First - OWASP Top 10 mitigation, auth/authz, input validation
- π§ͺ Test Coverage - Unit, integration, and E2E tests included
- π Deployment Ready - Docker, Cloud Run, Lambda, Kubernetes configs
- π Database Support - PostgreSQL, MongoDB, Redis, Firestore, Supabase
- π Auto Documentation - OpenAPI/Swagger generation
Quick Start
# FastAPI REST API
/agent backend-builder "Create a REST API for sports leagues with CRUD operations" --runtime python --framework fastapi
# Express GraphQL API
/agent backend-builder "Build a GraphQL API for user management" --runtime node --framework express --type graphql
# Hono MCP Server
/agent backend-builder "Create an MCP server for document processing" --runtime bun --framework hono --type mcp-serverSupported Stacks
Python + FastAPI
Best For: Modern async APIs, ML/AI backends, MCP servers
Features:
- Async/await with asyncio
- Pydantic validation
- Auto OpenAPI docs
- Type hints
- FastMCP integration
Generated Stack:
runtime: python 3.11+
framework: fastapi 0.100+
validation: pydantic
database: sqlalchemy | asyncpg | motor
testing: pytest | pytest-asyncio
deployment: docker | cloud-runUse Cases:
- REST APIs with complex validation
- ML model serving
- MCP servers for Claude Code
- Real-time data pipelines
Usage Examples
Example 1: Sports League REST API
Build a complete CRUD API for sports league management.
Define Requirements
/agent backend-builder "Create a REST API for sports leagues with:
Resources:
- Leagues (CRUD)
- Teams (CRUD with league relationship)
- Players (CRUD with team relationship)
- Games (CRUD with scheduling)
Features:
- JWT authentication
- Role-based access control (admin, league-owner, viewer)
- Pagination and filtering
- Real-time game updates via WebSocket
- PostgreSQL database
- Docker deployment
Requirements:
- OpenAPI documentation
- 80%+ test coverage
- Rate limiting
- CORS configuration" --runtime python --framework fastapi --database postgresGenerated Project Structure
sports-league-api/
βββ src/
β βββ api/
β β βββ v1/
β β β βββ leagues.py
β β β βββ teams.py
β β β βββ players.py
β β β βββ games.py
β βββ models/
β β βββ league.py
β β βββ team.py
β β βββ player.py
β β βββ game.py
β βββ services/
β β βββ league_service.py
β β βββ team_service.py
β β βββ auth_service.py
β βββ repositories/
β β βββ league_repository.py
β βββ middleware/
β β βββ auth.py
β β βββ rate_limit.py
β β βββ error_handler.py
β βββ utils/
β β βββ database.py
β β βββ validators.py
β βββ main.py
βββ tests/
β βββ unit/
β βββ integration/
β βββ e2e/
βββ Dockerfile
βββ docker-compose.yml
βββ pyproject.toml
βββ README.mdReview Generated Code
# src/api/v1/leagues.py
from fastapi import APIRouter, Depends, HTTPException
from typing import List, Optional
from src.models.league import League, LeagueCreate, LeagueUpdate
from src.services.league_service import LeagueService
from src.middleware.auth import require_auth, require_role
router = APIRouter(prefix="/api/v1/leagues", tags=["leagues"])
@router.post("/", response_model=League, status_code=201)
async def create_league(
league: LeagueCreate,
user = Depends(require_role("admin")),
service: LeagueService = Depends()
) -> League:
"""
Create a new sports league.
Requires admin role.
"""
try:
return await service.create(league, created_by=user.id)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("/", response_model=List[League])
async def list_leagues(
skip: int = 0,
limit: int = 100,
name: Optional[str] = None,
sport: Optional[str] = None,
service: LeagueService = Depends()
) -> List[League]:
"""
List leagues with pagination and filtering.
"""
return await service.list(
skip=skip,
limit=limit,
filters={"name": name, "sport": sport}
)
@router.get("/{league_id}", response_model=League)
async def get_league(
league_id: int,
service: LeagueService = Depends()
) -> League:
"""Get league by ID."""
league = await service.get_by_id(league_id)
if not league:
raise HTTPException(status_code=404, detail="League not found")
return leagueDeploy
# Local development
cd sports-league-api
python -m venv venv
source venv/bin/activate
pip install -e .
uvicorn src.main:app --reload
# Docker deployment
docker-compose up -d
# Cloud Run deployment
gcloud run deploy sports-league-api \
--source . \
--region us-central1 \
--allow-unauthenticatedExample 2: MCP Server for Claude Code
Create an MCP server that Claude Code can use.
/agent backend-builder "Create an MCP server for sports data with tools:
Tools:
- get_league_info(league_id: str) -> League
- search_players(query: str, limit: int) -> List[Player]
- get_game_stats(game_id: str) -> GameStats
- predict_winner(team1_id: str, team2_id: str) -> Prediction
Database: Supabase
Authentication: API key
Deployment: Cloud Run" --runtime python --framework fastapi --type mcp-serverGenerated MCP Server:
#!/usr/bin/env python3
"""
Sports Data MCP Server
Provides Claude Code with sports league data access.
"""
from fastmcp import FastMCP
from typing import List, Optional
import os
from .services import LeagueService, PlayerService, GameService
# Initialize MCP server
mcp = FastMCP("sports-data")
# Initialize services
league_service = LeagueService(supabase_url=os.getenv("SUPABASE_URL"))
player_service = PlayerService(supabase_url=os.getenv("SUPABASE_URL"))
game_service = GameService(supabase_url=os.getenv("SUPABASE_URL"))
@mcp.tool()
async def get_league_info(league_id: str) -> dict:
"""
Get detailed information about a sports league.
Args:
league_id: Unique league identifier
Returns:
League details including teams, standings, and statistics
"""
league = await league_service.get_by_id(league_id)
if not league:
raise ValueError(f"League {league_id} not found")
return {
"id": league.id,
"name": league.name,
"sport": league.sport,
"teams_count": len(league.teams),
"season": league.current_season,
"standings": await league_service.get_standings(league_id)
}
@mcp.tool()
async def search_players(
query: str,
limit: int = 10
) -> List[dict]:
"""
Search for players across all leagues.
Args:
query: Search query (name, team, position)
limit: Maximum results to return
Returns:
List of matching players
"""
players = await player_service.search(query, limit=limit)
return [
{
"id": p.id,
"name": p.name,
"team": p.team.name,
"position": p.position,
"stats": p.season_stats
}
for p in players
]
@mcp.tool()
async def get_game_stats(game_id: str) -> dict:
"""
Get detailed statistics for a game.
Args:
game_id: Unique game identifier
Returns:
Game statistics including scores, player stats, and events
"""
game = await game_service.get_with_stats(game_id)
if not game:
raise ValueError(f"Game {game_id} not found")
return {
"id": game.id,
"home_team": game.home_team.name,
"away_team": game.away_team.name,
"score": f"{game.home_score} - {game.away_score}",
"status": game.status,
"player_stats": game.player_stats,
"key_events": game.key_events
}
@mcp.tool()
async def predict_winner(
team1_id: str,
team2_id: str
) -> dict:
"""
Predict the winner of a matchup between two teams.
Args:
team1_id: First team identifier
team2_id: Second team identifier
Returns:
Prediction with probability and reasoning
"""
prediction = await game_service.predict_matchup(team1_id, team2_id)
return {
"predicted_winner": prediction.winner.name,
"confidence": prediction.confidence,
"win_probability": prediction.win_probability,
"reasoning": prediction.reasoning,
"key_factors": prediction.key_factors
}
if __name__ == "__main__":
mcp.run()Using in Claude Code:
// .cursor/mcp.json
{
"mcpServers": {
"sports-data": {
"command": "python",
"args": ["-m", "sports_data_mcp"],
"env": {
"SUPABASE_URL": "https://your-project.supabase.co",
"SUPABASE_KEY": "your-api-key"
}
}
}
}Example 3: GraphQL API
Build a GraphQL API with Express and TypeScript.
/agent backend-builder "Create a GraphQL API for user management:
Types:
- User (id, email, name, role, created_at)
- Post (id, title, content, author, published)
- Comment (id, content, author, post, created_at)
Queries:
- users(filter, pagination)
- user(id)
- posts(author_id, published, pagination)
- post(id)
Mutations:
- createUser(input)
- updateUser(id, input)
- deleteUser(id)
- createPost(input)
- publishPost(id)
- addComment(post_id, content)
Features:
- JWT authentication
- DataLoader for N+1 prevention
- Subscriptions for real-time updates
- MongoDB database" --runtime node --framework express --type graphql --database mongodbConfiguration Options
Runtime & Framework
# Python + FastAPI (default)
--runtime python --framework fastapi
# Node.js + Express
--runtime node --framework express
# Node.js + Fastify
--runtime node --framework fastify
# Bun + Hono
--runtime bun --framework hono
# Go + Gin
--runtime go --framework ginAPI Type
# REST API (default)
--type rest-api
# GraphQL API
--type graphql-api
# WebSocket server
--type websocket
# MCP server
--type mcp-server
# gRPC service
--type grpcDatabase
# PostgreSQL
--database postgres
# MongoDB
--database mongo
# Redis
--database redis
# Firestore
--database firestore
# Supabase
--database supabase
# Multiple databases
--database postgres,redisDeployment
# Docker
--deployment docker
# Google Cloud Run
--deployment cloud-run
# AWS Lambda
--deployment lambda
# Kubernetes
--deployment kubernetes
# Vercel Functions
--deployment vercelBest Practices
1. Layered Architecture
Generated code follows clean architecture:
Controller (API) β Service (Business Logic) β Repository (Data Access)2. Security First
All generated APIs include:
- β Input validation (Pydantic, Zod, etc.)
- β Authentication & authorization
- β Rate limiting
- β CORS configuration
- β SQL injection prevention
- β XSS protection
- β Secrets in environment variables
3. Comprehensive Testing
# Unit tests
pytest tests/unit/
# Integration tests
pytest tests/integration/
# E2E tests
pytest tests/e2e/
# Coverage report
pytest --cov=src --cov-report=html4. API Documentation
Auto-generated OpenAPI/Swagger docs:
http://localhost:8080/docs # Swagger UI
http://localhost:8080/redoc # ReDoc
http://localhost:8080/openapi.json # OpenAPI specAdvanced Features
Caching Strategy
# Generated caching layer
from redis import Redis
from functools import wraps
redis_client = Redis.from_url(os.getenv("REDIS_URL"))
def cache(ttl: int = 300):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
cache_key = f"{func.__name__}:{args}:{kwargs}"
# Check cache
cached = redis_client.get(cache_key)
if cached:
return json.loads(cached)
# Compute result
result = await func(*args, **kwargs)
# Store in cache
redis_client.setex(cache_key, ttl, json.dumps(result))
return result
return wrapper
return decoratorBackground Jobs
# Generated background task system
from celery import Celery
celery = Celery('tasks', broker=os.getenv("REDIS_URL"))
@celery.task
def send_email(user_id: str, subject: str, body: str):
"""Send email in background"""
# Email sending logic
pass
# Trigger from API
@router.post("/users/{user_id}/welcome-email")
async def send_welcome_email(user_id: int):
send_email.delay(user_id, "Welcome!", "Welcome message...")
return {"status": "queued"}Monitoring & Observability
# Generated monitoring
from prometheus_client import Counter, Histogram, generate_latest
from opentelemetry import trace
# Metrics
request_count = Counter('http_requests_total', 'Total requests')
request_duration = Histogram('http_request_duration_seconds', 'Request duration')
# Tracing
tracer = trace.get_tracer(__name__)
@app.get("/metrics")
async def metrics():
return Response(content=generate_latest(), media_type="text/plain")Troubleshooting
Database Connection Issues
# Check database connection
python -c "from src.utils.database import db; db.health_check()"
# Run migrations
alembic upgrade head
# Reset database (development only)
docker-compose down -v && docker-compose up -dAuthentication Not Working
# Verify JWT secret is set
echo $JWT_SECRET
# Test auth endpoint
curl -X POST http://localhost:8080/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password"}'Performance Issues
# Enable query logging
DATABASE_LOG_LEVEL=DEBUG uvicorn src.main:app
# Profile requests
python -m cProfile -o profile.stats src/main.py
# Analyze profile
python -m pstats profile.statsNext Steps
- π¨ Frontend Designer - Create UI for your API
- π§ AI Orchestrator - Add AI workflows
- π§ Creating Custom Agents - Build specialized backend agents