api-builder
Skill0 starsChanged 41 days agoMITView on GitHub
Genera una API REST production-ready (FastAPI + Dockerfile + tests + README) a partir de una funcion Python de analisis. Usese al final del flujo cuando el stakeholder quiere consumir el analisis como servicio, no como reporte estatico. La skill inspecciona la firma con stdlib (NO ejecuta side effects), genera codigo en un directorio temporal, valida que importa sin errores, y rollback si falla. Auth opcional via API key (env var); sin auth por default (dev).
- Installs packages
2 other projects use a version of this.
Adopted by
Most recently taken up by
- amanning3390/hermeshubtheir own version, first seen Oct 8, 2026
- kevinaimonster/skill-hubtheir own version, first seen Mar 18, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- amanning3390/hermeshub★ 48same name
- kevinaimonster/skill-hub★ 4same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository24 other files it gives its agents.
- AGENTS.mdAGENTS.md
- ab-testing-analysisSkill
- audit-logSkill
- cohort-retentionSkill
- csv-profilerSkill
- customer-segmentationSkill
- data-quality-contractsSkill
- excel-formulasSkill
- excel-profilerSkill
- feature-engineeringSkill
- insight-synthesisSkill
- ml-modelingSkill
- model-evaluationSkill
- pandas-cleaningSkill
- query-validationSkill
- report-exportSkill
- schema-mapperSkill
- sql-cloud-warehouseSkill
- sql-query-helperSkill
- sql-writeSkill
- statistical-testingSkill
- time-series-patternsSkill
- using-data-analytics-agentsSkill
- viz-patternsSkill
The file
Files
API Builder
Toma una función Python de análisis terminada y la convierte en una API REST
lista para servir con uvicorn. Cierra el ciclo "del análisis al servicio"
mencionado por el video BYOA.
Descripción general
A diferencia de las skills de análisis (que viven en el flujo de trabajo), esta opera al final del pipeline como servicio de empaquetado. Recibe:
- Una ruta a un archivo
.pycon una función callable - El nombre de la función
Y produce en output_dir/:
analysis.py— copia del input originalapp.py— FastAPI app con/health,/schema, y el endpoint de la funciónrequirements.txt— fastapi + uvicorn + pydantic + imports del usuarioDockerfile— python:3.11-slim + uvicornREADME.md— instrucciones de uso local + deploytests/test_app.py— pytest con TestClient de FastAPI
Cuándo usar
Invocar esta skill cuando el pedido matchee con alguno de:
- "Tengo esta función
score_cliente(...). Expónla como API REST." - "Quiero servir el forecast como endpoint para el equipo de pricing."
- "Necesito una API lista para deployar en Railway/Fly/Vercel."
- "Convertime el notebook en un servicio que el front pueda consumir."
No invocar cuando:
- El usuario todavía está explorando datos → seguir en el flujo normal.
- Necesita un dashboard interactivo con UI → eso es Streamlit/Gradio, no REST. Si lo pide, escalar a ADR-003.
- El usuario quiere deployar directamente sin ver el código → fuera de scope v1 (la skill genera código, no deploya).
Flujo de trabajo
- Validar inputs: recibir
--analysis-path,--func-name,--output-dir,--endpoint,--api-key(opcional). Verificar que el archivo existe y que el nombre de función está en el módulo (víainspect, sin ejecutar side effects). - Analizar la función con
analyze_function(path, func_name): extrae signature, type hints, docstring, imports del archivo. Si algún param no tiene type hint, warning al usuario y se usaAny. - Generar código en memoria:
- Pydantic model de input (
generate_pydantic_model) - FastAPI app (
generate_fastapi_app) - Requirements, Dockerfile, README, tests
- Pydantic model de input (
- Validar que el código generado importa sin errores en un directorio
temporal (
validate_generated_app). Si falla, rollback y reportar el error completo al usuario. - Escribir a disco en
output_dir/(conanalysis.pycopiado tal cual). - Reportar la lista de archivos generados + warnings al usuario.
Recetas pre-aprobadas (importables)
import sys
sys.path.insert(0, "ruta/al/repo")
from skills_loader import load_skill_packages
load_skill_packages("skills")
from api_builder.recetas import (
analyze_function, # inspect de la funcion
generate_pydantic_model, # model pydantic del input
generate_fastapi_app, # codigo de app.py
generate_requirements, # requirements.txt
generate_dockerfile, generate_readme, generate_tests,
build_api, # orquestador end-to-end
validate_generated_app, # check de import
)Las recetas son funciones puras excepto build_api (que escribe a
disco). Para testing, se puede llamar cada generate_* por separado.
CLI rápido (uso desde el agente o terminal)
# Demo end-to-end con la funcion score_cliente de muestra
python examples/api_builder_sample/build_demo.py
# O ad-hoc contra tu propia funcion
python -c "
import sys; sys.path.insert(0, '.')
from skills_loader import load_skill_packages
load_skill_packages('skills')
from api_builder.recetas import build_api
result = build_api(
analysis_path='mi_analisis.py',
func_name='mi_funcion',
output_dir='out_api',
endpoint='predict', # opcional, default 'predict'
api_key=None, # opcional, setear para requerir X-API-Key
)
print(result)
"Templates
Los archivos generados NO son hardcodeados — cada generate_* toma
AnalyzeResult y produce un string. Los "templates" están embebidos
en recetas/codegen.py como f-strings.
Si querés customizar el aspecto (e.g. agregar CORS, logging, rate
limiting), editá generate_fastapi_app directamente. Es 1 archivo,
~150 líneas.
Justificaciones comunes
- Por qué FastAPI y no Flask? FastAPI genera docs automáticas en
/docs(Swagger UI), valida inputs con pydantic, y es async-native. Para entregar "ya hay docs en/docs" al manager, gana. - Por qué no usar
exec()para "ver" qué hace la función? Porque podría tener side effects (mandar emails, escribir DB). Solo leemos signature y type hints con stdlib. La función se ejecuta solo cuando el endpoint recibe un request. - Por qué validar en directorio temporal antes de escribir? Para
rollback si el código generado no compila. Mejor fallar limpio que
dejar archivos rotos en
output_dir/. - Por qué API key y no JWT/OAuth? Porque JWT requiere issuer, JWKS, refresh tokens — overkill para v1. API key es 1 línea de código y cubre el caso "no quiero que internet use mi endpoint".
Señales de alerta
- Función sin type hints en sus parámetros → warning, pydantic usa
Any. La API funciona pero sin validación. Sugerir al usuario agregar type hints. - Función con side effects al importar (e.g.
print(),requests.get()a un endpoint externo en el top-level) → esos se ejecutan al cargar el módulo en la API. Warning al usuario. - Función con
*args/**kwargsno soportados → error accionable. output_dir/ya existe con archivos → se sobreescriben. Warning.pip installde requirements falla en runtime → el usuario lo ve cuando correuvicorn app:app, no en la generación.
Verificación
Criterios de "listo" (ver docs/prd/api-builder.md):
examples/api_builder_sample/conanalysis.py(función de scoring) +build_demo.pyque genera la API completa.make test-api-builderejecuta el demo y verifica que:python -c "import app"pasa (validación interna)pytest tests/test_app.pypasa (3/3 OK: health, schema, endpoint)- API responde en vivo:
GET /health,POST /predict,GET /schema
- La skill está en
skills/api-builder/SKILL.mdcon el template de 6 secciones completo. AGENTS.mdactualizado:reporting-analystcargaapi-builderOPCIONAL al final (después dereport-export).package.json:fastapi,uvicorn,pydanticdeclarados como peerDeps opcionales.
Dependencias
- fastapi >= 0.110 — peerDep opcional
- uvicorn[standard] >= 0.27 — peerDep opcional (servidor ASGI)
- pydantic >= 2.0 — peerDep opcional
- pytest + httpx (transitivo de TestClient) — para correr los tests
Si una dep no está, el usuario debe pip install -r requirements.txt
en el directorio generado, no globalmente. La skill no instala nada.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

