FHIR® tutorials FHIR® уроки

Operations

This tutorial will give you an overview of Operations in the FHIR specification.

Step 1: What are Operations

In the Simple Patient tutorial, we looked at interacting with the FHIR server using the CRUD actions (Create, Read, Update and Delete). Operations extend on these basic actions to provide unique functionality where required. For instance, the operation $validate can check that a provided resource is acceptable to the server before you attempt to upload it. $translate can map one code to another using a ConceptMap. You can find a full list of the operations defined by the FHIR specification here: FHIR defined Operations and for operations that are particular to a given FHIR resource, you will find an operation tab at the top of the given resource's page.

Operation tab as seen on the Patient resource page

Let's jump straight in and look at some operation syntax examples. The basic concept of operations is much like a function in programming. An operation has an 'Operation Name' (e.g. $meta, $everything) which are always prefixed with a dollar sign '$' and operations are run in one of three context, them being:

Against the entire FHIR server:
Give me the meta-data for the entire FHIR server
Syntax: [Service Root URL]/[$Operation Name]
Example: http://www.acmehealth/fhirapi/$meta

Against a type of resource:
Give me the meta-data for a given resource type (Patient)
Syntax: [Service Root URL]/[Resource Type]/[$Operation Name]
Example: http://www.acmehealth/fhirapi/Patient/$meta

Against a single resource instance:
Give me all resources (everything) for the Patient resource with the given resource id of (123456)
Syntax: [Service Root URL]/[Resource Type]/[Resource Id]/[$Operation Name]
Example: http://www.acmehealth/fhirapi/Patient/123456/$everything

Operations can also have any number of input and output parameters. We will look at input parameter next.

Step 2: Operations input parameters

There are two different ways to pass input parameters to an operation on a FHIR server. Generally, the POST action is used and the parameters are given in the HTTP body as a Parameters resource. Take a look at the Parameters resource in the FHIR specification now to get a feel for its contents. In essence, it is a resource containing value pairs (key, value) where value may be a FHIR data type or a whole resource. The point to take home here is that the Parameters resource allows you to pass in complex data types and whole resources as parameters.

The other way to pass input parameters into operations is by using an HTTP GET and putting the parameters in the GET URL string as seen in the following examples:

Syntax: [Service Root URL]/[Resource Name]/[$OperationName]?[OpParameterName1=value]&[OpParameterName2=value]..etc.

The $match operation can be given on a Patient resource type using a number of input parameters:
Give me all the Patient resources that match on the patient demographic parameters (family, given, birthdate)
Example: http://www.acmehealth/fhirapi/Patient/$match?family=chalmers&given=peter&birthdate=1974-12-25

Activity: Find in the FHIR specification documentation the $match operation and answer; what other input parameters can this operation take and what is its output?

So when do you use each - Parameters in the URL string or parameters in the body using the Parameters resource?

For some operations, you can use either option as long as the server supports both, for instance, the $lookup operation on a CodeSystem resource can be performed using both methods. Yet sometimes you must use the Parameters resource and HTTP POST rather than the parameters in the URL string and GET. One of the key reasons for this is due to the parameters you need to pass into the operation. If one of them is a whole Resource or a complex datatype then you must use the Parameters resource as you are unable to place a whole resource or complex data type in an URL string. The other reason is that an operation must be 'Idempotent' to use a GET action.

What the; Idempotent?
Idempotent: An Idempotent operation can be applied multiple times without changing the result beyond the initial application. For example, if I make a call to delete a resource the action is said to be 'Idempotent' because if I repeat the very same call many times, no further changes occur, the resource just remains deleted as it did on the first call.

Step 3: Operations output parameters

The output of an operation is somewhat the same as the input. If the operation was successful a HTTP status code of 200 OK will be returned along with either a Parameters resource or you may get a whole resource returned depending on the operation. If an error is encountered by the server you will receive an OperationOutcome resource and an HTTP status code of 4xx or 5xx. Not all operations are alike so browse the full list to get a feel for inputs and outputs of each.

Step 4: Custom Operations

