FHIR® tutorials FHIR® уроки

Working with APIs for FHIR

If you're a developer, or just someone interested in coding with FHIR, then this is the page for you to read! In this tutorial we'll walk you through doing all of the tutorials you've been doing with Postman programmatically.

This tutorial requires technical knowledge to do! If you're not technically minded, you can still learn FHIR by doing other tutorials on this website.
Click the appropriate button below depending on which programming language you are interested in. This will help this web site display the examples most relevant to your choice.

Работа с API для FHIR

Если вы разработчик или просто хотите писать код для работы с FHIR, эта страница для вас! В этом уроке мы покажем, как программно выполнить всё то, что вы делали в предыдущих уроках с помощью Postman.

Для этого урока нужны технические знания! Если вы не программист, вы всё равно можете изучать FHIR с помощью других уроков на этом сайте.
Нажмите кнопку ниже, соответствующую интересующему вас языку программирования. Тогда сайт будет показывать примеры, наиболее подходящие для вашего выбора.
Step 1: Setup Шаг 1: Подготовка

FHIR provides some official API code libraries in Java and .NET to help you work with the standard.

They are:

Java

HAPI FHIR library: To get started with HAPI, add the dependency via Maven or Gradle - or download the library from the releases page. For R4, include all non-hapi jars in your classpath, and the following HAPI jars: hapi-fhir-base, hapi-fhir-structures-r4, hapi-fhir-validation-resources-r4.

To run the Java examples you need a Java Development Kit (JDK); current HAPI FHIR releases require JDK 17 or newer.

Microsoft .Net

FHIR .NET SDK: The simplest way to get started with the .NET SDK is to search for it in the NuGet package manager built into Visual Studio. Right click your Solution and select 'Manage NuGet Packages' and then search for and install 'Hl7.Fhir.R4'. You can find a C# project here on GitHub that contains C# examples.

Для FHIR существуют официальные библиотеки API на Java и .NET, которые помогают работать со стандартом.

Вот они:

Java

Библиотека HAPI FHIR: чтобы начать работу с HAPI, добавьте зависимость через Maven или Gradle — или скачайте библиотеку со страницы релизов. Для R4 добавьте в classpath все jar-файлы, не относящиеся к HAPI, а также следующие jar-файлы HAPI: hapi-fhir-base, hapi-fhir-structures-r4, hapi-fhir-validation-resources-r4.

Актуальные версии HAPI FHIR требуют Java 17 или новее.

Microsoft .NET

FHIR .NET SDK: проще всего начать работу с .NET SDK, найдя его в менеджере пакетов NuGet, встроенном в Visual Studio. Щёлкните правой кнопкой мыши по решению (Solution), выберите 'Manage NuGet Packages', затем найдите и установите пакет 'Hl7.Fhir.R4'. Проект с примерами на C# можно найти на GitHub здесь.

Step 2: Create a basic Patient Шаг 2: Создание простого ресурса Patient

Upon creating a new project, you'll see a new blank class not much different from this:

Создав новый проект, вы увидите пустой класс примерно такого вида:

Create a basic Patient resource and populate it with some information. Running this code will print the resource as JSON for you:

Создайте простой ресурс Patient и заполните его какими-нибудь данными. При запуске этот код выведет ресурс в формате JSON:

Once run, you should see something like this:

После запуска вы увидите примерно следующее:

If your IDE supports code completion, try using it to explore the Patient resource and populate it with some information such as the gender, birthday and phone number. Otherwise, consult the FHIR Patient page to see what you can populate your resource with (Javadoc is also available).

Если ваша IDE поддерживает автодополнение кода, попробуйте с его помощью изучить ресурс Patient и добавить в него другие данные, например пол, дату рождения и номер телефона. Если нет, загляните на страницу FHIR Patient, чтобы узнать, чем можно заполнить ресурс (также доступна документация Javadoc).

Step 3: Upload your basic Patient Шаг 3: Загрузка ресурса Patient на сервер

Now that we can create a simple resource, let's upload it to a FHIR server:

Теперь, когда мы умеем создавать простой ресурс, давайте загрузим его на FHIR-сервер:

Comparing the resource that we sent up to the resource we received back, you'll notice that the server generated a basic narrative for us from the data available and also added its logical ID

Сравнив отправленный ресурс с ресурсом, полученным в ответ, вы заметите, что сервер сгенерировал для нас простое текстовое представление (narrative) на основе имеющихся данных, а также присвоил ресурсу логический ID.

Now that you've uploaded a resource, try searching for it. Remember that you'll get a bundle back with many entries, one resource per entry.

Теперь, когда вы загрузили ресурс, попробуйте его найти. Помните, что в ответ вы получите Bundle с множеством записей (entry) — по одному ресурсу в каждой.

Step 5: Run an operation Шаг 5: Выполнение операции

Lastly, let's execute an operation on the server. A simple operation we can do is the Patient/$everything - this'll fetch us the Patient resource and all related resources to it.

Firstly, lets upload the sample Patient we've explored before in the Patient with References tutorial:

Напоследок выполним операцию на сервере. Простая операция, с которой можно начать, — Patient/$everything: она вернёт ресурс Patient и все связанные с ним ресурсы.

Сначала загрузим пример пациента, который мы уже рассматривали в уроке Пациент со ссылками:


Now we can run a query on the operation to get a Bundle with the Patient and associated resources. Here's how it looks in code. Make sure to update MY_PATIENT_ID with (press Upload first).

Теперь можно вызвать операцию и получить Bundle с ресурсом Patient и связанными с ним ресурсами. Вот как это выглядит в коде. Не забудьте заменить MY_PATIENT_ID на (сначала нажмите Загрузить).

Try running the code and you should see the same IDs for related resources as on this page:

Запустите код — вы должны увидеть те же ID связанных ресурсов, что и на этой странице:

Patient/(press Upload first)(сначала нажмите Загрузить)
Encounter/(press Upload first)(сначала нажмите Загрузить)
Observation/(press Upload first)(сначала нажмите Загрузить)
Observation/(press Upload first)(сначала нажмите Загрузить)
DiagnosticReport/(press Upload first)(сначала нажмите Загрузить)

That's about it for the basics! Happy coding. Check out the HAPI documentation if you're using Java for more as well.

Вот и всё, что касается основ! Удачи в программировании. Если вы пишете на Java, загляните также в документацию HAPI — там вы найдёте больше информации.