🚀 API Service - Sistem Manajemen Pasien
Sistem manajemen pasien modern dengan arsitektur bersih untuk pengelolaan data kesehatan dan integrasi layanan kesehatan
📑 Daftar Isi
- ✨ Fitur Utama
- 🏗️ Arsitektur
- ⚡ Quick Start
- 🔐 Autentikasi
- 📊 API Endpoints
- 🛠️ Development
- 🚀 Deployment
- 📚 Dokumentasi
- 🚨 Troubleshooting
✨ Fitur Utama
Core Features
- 🔒 JWT Authentication - Sistem autentikasi dengan Keycloak integration
- 👥 Patient Management - CRUD lengkap untuk data pasien
- 🔍 Dynamic Filtering - Filter dan pencarian data pasien secara dinamis
- 📊 Advanced Search - Pencarian dengan multiple fields dan operators
- 🏥 BPJS Integration - Integrasi dengan layanan kesehatan BPJS
- 🩺 SATUSEHAT Integration - Integrasi dengan platform kesehatan SATUSEHAT
- 📖 API Documentation - Swagger/OpenAPI yang interaktif
Developer Experience
- 🔥 Hot Reload - Development dengan auto-restart
- 🐳 Docker Ready - Deployment yang mudah
- ⚡ Code Generator - Tools untuk generate handler dan model
- 🧪 Testing Suite - Unit dan integration tests
- 📊 Health Monitoring - Monitoring kesehatan aplikasi
- 🗄️ Multi Database - Support PostgreSQL, MySQL, dan MongoDB
🏗️ Arsitektur
Clean Architecture Layers
┌─────────────────────────────────────┐
│ Presentation Layer │ ← handlers/, routes/
├─────────────────────────────────────┤
│ Application Layer │ ← middleware/, services/
├─────────────────────────────────────┤
│ Domain Layer │ ← models/, validation/
├─────────────────────────────────────┤
│ Infrastructure Layer │ ← database/, external APIs
└─────────────────────────────────────┘
Struktur Project
api-service/
├── 📁 cmd/ # Entry points aplikasi
│ ├── api/main.go # API server
│ └── logging/main.go # Logging service
├── 📁 internal/ # Core business logic
│ ├── config/ # Configuration management
│ ├── database/ # Database connections
│ ├── handlers/ # HTTP controllers
│ │ ├── auth/ # Authentication handlers
│ │ ├── healthcheck/ # Health check handlers
│ │ └── pasien/ # Pasien handlers
│ ├── middleware/ # Auth & validation middleware
│ ├── models/ # Data structures
│ │ ├── auth/ # Auth models
│ │ └── pasien/ # Pasien models
│ ├── routes/ # API routing
│ ├── services/ # Business logic services
│ │ └── auth/ # Auth services
│ ├── utils/ # Utility functions
│ │ ├── filters/ # Dynamic filtering
│ │ └── validation/ # Data validation
│ └── server/ # HTTP server setup
├── 📁 docs/ # Documentation
├── 📁 examples/ # Example files
├── 📁 scripts/ # Automation scripts
└── 📁 tools/ # Development tools
⚡ Quick Start
1️⃣ Setup Environment (2 menit)
# Clone repository
git clone <repository-url>
cd api-service
# Setup environment
cp example.env .env
2️⃣ Pilih Method Setup
🐳 Docker (Recommended)
make docker-run
🔧 Manual Setup
# Install dependencies
go mod download
# Start server
go run cmd/api/main.go
3️⃣ Update Swagger Documentation
swag init -g cmd/api/main.go -o docs/
4️⃣ Verify Installation
| Service | URL | Status |
|---|---|---|
| API | http://localhost:8080/api/v1 | ✅ |
| Swagger | http://localhost:8080/swagger/index.html | 📖 |
| Health Check | http://localhost:8080/api/sistem/health | 💚 |
🔐 Autentikasi
Login & Mendapatkan Token
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"username": "admin",
"password": "password"
}'
Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"expires_in": 3600,
"user": {
"id": "123",
"username": "admin",
"role": "admin"
}
}
Menggunakan Token
curl -X GET http://localhost:8080/api/v1/pasien \
-H "Authorization: Bearer <your-token>"
Demo Accounts
| Username | Password | Role | Akses |
|---|---|---|---|
admin |
password |
Admin | Semua endpoint |
dokter |
password |
Dokter | Akses terbatas |
perawat |
password |
Perawat | Read-only |
📊 API Endpoints
🌍 Public Endpoints
| Method | Endpoint | Deskripsi |
|---|---|---|
POST |
/api/v1/auth/login |
Login pengguna |
POST |
/api/v1/auth/register |
Registrasi pengguna baru |
GET |
/api/sistem/health |
Status kesehatan API |
GET |
/api/sistem/info |
Informasi sistem |
🔒 Protected Endpoints
System Information
| Method | Endpoint | Deskripsi |
|---|---|---|
GET |
/api/sistem/databases |
Informasi database connections |
Patient Management
| Method | Endpoint | Deskripsi |
|---|---|---|
GET |
/api/v1/pasien |
List semua pasien dengan pagination |
GET |
/api/v1/pasien/dynamic |
Query pasien dengan filter dinamis |
GET |
/api/v1/pasien/search |
Pencarian pasien advanced |
GET |
/api/v1/pasien/id/:id |
Detail pasien by ID |
GET |
/api/v1/pasien/nik/:nik |
Detail pasien by NIK |
POST |
/api/v1/pasien |
Buat pasien baru |
PUT |
/api/v1/pasien/id/:id |
Update data pasien |
DELETE |
/api/v1/pasien/id/:id |
Hapus data pasien (soft delete) |
Medical Records
| Method | Endpoint | Deskripsi |
|---|---|---|
GET |
/api/v1/pasien/:id/medical-records |
Riwayat medis pasien |
POST |
/api/v1/pasien/:id/medical-records |
Tambah rekam medis |
GET |
/api/v1/pasien/:id/medical-records/:recordId |
Detail rekam medis |
Dynamic Query Examples
Filter berdasarkan jenis kelamin:
GET /api/v1/pasien/dynamic?filter[jenis_kelamin][_eq]=L
Kombinasi filter:
GET /api/v1/pasien/dynamic?filter[status][_eq]=active&filter[umur][_gt]=18
Pagination dan sorting:
GET /api/v1/pasien/dynamic?sort=-tanggal_daftar&limit=10&offset=20
Advanced search:
GET /api/v1/pasien/search?q=andi&limit=20&offset=0
🏥 External Integrations
BPJS Integration
| Method | Endpoint | Deskripsi |
|---|---|---|
GET |
/api/v1/bpjs/peserta/:no |
Data peserta BPJS |
GET |
/api/v1/bpjs/rujukan/:no |
Data rujukan |
POST |
/api/v1/bpjs/rujukan |
Buat rujukan baru |
SATUSEHAT Integration
| Method | Endpoint | Deskripsi |
|---|---|---|
GET |
/api/v1/satusehat/patient/:id |
Data pasien SATUSEHAT |
POST |
/api/v1/satusehat/patient |
Buat pasien di SATUSEHAT |
GET |
/api/v1/satusehat/encounter/:id |
Data kunjungan |
POST |
/api/v1/satusehat/encounter |
Buat kunjungan baru |
🛠️ Development
Development Commands
# 🔥 Development dengan hot reload
make watch
# 🏃 Run server
make run
# 🧪 Testing
make test # Unit tests
make itest # Integration tests
# 🐳 Docker operations
make docker-run # Start all services
make docker-down # Stop all services
# 🔍 Code quality
make build # Build application
make clean # Clean build artifacts
Environment Configuration
📁 .env File:
# Server Configuration
PORT=8080
GIN_MODE=debug
# Database Configuration
DB_CONNECTION=postgres
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres
DB_DATABASE=api_service
# PostgreSQL Satudata Database
POSTGRES_SATUDATA_CONNECTION=postgres
POSTGRES_SATUDATA_HOST=localhost
POSTGRES_SATUDATA_PORT=5432
POSTGRES_SATUDATA_USERNAME=postgres
POSTGRES_SATUDATA_PASSWORD=postgres
POSTGRES_SATUDATA_DATABASE=satu_db
# MongoDB Configuration
MONGODB_MONGOHL7_CONNECTION=mongodb
MONGODB_MONGOHL7_HOST=localhost
MONGODB_MONGOHL7_PORT=27017
MONGODB_MONGOHL7_USER=admin
MONGODB_MONGOHL7_PASS=password
# MySQL Medical Database
MYSQL_MEDICAL_CONNECTION=mysql
MYSQL_MEDICAL_HOST=localhost
MYSQL_MEDICAL_PORT=3306
MYSQL_MEDICAL_USERNAME=user
MYSQL_MEDICAL_PASSWORD=password
MYSQL_MEDICAL_DATABASE=healtcare_database
# JWT Configuration
JWT_SECRET=your-super-secret-key-change-in-production
# Keycloak Configuration
KEYCLOAK_ISSUER=${KEYCLOAK_ISSUER_URL}
KEYCLOAK_AUDIENCE=${KEYCLOAK_AUDIENCE_VALUE}
KEYCLOAK_JWKS_URL=${KEYCLOAK_JWKS_URL_VALUE}
KEYCLOAK_ENABLED=true
# BPJS Configuration
BPJS_BASEURL=${BPJS_API_URL}
BPJS_CONSID=${BPJS_CONSID_VALUE}
BPJS_USERKEY=${BPJS_USERKEY_VALUE}
BPJS_SECRETKEY=${BPJS_SECRETKEY_VALUE}
# SATUSEHAT Configuration
SATUSEHAT_BASEURL=${SATUSEHAT_API_URL}
SATUSEHAT_CLIENT_ID=${SATUSEHAT_CLIENT_ID_VALUE}
SATUSEHAT_CLIENT_SECRET=${SATUSEHAT_CLIENT_SECRET_VALUE}
Code Generation
Generate Handler untuk Pasien:
# Config
go run tools/general/generate-handler.go --config tools/general/services-config.yaml --verbose
🚀 Deployment
🐳 Docker Deployment
Development:
# Start semua services
make docker-run
# Stop services
make docker-down
Production:
# Build production image
docker build -t api-service:prod .
# Run production container
docker run -d \
--name api-service \
-p 8080:8080 \
--env-file .env.prod \
api-service:prod
🔧 Manual Deployment
# Build aplikasi
make build
# Start server
./main
📋 Environment Variables untuk Production
# Server Configuration
APP_ENV=production
PORT=8080
GIN_MODE=release
# Database Configuration
DB_CONNECTION=postgres
DB_HOST=${DB_HOST_VALUE}
DB_PORT=5432
DB_USERNAME=${DB_USERNAME_VALUE}
DB_PASSWORD=${DB_PASSWORD_VALUE}
DB_DATABASE=${DB_DATABASE_VALUE}
# Security
JWT_SECRET=${JWT_SECRET_VALUE}
KEYCLOAK_ENABLED=true
# External Services
BPJS_BASEURL=${BPJS_PRODUCTION_URL}
SATUSEHAT_BASEURL=${SATUSEHAT_PRODUCTION_URL}
📚 Dokumentasi
📖 Interactive API Documentation
Kunjungi Swagger UI di: http://localhost:8080/swagger/index.html
Cara menggunakan:
- 🔑 Login melalui
/auth/loginendpoint - 📋 Copy token dari response
- 🔓 Klik tombol "Authorize" di Swagger
- 📝 Masukkan:
Bearer <your-token> - ✅ Test semua endpoint yang tersedia
🧪 Testing Examples
JavaScript/Axios:
// Login dan set token
const auth = await axios.post('/api/v1/auth/login', {
username: 'admin',
password: 'password'
});
axios.defaults.headers.common['Authorization'] =
`Bearer ${auth.data.access_token}`;
// Fetch patient data
const patients = await axios.get('/api/v1/pasien');
console.log(patients.data);
// Create new patient
const newPatient = await axios.post('/api/v1/pasien', {
nama: "John Doe",
nik: "1234567890123456",
tanggal_lahir: "1990-01-01",
jenis_kelamin: "L",
alamat: "Jl. Contoh No. 123"
});
cURL Examples:
# Login
TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"password"}' | jq -r '.access_token')
# Get patient data
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/pasien
# Dynamic filtering
curl -H "Authorization: Bearer $TOKEN" \
"http://localhost:8080/api/v1/pasien/dynamic?filter[jenis_kelamin][_eq]=L"
# Create new patient
curl -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"nama": "Jane Doe",
"nik": "6543210987654321",
"tanggal_lahir": "1985-05-15",
"jenis_kelamin": "P",
"alamat": "Jl. Contoh No. 456"
}' \
http://localhost:8080/api/v1/pasien
🔍 Health Monitoring
# Basic health check
curl http://localhost:8080/api/sistem/health
# Database status
curl http://localhost:8080/api/sistem/databases
# System info
curl http://localhost:8080/api/sistem/info
Response:
{
"status": "healthy",
"timestamp": "2025-01-10T05:39:00Z",
"services": {
"database": "connected",
"keycloak": "accessible",
"bpjs_api": "accessible",
"satusehat_api": "accessible"
},
"version": "1.0.0"
}
🚨 Troubleshooting
Masalah Umum
❌ Database Connection Error
# Cek status database
make docker-run
# Check logs
docker logs api-service
# Verify environment variables
cat .env | grep DB_
❌ Authentication Error
- 🔄 Pastikan Keycloak service berjalan
- ✅ Cek KEYCLOAK_ISSUER URL
- 📝 Format token harus:
Bearer <token>
❌ Dynamic Filter Error
- ✅ Pastikan field name sesuai dengan database
- 🔍 Cek syntax filter:
filter[field][operator]=value - 📝 Operator yang didukung:
_eq,_neq,_gt,_lt,_contains
❌ BPJS/SATUSEHAT Integration Error
- ✅ Verifikasi kredensial API
- 🔄 Cek koneksi ke layanan eksternal
- 📝 Pastikan format data sesuai dengan spesifikasi
Debug Mode
# Enable debug logging
export GIN_MODE=debug
# Run dengan verbose output
make run
# Monitor dengan hot reload
make watch
🎯 Next Steps
📋 Development Roadmap
- Setup environment selesai
- Implementasi patient management
- Setup authentication dengan Keycloak
- Integrasi BPJS dan SATUSEHAT
- Testing dan validation
- Setup monitoring dan logging
- Deploy ke production
🚀 Advanced Features
- 📊 Real-time Dashboard
- 🔒 Enhanced Security (Rate limiting, CORS)
- 📈 Performance Monitoring
- 🌐 API Versioning
- 📱 Mobile SDK Integration
⚡ Total setup time: 5 menit | 🔧 Generate Handler: 30 detik | 🧪 Testing: Langsung via Swagger
💡 Pro Tip: Gunakan
make helpuntuk melihat semua command yang tersedia
🔐 Keamanan & Konfigurasi
Environment Variables untuk Production
Untuk keamanan, semua konfigurasi sensitif harus menggunakan environment variables:
# Keycloak Configuration
KEYCLOAK_ISSUER=${KEYCLOAK_ISSUER_URL}
KEYCLOAK_AUDIENCE=${KEYCLOAK_AUDIENCE_VALUE}
KEYCLOAK_JWKS_URL=${KEYCLOAK_JWKS_URL_VALUE}
# BPJS Configuration
BPJS_BASEURL=${BPJS_API_URL}
BPJS_CONSID=${BPJS_CONSID_VALUE}
BPJS_USERKEY=${BPJS_USERKEY_VALUE}
BPJS_SECRETKEY=${BPJS_SECRETKEY_VALUE}
# SATUSEHAT Configuration
SATUSEHAT_BASEURL=${SATUSEHAT_API_URL}
SATUSEHAT_CLIENT_ID=${SATUSEHAT_CLIENT_ID_VALUE}
SATUSEHAT_CLIENT_SECRET=${SATUSEHAT_CLIENT_SECRET_VALUE}
# Database Configuration
DB_HOST=${DB_HOST_VALUE}
DB_USERNAME=${DB_USERNAME_VALUE}
DB_PASSWORD=${DB_PASSWORD_VALUE}
DB_DATABASE=${DB_DATABASE_VALUE}
# Security
JWT_SECRET=${JWT_SECRET_VALUE}
Best Practices
- Jangan pernah commit file .env ke repository
- Gunakan environment variables untuk semua data sensitif
- Gunakan secret management tools untuk production
- Rotasi kunci API secara berkala
- Implementasi rate limiting untuk API endpoints