API REST en .NET 9 para el tutorial Tour of Heroes de Angular, con soporte para SQL Server y PostgreSQL, observabilidad completa con OpenTelemetry, y despliegue en Azure con Terraform.
| Característica | Descripción |
|---|---|
| 🦸 CRUD de Héroes | API REST completa para gestionar héroes |
| 🗄️ Multi-Base de Datos | Soporte para SQL Server y PostgreSQL |
| 🛡️ Rate Limiting | Protección contra abuso de la API |
| 📊 OpenTelemetry | Trazas, métricas y logs distribuidos |
| 📈 Prometheus | Métricas exportadas en /metrics |
| 🔍 Jaeger | Trazas distribuidas |
| 📉 Grafana | Dashboards de monitorización |
| 🐳 Docker | Contenedores listos para producción |
| ☁️ Terraform | Infraestructura como código para Azure |
| 🧪 Tests | Tests unitarios con xUnit y Moq |
- .NET 9.0 SDK
- Docker (opcional, para base de datos)
Este proyecto incluye un Dev Container con todo lo necesario:
# Abrir en VS Code con la extensión Dev Containers
code .
# Ctrl+Shift+P -> "Dev Containers: Reopen in Container"# Clonar el repositorio
git clone https://github.com/0GiS0/tour-of-heroes-dotnet-api.git
cd tour-of-heroes-dotnet-api
# Restaurar dependencias
dotnet restore
# Ejecutar la API
cd src
dotnet runLa API estará disponible en:
- 🏠 API Info: http://localhost:5020
- 📖 Swagger: http://localhost:5020/swagger
- 📈 Métricas: http://localhost:5020/metrics
La API soporta SQL Server y PostgreSQL. Configura el proveedor con la variable de entorno DATABASE_PROVIDER.
# Iniciar SQL Server con Docker
docker run \
-e 'ACCEPT_EULA=Y' \
-e 'SA_PASSWORD=YourStrong@Password1' \
-e 'MSSQL_PID=Express' \
--name sqlserver \
-p 1433:1433 \
-d mcr.microsoft.com/mssql/server:2022-latestPara Mac con chip ARM:
docker run \
--name azuresqledge \
--cap-add SYS_PTRACE \
-e 'ACCEPT_EULA=1' \
-e 'MSSQL_SA_PASSWORD=YourStrong@Password1' \
-p 1433:1433 \
-d mcr.microsoft.com/azure-sql-edge# Iniciar PostgreSQL con Docker
docker run \
--name postgres \
-e POSTGRES_DB=heroes \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=YourStrong@Password1 \
-p 5432:5432 \
-d postgres:16-alpine| Variable | Descripción | Valores | Default |
|---|---|---|---|
DATABASE_PROVIDER |
Proveedor de BD | SqlServer, PostgreSQL |
SqlServer |
ConnectionStrings__DefaultConnection |
Connection string SQL Server | string | - |
ConnectionStrings__PostgreSQL |
Connection string PostgreSQL | string | - |
Ejemplo de uso:
# Usar PostgreSQL
export DATABASE_PROVIDER=PostgreSQL
export ConnectionStrings__PostgreSQL="Host=localhost;Database=heroes;Username=postgres;Password=YourStrong@Password1"
dotnet run| Método | Ruta | Descripción | Rate Limit |
|---|---|---|---|
GET |
/ |
Información de la API | ✅ |
GET |
/api/health |
Health check | ❌ |
GET |
/api/heroes |
Listar todos los héroes | ✅ |
GET |
/api/heroes/{id} |
Obtener héroe por ID | ✅ |
POST |
/api/heroes |
Crear nuevo héroe | ✅ |
PUT |
/api/heroes/{id} |
Actualizar héroe | ✅ |
DELETE |
/api/heroes/{id} |
Eliminar héroe | ✅ |
GET |
/metrics |
Métricas Prometheus | ❌ |
GET |
/swagger |
Documentación Swagger | ❌ |
# Listar héroes
curl http://localhost:5020/api/heroes
# Crear héroe
curl -X POST http://localhost:5020/api/heroes \
-H "Content-Type: application/json" \
-d '{"name": "Superman", "alterEgo": "Clark Kent"}'
# Obtener héroe
curl http://localhost:5020/api/heroes/1También puedes usar el archivo client.http con la extensión REST Client de VS Code.
El proyecto incluye observabilidad completa con OpenTelemetry:
| Componente | Puerto | URL |
|---|---|---|
| 📈 Prometheus | 9090 | http://localhost:9090 |
| 🔍 Jaeger | 16686 | http://localhost:16686 |
| 📉 Grafana | 3000 | http://localhost:3000 |
http_server_request_duration_seconds- Duración de peticiones HTTPhttp_server_active_requests- Peticiones activasdb_client_operation_duration- Duración de operaciones de BDprocess_cpu_usage- Uso de CPUprocess_memory_usage- Uso de memoria
docker build -t tour-of-heroes-api -f build/docker/Dockerfile .docker run -d \
-p 8080:8080 \
-e "ConnectionStrings__DefaultConnection=Server=host.docker.internal,1433;Database=heroes;User Id=sa;Password=YourPassword;TrustServerCertificate=True" \
tour-of-heroes-apidocker run -d \
-p 8080:8080 \
-e "DATABASE_PROVIDER=PostgreSQL" \
-e "ConnectionStrings__PostgreSQL=Host=host.docker.internal;Database=heroes;Username=postgres;Password=YourPassword" \
tour-of-heroes-apitour-of-heroes-dotnet-api/
├── 📁 src/ # Código fuente de la API
│ ├── 📁 Controllers/ # Controladores REST
│ ├── 📁 Models/ # Modelos y DbContext
│ ├── 📁 Repositories/ # Patrón Repository
│ ├── 📁 Interfaces/ # Interfaces
│ ├── 📄 Program.cs # Punto de entrada
│ └── 📄 appsettings.json # Configuración
├── 📁 tests/ # Tests unitarios
├── 📁 build/
│ ├── 📁 docker/ # Dockerfile
│ └── 📁 scripts/ # Scripts de utilidad
├── 📁 infrastructure/ # Terraform para Azure
├── 📁 docs/ # Documentación adicional
└── 📄 README.md
El proyecto incluye infraestructura como código con Terraform:
cd infrastructure
# Inicializar Terraform
terraform init
# Ver plan de despliegue
terraform plan -var="database_provider=SqlServer"
# Aplicar cambios
terraform apply -var="database_provider=SqlServer"Recursos creados:
- Azure App Service (Windows, .NET 9)
- Azure SQL Database o PostgreSQL Flexible Server (configurable)
- App Service Plan (S1)
- Resource Group
Variables disponibles:
database_provider:SqlServer(default) oPostgreSQL- Ver infrastructure/README.md para más detalles
# Ejecutar todos los tests
cd tests
dotnet test
# Con cobertura
dotnet test --collect:"XPlat Code Coverage"- Fork del repositorio
- Crear rama feature (
git checkout -b feature/AmazingFeature) - Commit de cambios (
git commit -m 'Add AmazingFeature') - Push a la rama (
git push origin feature/AmazingFeature) - Abrir Pull Request
Este proyecto está bajo la licencia MIT. Ver LICENSE para más detalles.
This code was generated by GitHub Copilot 🤖