While the FHIR specification outlines a set of operations, there is no requirement that any given server support these operations. In order to work out which operations a server supports you will need to inspect the servers' own CapabilityStatement which is a resource that all servers must provide given the following call: GET: [Service Root URL]/metadata. Check this resource to see which OperationDefinition resources it lists as supported. These will be listed at the following path in the CapabilityStatement resource: CapabilityStatement/rest/operation Here you should see a reference to another resource named OperationDefinition which is used to define the operation in its entirety; what the operation does and the inputs and outputs it uses.

Servers are also allowed to offer their own custom operations. Each of these should be defined in that servers CapabilityStatement resource by an OperationDefinition resource, as described above. A server can even extend onto an existing operation with new input and output parameters, once again all of these need to be stated in the appropriate OperationDefinition and referenced in the servers' own CapabilityStatement .

Activity: Using a post client GET your servers' CapabilityStatement resource and identify the operations it supports?
Tip GET: [Service Root URL]/metadata

All operations in FHIR are accessed using a dollar symbol e.g GET: [Service Root URL]/$MyOperationName. Yet, the metadata call to get the servers' CapabilityStatement does not use a dollar sign. This is a quirk of the early development of FHIR. The 'metadata' operation was the very first operation ever defined by FHIR and as it returns the information about what the server supports. It is a critical piece of infrastructure. The FHIR team thought changing this call to '$metadata' would be to much of a breaking change.

Операции

Этот урок даст вам обзор Операций в спецификации FHIR.

Шаг 1: Что такое операции

В уроке Пациент мы рассмотрели взаимодействие с FHIR-сервером с использованием CRUD-действий (Создание, Чтение, Обновление и Удаление). Операции расширяют эти базовые действия, предоставляя уникальную функциональность там, где это необходимо. Например, операция $validate может проверить, что предоставленный ресурс приемлем для сервера, прежде чем вы попытаетесь его загрузить. $translate может сопоставить один код с другим, используя ConceptMap. Полный список операций, определенных спецификацией FHIR, можно найти здесь: Операции, определенные FHIR, а для операций, специфичных для данного ресурса FHIR, вы найдете вкладку операций в верхней части страницы данного ресурса.

Вкладка Операции, как видно на странице ресурса Patient

Давайте сразу перейдем к рассмотрению примеров синтаксиса операций. Основная концепция операций очень похожа на функцию в программировании. Операция имеет 'имя операции' (например, $meta, $everything), которые всегда начинаются со знака доллара '$', и операции выполняются в одном из трех контекстов:

На весь FHIR-сервера:
Дайте мне метаданные для всего FHIR-сервера
Синтаксис: [URL корня службы]/[$имя операции]
Пример: http://www.acmehealth/fhirapi/$meta

На тип ресурса:
Дайте мне метаданные для данного типа ресурса (Patient)
Синтаксис: [URL корня службы]/[Тип ресурса]/[$имя операции]
Пример: http://www.acmehealth/fhirapi/Patient/$meta

На одного экземпляра ресурса:
Дайте мне все ресурсы (everything) для ресурса Patient с данным идентификатором ресурса (123456)
Синтаксис: [URL корня службы]/[Тип ресурса]/[ID ресурса]/[$имя операции]
Пример: http://www.acmehealth/fhirapi/Patient/123456/$everything

Операции также могут иметь любое количество входных и выходных параметров. Далее мы рассмотрим входные параметры.

Шаг 2: Входные параметры операций

Существует два различных способа передачи входных параметров операции на FHIR-сервер. Обычно используется действие POST, и параметры передаются в теле HTTP как ресурс Parameters. Взгляните на ресурс Parameters в спецификации FHIR сейчас, чтобы понять его содержимое. По сути, это ресурс, содержащий пары значений (ключ, значение), где значение может быть типом данных FHIR или целым ресурсом. Главное, что нужно понять здесь, это то, что ресурс Parameters позволяет передавать типы данных и целые ресурсы в качестве параметров.

Другой способ передачи входных параметров в операции - использование HTTP GET и размещение параметров в строке URL GET, как показано в следующих примерах:

