# SDK

> Dart / Flutter (anpheros_sdk) 및 TypeScript (@anpheros/sdk) 클라이언트: 동일한 구조, 멱등성 생성, 재시도, 토큰 새로고침 및 동의 흐름.

Source: https://developers.anpheros.com/ko/guides/sdks

> 무료 FHIR 샌드박스를 갖춘 FHIR R4 의료 API용 공식 클라이언트 라이브러리: 환자, 관찰, 검사 결과, 상태, 약물, 국제 환자 요약, 환자 동의 및 AI 컨텍스트 (TypeScript 및 Dart / Flutter).

**Anpheros는 의료 애플리케이션, 의료 소프트웨어 및 AI 서비스를 구축하기 위한 상호 운용 가능한 의료 데이터 인프라입니다.** 각 환자는 자신이 제어하는 하나의 HL7 FHIR R4 레코드를 가집니다. 애플리케이션, 클리닉, 실험실 및 AI 에이전트는 환자 동의 (OAuth 2.1 / SMART on FHIR), 모든 쓰기에 대한 출처 및 환자가 볼 수 있는 액세스 로그를 통해 Anpheros Platform API를 통해 이를 읽고 씁니다. 이 저장소에는 공식 클라이언트 라이브러리와 실행 가능한 예제가 포함되어 있습니다.

