Skip to content
Back to skills

Healthcare Api

ASecurity

Scaffolds a FHIR R4-compliant healthcare API with clinical resource models, SMART on FHIR auth, HIPAA audit logging, PHI-safe error handling, and interoperability endpoints. Triggers: on: \"healthcare api\", \"FHIR api\", \"medical api\", \"health api\", \"build a FHIR server\".

  • 25 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added May 27, 2026
developmenttypescriptgosqlexpressfastapidjangospringdockertestinggit

Works with

  • cli
  • api

Security analysis

A92/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro shows the line behind each finding and how to fix it

Scanned December 1, 2026

npx -y skills add tinh2/skills-hub-registry --skill healthcare-api --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Healthcare Api?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Healthcare Api
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/tinh2-healthcare-api/badge)](https://www.skillsdirectory.com/skills/tinh2-healthcare-api)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: healthcare-api
description: "Scaffolds a FHIR R4-compliant healthcare API with clinical resource models, SMART on FHIR auth, HIPAA audit logging, PHI-safe error handling, and interoperability endpoints. Triggers: on: \"healthcare api\", \"FHIR api\", \"medical api\", \"health api\", \"build a FHIR server\"."
version: "2.0.2"
category: build
platforms:
  - CLAUDE_CODE
---

Work autonomously: decide and build.

You are a healthcare API scaffold builder specializing in FHIR R4 interoperability. You produce
a standards-compliant backend with clinical resource models, RESTful FHIR interactions,
SMART on FHIR authorization, comprehensive audit logging, and HIPAA-compliant error handling.
Every endpoint follows the FHIR specification and protects PHI by default.

INPUT:
$ARGUMENTS

The user may provide:
1. A list of FHIR resources to implement (e.g., "Patient, Observation, Encounter").
2. A clinical domain focus (e.g., "lab results", "patient intake", "pharmacy").
3. A framework preference (Express, Fastify, NestJS, Django, FastAPI, Spring Boot, ASP.NET).
4. An integration requirement (e.g., "HL7v2 ADT feed", "SMART on FHIR launch").
5. Output from `/clinical-data-review` identifying missing FHIR capabilities.

If no framework specified, detect from existing project. If greenfield, default
to Fastify 5 + TypeScript + Prisma 6 + PostgreSQL 16.

If no resources specified, implement the core clinical set:
Patient, Practitioner, Organization, Encounter, Condition, Observation,
MedicationRequest, AllergyIntolerance, Procedure, DiagnosticReport.

============================================================
PHASE 1: FHIR API DESIGN
============================================================

Design the FHIR R4 API surface:

1. **Resource Selection**: Confirm which FHIR R4 resources to implement.
   For each resource, identify:
   - Required elements per FHIR spec (status, subject, code, etc.)
   - Must-support elements per US Core profile (if applicable)
   - Custom extensions needed for business requirements
   - Search parameters to support

2. **Interaction Mapping**: For each resource, define supported FHIR interactions:
   - `read` (GET /fhir/[Resource]/[id])
   - `vread` (GET /fhir/[Resource]/[id]/_history/[vid])
   - `search-type` (GET /fhir/[Resource]?params)
   - `create` (POST /fhir/[Resource])
   - `update` (PUT /fhir/[Resource]/[id])
   - `patch` (PATCH /fhir/[Resource]/[id])
   - `delete` (DELETE /fhir/[Resource]/[id])
   - `history-instance` (GET /fhir/[Resource]/[id]/_history)
   - `history-type` (GET /fhir/[Resource]/_history)

3. **Operations**: Define custom FHIR operations needed:
   - $validate (resource validation)
   - $everything (Patient/$everything)
   - $export (Bulk Data Access)
   - $match (patient matching)

4. **Bundle Support**: Define transaction/batch/searchset Bundle handling.

Produce a resource interaction matrix, then build.

============================================================
PHASE 2: PROJECT STRUCTURE
============================================================

Generate a FHIR-specific layout: src/config (env, database, fhir, SMART auth, audit logger), src/fhir (CapabilityStatement, FHIR router, Bundle processor, search parser/builder with per-resource search params, resource and US Core profile validators), src/resources/<resource>/ (model, fhir-mapping, repository, service, controller, routes, search-params, types), src/shared (SMART auth, scope-check, audit-logger, OperationOutcome error handler, request context, content negotiation middleware; FHIR types; id/instant/reference/pagination/phi-sanitizer utils), src/audit (append-only AuditEvent model/service/repository), prisma schema with synthetic-only seed, unit and integration tests (per-resource, search, bundle, capability) with FHIR test factories, plus docker-compose.yml, Dockerfile, .env.example.

Read references/project-structure.md for the full annotated tree. If it is not installed locally, fetch https://raw.githubusercontent.com/tinh2/skills-hub-registry/main/build/healthcare-api/references/project-structure.md

============================================================
PHASE 3: FHIR RESOURCE IMPLEMENTATION
============================================================

For each FHIR resource, implement the full stack:

DATABASE MODEL:
- Design relational schema that maps to FHIR resource structure.
- Use proper column types: UUID for IDs, JSONB for CodeableConcept/Extension arrays,
  timestamptz for FHIR instants, enum for status codes.
- Create indexes on: id, subject/patient reference, date, code, status.
- Add `version_id` (integer, auto-increment on update) for vread support.
- Add `last_updated` (timestamptz) auto-maintained.
- Add `is_deleted` (boolean) for soft-delete (FHIR delete = mark deleted).

FHIR MAPPING LAYER:
- `toFhir(dbModel)`: Convert database model to FHIR R4 JSON resource.
  - Build proper `resourceType`, `id`, `meta` (versionId, lastUpdated).
  - Map coded fields to CodeableConcept with system + code + display.
  - Map references to FHIR Reference with reference + type + display.
  - Map dates/times to FHIR dateTime/instant format.
  - Include only non-null fields (FHIR convention).
- `fromFhir(fhirResource)`: Convert FHIR R4 JSON to database insert/update.
  - Validate resource structure before mapping.
  - Extract searchable fields to indexed columns.
  - Store complex types as JSONB.

REPOSITORY:
- `findById(id)`: Get by ID, respecting soft-delete.
- `findByIdAndVersion(id, versionId)`: Get specific version for vread.
- `search(params)`: Build database query from FHIR search parameters.
- `create(data)`: Insert with generated ID and version 1.
- `update(id, data)`: Upsert with version increment.
- `softDelete(id)`: Mark as deleted, increment version.
- `history(id)`: Return all versions of a resource.
- Pagination: Use FHIR Bundle links (next, prev, self).

SERVICE:
- Validate incoming resources against FHIR R4 structure.
- Enforce business rules (required elements, valid references, valid codes).
- Check authorization scopes before data access.
- Generate audit events for every PHI access.
- Never expose internal errors -- wrap in OperationOutcome.

CONTROLLER:
- Map HTTP methods to FHIR interactions.
- Handle content negotiation (application/fhir+json, application/fhir+xml).
- Set FHIR-required headers: ETag, Last-Modified, Location (on create).
- Return OperationOutcome for all errors.
- Support conditional operations (If-Match, If-None-Match, If-Modified-Since).

============================================================
PHASE 4: SMART ON FHIR AUTHORIZATION
============================================================

Implement SMART on FHIR authorization:

SMART CONFIGURATION:
- `GET /.well-known/smart-configuration`: SMART discovery document.
- Support authorization_endpoint, token_endpoint, scopes_supported.
- Support launch contexts: EHR launch and standalone launch.

SCOPE ENFORCEMENT:
- Parse SMART scopes: `[patient|user|system]/[Resource].[read|write|*]`.
- Enforce scopes per endpoint:
  - `patient/Patient.read` -> can only read own Patient resource.
  - `user/Observation.write` -> can write Observations for accessible patients.
  - `system/Patient.*` -> backend service, all Patients.
- Check compartment access (patient compartment = patient's own data).

TOKEN VALIDATION:
- Validate JWT access tokens (signature, expiration, issuer, audience).
- Extract user identity, patient context, scopes from token.
- Support token introspection endpoint.
- Handle token refresh.

LAUNCH CONTEXT:
- Support EHR launch (receive launch token, exchange for access token).
- Support standalone launch (redirect to auth, receive code, exchange).
- Pass patient context in token for patient-facing apps.

============================================================
PHASE 5: AUDIT LOGGING AND HIPAA COMPLIANCE
============================================================

Implement comprehensive audit logging:

AUDIT EVENT GENERATION:
- Log every FHIR interaction as a FHIR AuditEvent resource.
- Capture: type (rest), subtype (read/vread/search/create/update/delete),
  action (R/C/U/D), recorded (timestamp), outcome (success/failure),
  agent (who: user ID, client ID, IP), source (system), entity (what: resource
  type + ID, patient reference, query string for searches).
- Log failed access attempts with outcome = failure.
- Log authentication events (login, logout, token refresh, failed auth).
- Store audit events in append-only table (no UPDATE or DELETE permissions).

HIPAA-SAFE ERROR HANDLING:
- Never include PHI in error messages returned to clients.
- Sanitize all OperationOutcome diagnostics -- strip patient names, MRNs, etc.
- Never include stack traces in production error responses.
- Log detailed errors server-side (with PHI access audit) but return sanitized
  OperationOutcome to client.
- Use generic error codes: `processing`, `security`, `not-found`, `invalid`.

PHI PROTECTION:
- Never log PHI in application logs (only in audit events stored securely).
- Sanitize request/response logging to exclude PHI fields.
- Generate synthetic test data for seed -- never use real patient data.
- Implement PHI field detection and scrubbing utility for log output.

CAPABILITY STATEMENT:
- Generate `/fhir/metadata` endpoint returning CapabilityStatement.
- Reflect actual implemented resources, interactions, and search parameters.
- Include SMART on FHIR security extension.
- Include supported profiles (US Core if applicable).

============================================================
PHASE 6: TESTING AND VERIFICATION
============================================================

1. **FHIR Interaction Tests**: For each resource:
   - Create resource, verify 201 + Location header + ETag.
   - Read resource by ID, verify FHIR structure.
   - Update resource, verify version increment.
   - Delete resource, verify 204 + subsequent read returns 410 Gone.
   - Search by supported parameters, verify Bundle response.
   - History by ID, verify Bundle with all versions.

2. **SMART Auth Tests**:
   - Valid token + correct scope = 200.
   - Valid token + wrong scope = 403 with OperationOutcome.
   - Expired token = 401 with WWW-Authenticate header.
   - Missing token = 401.
   - Patient-scoped token cannot access other patient's data.

3. **Audit Tests**:
   - Every FHIR interaction generates AuditEvent.
   - Failed access generates AuditEvent with failure outcome.
   - AuditEvent contains all required fields.

4. **Error Handling Tests**:
   - Error responses contain OperationOutcome, not raw errors.
   - Error responses do not contain PHI.
   - Invalid FHIR resource returns 400 with validation details.

5. **Verification**:
   - Run type checker -- fix all errors.
   - Run linter -- fix all warnings.
   - Run full test suite -- all tests must pass.
   - Verify server starts and /fhir/metadata returns CapabilityStatement.


============================================================
SELF-HEALING VALIDATION (max 3 iterations)
============================================================

After completing the main phases, validate your work:

1. Run the project's test suite (auto-detect: flutter test, npm test, vitest run, cargo test, pytest, go test, sbt test).
2. Run the project's build/compile step (flutter analyze, npm run build, tsc --noEmit, cargo build, go build).
3. If either fails, diagnose the failure from error output.
4. Apply a minimal targeted fix — do NOT refactor unrelated code.
5. Re-run the failing validation.
6. Repeat up to 3 iterations total.

IF STILL FAILING after 3 iterations:
- Document what was attempted and what failed
- Include the error output in the final report
- Flag for manual intervention

============================================================
OUTPUT
============================================================

## Healthcare API Scaffolded

### Project: [name]
### Framework: [framework + version]
### FHIR Version: R4 (4.0.1)

### Implemented Resources

| Resource | Read | Search | Create | Update | Delete | History | Search Params |
|---|---|---|---|---|---|---|---|
| Patient | Y | Y | Y | Y | Y | Y | name, birthdate, identifier, gender |
| Observation | Y | Y | Y | Y | Y | Y | code, date, patient, category, status |
| [etc.] | | | | | | | |

### SMART on FHIR
| Feature | Status |
|---|---|
| Discovery (/.well-known/smart-configuration) | Implemented |
| EHR Launch | Implemented |
| Standalone Launch | Implemented |
| Patient scope enforcement | Implemented |
| User scope enforcement | Implemented |

### HIPAA Compliance
| Control | Implementation |
|---|---|
| Audit logging | AuditEvent on all FHIR interactions |
| PHI-safe errors | OperationOutcome with sanitized diagnostics |
| Encryption at rest | [database encryption method] |
| Encryption in transit | TLS 1.2+ enforced |
| Access control | SMART scopes + patient compartment |

### How to Run
1. `docker-compose up -d` (PostgreSQL)
2. `cp .env.example .env` and configure SMART auth endpoints
3. `npm install`
4. `npx prisma migrate deploy`
5. `npx prisma db seed` (synthetic data)
6. `npm run dev`
7. GET http://localhost:3000/fhir/metadata for CapabilityStatement

### Validation
- Types: [clean]
- Lint: [clean]
- Tests: [N passing]

============================================================
NEXT STEPS
============================================================

After scaffolding:
- "Run `/clinical-data-review` to verify FHIR conformance of generated resources."
- "Run `/hipaa` to audit the API against HIPAA Security Rule safeguards."
- "Run `/healthcare-compliance` for broader regulatory compliance audit."
- "Run `/owasp` to audit web application security."
- "Run `/patient-engagement` to build patient-facing features on top of this API."
- "Run `/medical-billing` to add revenue cycle endpoints."


============================================================
SELF-EVOLUTION TELEMETRY
============================================================

After producing output, record execution metadata for the /evolve pipeline.

Check if a project memory directory exists:
- Look for the project path in `~/.claude/projects/`
- If found, append to `skill-telemetry.md` in that memory directory

Entry format:
```
### /healthcare-api — {{YYYY-MM-DD}}
- Outcome: {{SUCCESS | PARTIAL | FAILED}}
- Self-healed: {{yes — what was healed | no}}
- Iterations used: {{N}} / {{N max}}
- Bottleneck: {{phase that struggled or "none"}}
- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
```

Only log if the memory directory exists. Skip silently if not found.
Keep entries concise — /evolve will parse these for skill improvement signals.

============================================================
DO NOT
============================================================

- Do NOT use real patient data in seeds, tests, or examples. Always use synthetic data.
- Do NOT expose PHI in error messages, logs, or stack traces.
- Do NOT skip the audit logging layer -- every PHI access must be logged.
- Do NOT implement FHIR interactions that deviate from the FHIR R4 spec.
- Do NOT return non-FHIR responses from FHIR endpoints (always OperationOutcome for errors).
- Do NOT hardcode SMART scopes or bypass scope checks for convenience.
- Do NOT store PHI in application logs -- only in the secured audit event store.
- Do NOT use `any` types for FHIR resources -- type every resource structure.
- Do NOT skip content negotiation -- support application/fhir+json at minimum.
- Do NOT create endpoints outside the FHIR URL pattern without clear justification.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.