Синтаксис: [URL корня службы]/[Имя ресурса]/[$имя операции]?[Имя параметра операции1=значение]&[Имя параметра операции2=значение]..и т.д.

Операция $match может быть выполнена для типа ресурса Patient с использованием ряда входных параметров:
Дайте мне все ресурсы Patient, которые соответствуют демографическим параметрам пациента (family, given, birthdate)
Пример: http://www.acmehealth/fhirapi/Patient/$match?family=chalmers&given=peter&birthdate=1974-12-25

Задание: Найдите в документации спецификации FHIR операцию $match и ответьте: какие еще входные параметры может принимать эта операция и каков ее выход?

Итак, когда использовать каждый из них - параметры в строке URL или параметры в теле с использованием ресурса Parameters?

Для некоторых операций вы можете использовать любой вариант, если сервер поддерживает оба, например, операция $lookup для ресурса CodeSystem может выполняться обоими методами. Однако иногда вы должны использовать ресурс Parameters и HTTP POST, а не параметры в строке URL и GET. Одна из ключевых причин этого связана с параметрами, которые вам нужно передать в операцию. Если один из них является целым ресурсом или сложным типом данных, то вы должны использовать ресурс Parameters, поскольку вы не можете поместить целый ресурс или сложный тип данных в строку URL. Другая причина заключается в том, что операция должна быть 'Идемпотентной' для использования действия GET.

Что такое идемпотентность?
Идемпотентность: Идемпотентная операция может применяться несколько раз без изменения результата после первоначального применения. Например, если я делаю вызов для удаления ресурса, действие называется 'Идемпотентным', потому что если я повторю тот же самый вызов много раз, никаких дальнейших изменений не произойдет, ресурс просто останется удаленным, как это было при первом вызове.

Шаг 3: Выходные параметры операций

Выход операции в некоторой степени такой же, как и вход. Если операция была успешной, будет возвращен HTTP-код состояния 200 OK вместе с ресурсом Parameters или вы можете получить целый ресурс в зависимости от операции. Если сервер столкнется с ошибкой, вы получите ресурс OperationOutcome и HTTP-код состояния 4xx или 5xx. Не все операции одинаковы, поэтому просмотрите полный список, чтобы понять входы и выходы каждой.

Шаг 4: Пользовательские операции

Хотя спецификация FHIR определяет набор операций, нет требования, чтобы какой-либо данный сервер поддерживал эти операции. Чтобы выяснить, какие операции поддерживает сервер, вам нужно будет проверить собственный CapabilityStatement сервера, который является ресурсом, который все серверы должны предоставлять при следующем вызове: GET: [URL корня службы]/metadata. Проверьте этот ресурс, чтобы увидеть, какие ресурсы OperationDefinition он перечисляет как поддерживаемые. Они должны быть перечислены по следующему пути в ресурсе CapabilityStatement: CapabilityStatement/rest/operation Здесь вы должны увидеть ссылку на другой ресурс с именем OperationDefinition, который используется для определения операции в ее полноте; что делает операция и какие входы и выходы она использует.

Серверам также разрешено предлагать свои собственные пользовательские операции. Каждая из них должна быть определена в ресурсе CapabilityStatement этого сервера ресурсом OperationDefinition, как описано выше. Сервер может даже расширить существующую операцию новыми входными и выходными параметрами, опять же все это должно быть указано в соответствующем OperationDefinition и ссылаться в собственном CapabilityStatement сервера.

Задание: Используя POST-клиент, получите ресурс CapabilityStatement вашего сервера и определите операции, которые он поддерживает?
Подсказка GET: [URL корня службы]/metadata

Все операции в FHIR доступны с использованием символа доллара, например GET: [URL корня службы]/$MyOperationName. Однако вызов metadata для получения CapabilityStatement сервера не использует знак доллара. Это особенность раннего развития FHIR. Операция 'metadata' была самой первой операцией, когда-либо определенной FHIR, и поскольку она возвращает информацию о том, что поддерживает сервер, это критически важная часть инфраструктуры. Команда FHIR посчитала, что изменение этого вызова на '$metadata' будет слишком кардинальным изменением.