| 언어 | 패키지 | 설치 | 소스 |
|---|---|---|---|
| Dart / Flutter | [`anpheros_sdk`](https://pub.dev/packages/anpheros_sdk) | `dart pub add anpheros_sdk` | [`dart/anpheros_sdk`](https://github.com/anpheros/anpheros-sdk/tree/main/dart/anpheros_sdk) |
| TypeScript (Node 18+, 브라우저, Deno, Bun) | [`@anpheros/sdk`](https://www.npmjs.com/package/@anpheros/sdk) | `npm install @anpheros/sdk` | [`ts`](https://github.com/anpheros/anpheros-sdk/tree/main/ts) |

## 2분 만에 시작하기

1. **무료 샌드박스 키 받기:** [대시보드](https://platform.anpheros.com/dashboard/)에 로그인하고 **샌드박스 키 받기** (`sk_test_…`)를 누르세요. 샌드박스에는 30명의 합성 환자가 있습니다.
2. **작동 확인:**

   ```bash
   curl -H "Authorization: Bearer $ANPHEROS_KEY" "https://platform.anpheros.com/fhir/R4/Patient?_count=3"
   ```

3. **SDK 설치 및 레코드 읽기:** `npm install @anpheros/sdk` 또는 `dart pub add anpheros_sdk`을 설치하고 [Connect](#connect) 아래의 코드를 실행하거나 [quickstart-ts](https://github.com/anpheros/anpheros-sdk/tree/main/examples/quickstart-ts)를 클론하세요.

## 대상

환자 및 가족 건강 앱, 의료 앱 백엔드, 진료소 및 실험실 통합, 환자의 구조화된 의료 컨텍스트가 필요한 AI 어시스턴트 또는 에이전트를 구축하는 개발자 — 의료 데이터베이스, 동의 시스템 및 감사 추적을 처음부터 설계할 필요 없이.

## 샌드박스 키 받기

샌드박스는 무료이며 셀프 서비스입니다. [대시보드](https://platform.anpheros.com/dashboard/)에서 Google로 로그인하고 **샌드박스 키 받기**를 누르면 즉시 샌드박스 프로젝트와 키를 얻을 수 있습니다. 각 샌드박스 프로젝트에는 30명의 합성 환자가 포함되어 있습니다. 이 환자들은 6개월간의 질병, 약물, 알레르기, 검사 결과 및 활력 징후 데이터를 가지며, 자유롭게 변경하고 언제든지 재설정할 수 있습니다. 샌드박스 키(`sk_test_…`)는 실제 환자 데이터에 접근하지 않습니다.

라이브 환경으로 전환 시, 프로덕션은 데이터 처리 계약이 있는 검증된 조직을 대상으로 하며, 월 €99부터 시작하고 첫 달은 무료입니다 ([가격](https://developers.anpheros.com/ko/guides/pricing)).

## 연결

```ts
import { Anpheros, apiKey } from '@anpheros/sdk';

const anpheros = new Anpheros({ auth: apiKey(process.env.ANPHEROS_KEY!) });   // sk_test_… in the sandbox
const { data: patients } = await anpheros.patients.list();
const labs = await anpheros.observations.list(patients[0].id, { category: 'laboratory', limit: 10 });
const ctx = await anpheros.context.build({ patient: patients[0].id, task: 'weekly check-in', budget_tokens: 1500, format: 'text' });
```

```dart
import 'package:anpheros_sdk/anpheros_sdk.dart';

final anpheros = Anpheros(auth: AnpherosAuth.apiKey('sk_test_…'));
final patients = await anpheros.patients.list();
final labs = await anpheros.observations.list(patients.data.first.id, category: 'laboratory', limit: 10);
```

API 키는 서버에 있어야 합니다. 개인을 대신하여 작동하는 앱은 OAuth를 사용합니다. 두 SDK 모두 동의 흐름(권한 부여 코드 + PKCE)을 구현하고 토큰을 자동으로 새로 고칩니다.

## SDK에서 다루는 내용

두 SDK 모두 동일한 구조로 공개된 모든 API 엔드포인트(`/v1`, `/fhir/R4`, `/oauth/token`, `/oauth/revoke`)를 다룹니다. 여기에는 `patients`, `observations`, `conditions`, `medications`, `documents`, `timeline`, `provenance`, `context`, `grants`, `terminology` 및 원시 `fhir`가 포함됩니다. 공개된 라우트가 SDK에 누락되거나 SDK가 서버에 없는 라우트를 호출하는 경우 테스트는 빌드를 실패시킵니다.

두 SDK 모두 다음 기능을 제공합니다: 생성 시 자동 `Idempotency-Key`, 429/5xx 오류 발생 시 백오프를 사용한 재시도, 401 오류 시 토큰 1회 새로고침, 요청 ID가 포함된 타입화된 오류, PKCE 헬퍼 및 동의 흐름.

## 의료 데이터 및 FHIR

이 레코드는 표준 FHIR R4 리소스로 구성됩니다. `Observation`, `Condition`, `MedicationStatement`, `DocumentReference`, `Immunization` 및 `AllergyIntolerance`를 포함한 26가지 유형이며, LOINC, ICD-10, ATC 및 UCUM으로 코딩됩니다. REST API (`/v1`) 및 FHIR API (`/fhir/R4`)는 동일한 ID를 사용하여 동일한 리소스를 읽고 씁니다. 두 SDK 모두에서 `fhir`는 원시 FHIR 액세스(검색, 트랜잭션, `$everything`, `$summary`, `$validate`)를 제공합니다.

## 예제

| 예제 | 설명 |
|---|---|
| [quickstart-ts](https://github.com/anpheros/anpheros-sdk/tree/main/examples/quickstart-ts) | 레코드 작성 및 읽기: 측정값, 검사 결과, 진단, 약물, 타임라인, FHIR 검색, IPS, AI 컨텍스트 |
| [quickstart-dart](https://github.com/anpheros/anpheros-sdk/tree/main/examples/quickstart-dart) | Dart / Flutter에서의 동일한 기능 |
| [consent-app-ts](https://github.com/anpheros/anpheros-sdk/tree/main/examples/consent-app-ts) | 동의 요청 (OAuth 2.1 + PKCE) 및 개인 레코드 읽기 웹 앱 |
| [ai-context-llm](https://github.com/anpheros/anpheros-sdk/tree/main/examples/ai-context-llm) | 선택한 모델 (로컬 또는 호스팅)으로 답변하는 레코드 관련 질문 |
| [fhir-transaction](https://github.com/anpheros/anpheros-sdk/tree/main/examples/fhir-transaction) | FHIR R4 트랜잭션 번들 및 결과 국제 환자 요약 |

예제는 무료 샌드박스에서 실행됩니다. 각 샌드박스 프로젝트에는 자체적인 30명의 합성 환자가 있습니다. [샌드박스 키 받기](#get-a-sandbox-key)를 참조하십시오.

## 관련 저장소

| 저장소 | 설명 |
|---|---|
| [fhir-api-openapi](https://github.com/anpheros/fhir-api-openapi) | API의 OpenAPI 3.1 사양 및 Postman 컬렉션 |
| [mcp-server](https://github.com/anpheros/mcp-server) | AI 에이전트용 호스팅 FHIR MCP 서버: Claude, Cursor, VS Code용 구성 |
| [agent-skills](https://github.com/anpheros/agent-skills) | Agent Skill, Claude Code 플러그인, Cursor 규칙 및 AGENTS.md |
| [fhir-synthetic-patients](https://github.com/anpheros/fhir-synthetic-patients) | FHIR R4 번들 및 NDJSON 형식의 합성 환자 30명 |
| [ips-examples](https://github.com/anpheros/ips-examples) | FHIR R4 형식의 국제 환자 요약(International Patient Summary) 문서 |
| [fhir-validate-action](https://github.com/anpheros/fhir-validate-action) | CI에서 FHIR R4 JSON을 검증하는 GitHub Action |
| [lab-results-to-fhir](https://github.com/anpheros/lab-results-to-fhir) | CLI: CSV / HL7 v2 검사 결과 보고서 → FHIR Observations |
| [healthcare-app-starters](https://github.com/anpheros/healthcare-app-starters) | Next.js 및 Flutter 건강 앱 템플릿 |

## 규정 준수

원시 테스트 결과는 확인을 위해 게시됩니다 (인증이 아닌 테스트 결과): [conformance/](https://github.com/anpheros/anpheros-sdk/tree/main/conformance). 2026년 9월 28일, Inferno SMART App Launch STU2 테스트 키트(v1.0.3)의 Standalone Launch 그룹이 플랫폼에 대해 22개 중 22개 테스트를 통과했습니다. EHR 시작은 지원되지 않습니다.

## 문서

- [개발자 가이드](https://developers.anpheros.com/guides/)
- [시작하기](https://developers.anpheros.com/ko/guides/getting-started)
- [FHIR 샌드박스](https://developers.anpheros.com/ko/guides/fhir-sandbox)
- [Healthcare API](https://developers.anpheros.com/ko/guides/healthcare-api)
- [Healthcare API 플랫폼](https://developers.anpheros.com/ko/guides/healthcare-api-platform)
- [FHIR 플랫폼](https://developers.anpheros.com/ko/guides/fhir)
- [SDK 가이드](https://developers.anpheros.com/ko/guides/sdks)
- [API 참조 (OpenAPI)](https://developers.anpheros.com/docs)
- [AI 어시스턴트용](https://developers.anpheros.com/llms.txt)
- [Anpheros](https://anpheros.com/)

## 이슈 및 보안

이 저장소의 이슈에 버그를 보고하십시오. 이슈에 API 키, 토큰 또는 환자 데이터를 절대 포함하지 마십시오. 보안 보고: contact@anpheros.com.

## 라이선스

Apache License 2.0 — 각 패키지의 `LICENSE` 파일을 참조하십시오. Copyright 2026 Anpheros.

## @anpheros/sdk

**Anpheros Platform**을 위한 TypeScript 클라이언트: 환자별 FHIR R4 건강 기록, 프로젝트 격리, 환자 동의 (OAuth 2.1 / SMART on FHIR), 모든 쓰기에 대한 출처 증명 및 AI 컨텍스트 API. `fetch`이 있는 모든 곳 (Node 18 이상, 브라우저, Deno, Bun)에서 실행됩니다.

```ts
import { Anpheros, apiKey } from '@anpheros/sdk';

const anpheros = new Anpheros({ auth: apiKey(process.env.ANPHEROS_KEY!) });
const { data: patients } = await anpheros.patients.list();
const labs = await anpheros.observations.list(patients[0].id, { category: 'laboratory', limit: 10 });
const ctx = await anpheros.context.build({ patient: patients[0].id, task: 'weekly check-in', budget_tokens: 1500, format: 'text' });
```

개인을 대신하여 행동:

```ts
import { OAuthFlow, OAuthAuth, generatePkce } from '@anpheros/sdk';

const flow = new OAuthFlow({ baseUrl: BASE, clientId: 'client_…', redirectUri: 'https://myapp.example/callback' });
const pkce = await generatePkce();
location.href = flow.authorizeUrl({ scopes: ['patient/Observation.rs?category=laboratory', 'offline_access'], state, pkce, lang: 'ro' });
// on the callback:
const tokens = await flow.exchange(code, pkce);
const anpheros = new Anpheros({ auth: new OAuthAuth({ tokens, onRefresh: flow.refresh, onTokens: persist }) });
```

오류는 `AnpherosError` (`status`, `type`, `message`, `field`, `requestId`)입니다. 생성은 `Idempotency-Key`을 보냅니다. 429/5xx는 재시도됩니다. 만료된 토큰은 한 번 새로 고침되고 호출이 재시도됩니다.

## anpheros_sdk

**Anpheros Platform**용 Dart / Flutter 클라이언트: 환자별 FHIR R4 레코드, 프로젝트 격리, 환자 동의 (OAuth 2.1 / SMART on FHIR), 모든 쓰기에 대한 출처 추적 및 AI 컨텍스트 API를 갖춘 건강 데이터 백엔드입니다.

```dart
import 'package:anpheros_sdk/anpheros_sdk.dart';

final anpheros = Anpheros(auth: AnpherosAuth.apiKey('sk_test_…'));      // server / sandbox

final patients = await anpheros.patients.list();
final elena = patients.data.first;
final labs = await anpheros.observations.list(elena.id, category: 'laboratory', limit: 10);
final ctx = await anpheros.context.build(ContextRequest(patient: elena.id, task: 'weekly check-in', budgetTokens: 1500));
```

## 개인을 위한 행동 (앱)

```dart
final flow = OAuthFlow(baseUrl: 'https://…', clientId: 'client_…', redirectUri: 'myapp://callback');
final pkce = Pkce.generate();
final url = flow.authorizeUrl(scopes: ['patient/Observation.rs?category=laboratory', 'patient/MedicationStatement.r', 'offline_access'],
                              state: 'abc', pkce: pkce, lang: 'ro');
// open `url`; on return with ?code=…:
final tokens = await flow.exchange(code: code, pkce: pkce);
final anpheros = Anpheros(auth: AnpherosAuth.oauth(
  accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, expiresAt: tokens.expiresAt,
  onRefresh: flow.refresh, onTokens: persist));
final meds = await anpheros.medications.listMedications(tokens.patient!);
```

모든 객체는 `fhir` (해당 `/fhir/R4` 참조)를 가지고 있으며, `anpheros.fhir`은 원시 FHIR 액세스(읽기, 검색, 생성, 트랜잭션, `$everything`, `$summary`, `$validate`)를 제공합니다.

오류는 `AnpherosException`, `status`, `type`, `message`, `field` 및 `requestId`과 함께 처리됩니다.
생성 시 `Idempotency-Key`이 자동으로 전송됩니다. 429/5xx 오류는 백오프(backoff)를 사용하여 재시도되며, 만료된 OAuth 토큰은 한 번 새로고침된 후 호출이 재시도됩니다.
