Политика AssignMessage изменяет или создает новые сообщения запроса и ответа в процессе работы API-прокси. Политика позволяет выполнять следующие действия с этими сообщениями:
Добавьте новые параметры формы, заголовки или параметры запроса в сообщение.
Копирование существующих свойств из одного сообщения в другое.
Удаление заголовков, параметров запроса, параметров формы и/или содержимого сообщения из сообщения.
Установить значение существующих свойств в сообщении
С помощью политики AssignMessage вы обычно добавляете, изменяете или удаляете свойства запроса или ответа. Однако вы также можете использовать политику AssignMessage для создания пользовательского сообщения запроса или ответа и передачи его в альтернативный целевой объект, как описано в разделе «Создание пользовательских сообщений запроса» .
Варианты использования
Существует множество ситуаций, когда может потребоваться изменить сообщение запроса или ответа во время обработки Apigee Edge. Например:
Задайте значение по умолчанию для параметра строки запроса или другого типа входных данных.
Удалите HTTP-заголовки из сообщения запроса перед его пересылкой в бэкэнд-сервис.
Перед отправкой ответа в приложение-потребитель необходимо добавить HTTP-заголовки.
Вставьте содержимое сообщения в формате JSON или XML перед отправкой ответа.
Генерируйте полные сообщения запроса или ответа. Например, вы можете использовать политику ServiceCallout для вызова удаленного API из API-прокси. Вы можете использовать политику AssignMessage для создания пользовательского сообщения запроса и присвоения его переменной. Затем используйте Service Callout для отправки этого сообщения удаленному API.
Добавьте заголовки к запросам и ответам для отладки и устранения неполадок.
Политика AssignMessage позволяет создавать или изменять сообщения или переменные потока. Используйте эту политику для изменения сообщений запроса перед их отправкой через прокси в вышестоящие системы или для изменения сообщений ответа перед их передачей приложениям-потребителям API.
В следующем примере показаны настройки по умолчанию, которые применяются при добавлении политики AssignMessage в поток в пользовательском интерфейсе Edge:
При добавлении новой политики AssignMessage в пользовательский интерфейс Edge шаблон содержит заглушки для всех возможных операций. Как правило, вы выбираете, какие операции вы хотите выполнить с помощью этой политики, и удаляете остальные дочерние элементы. Например, если вы хотите выполнить операцию копирования, используйте элемент <Copy> и удалите элементы <Add> , <Remove> и другие дочерние элементы из политики, чтобы сделать ее более читабельной.
Этот элемент имеет следующие атрибуты, общие для всех политик:
Атрибут
По умолчанию
Необходимый?
Описание
name
Н/Д
Необходимый
Внутреннее имя политики. Значение атрибута name может содержать буквы, цифры, пробелы, дефисы, символы подчеркивания и точки. Это значение не может превышать 255 символов.
При необходимости используйте элемент <DisplayName> , чтобы пометить политику в редакторе прокси-сервера пользовательского интерфейса управления другим именем на естественном языке.
continueOnError
ЛОЖЬ
Необязательный
Установите значение «false», чтобы возвращать ошибку при сбое политики. Это ожидаемое поведение для большинства политик. Установите значение «true», чтобы выполнение потока продолжалось даже после сбоя политики.
enabled
истинный
Необязательный
Установите значение «true», чтобы применить политику. Установите значение «false», чтобы «отключить» политику. Политика не будет применяться, даже если она остается присоединенной к потоку.
asyncnot_interested
ЛОЖЬ
Устаревший
Этот атрибут устарел.
В следующей таблице приведено общее описание дочерних элементов элемента <AssignMessage> :
Добавляет информацию в объект сообщения, указанный элементом <AssignTo> .
Элемент <Add> добавляет к сообщению заголовки или параметры, которых нет в исходном сообщении. Чтобы перезаписать существующие заголовки или параметры, используйте элемент <Set> .
Заменяет значения существующих свойств в запросе или ответе, которые указываются элементом <AssignTo> .
<Set> перезаписывает заголовки или параметры, которые уже существуют в исходном сообщении. Для добавления новых заголовков или параметров используйте элемент <Add> .
В этом примере новое сообщение не создаётся. Вместо этого, оно изменяет существующее ответное сообщение, добавляя HTTP-заголовок.
Поскольку в этом примере в элементе <AssignTo> в качестве имени переменной указана response , данная политика изменяет объект response, который изначально был задан данными, возвращенными целевым сервером.
HTTP-заголовок, добавляемый в ответное сообщение этой политикой, определяется переменной, заполняемой политикой LookupCache . Таким образом, ответное сообщение, измененное этой политикой Assign Message, содержит HTTP-заголовок, указывающий, были ли результаты получены из кэша или нет. Установка заголовков в ответе может быть полезна для отладки и устранения неполадок.
4: Настройка динамического контента
С помощью функции Assign Message можно встраивать динамический контент в полезную нагрузку ответных и запрашивающих сообщений.
Чтобы встроить переменные потока Edge в XML-данные, заключите указанную переменную в фигурные скобки, например так: {prefix.name} .
В следующем примере значение переменной потока HTTP-заголовка user-agent встраивается в XML-элемент с именем User-agent :
Для JSON-данных можно вставлять переменные, используя атрибуты variablePrefix и variableSuffix с разделительными символами, как показано в следующем примере:
Рекомендуется удалять параметр запроса apikey из сообщения запроса при использовании политики VerifyAPIKey для аутентификации пользователей. Это делается для предотвращения передачи конфиденциальной информации о ключе на целевую серверную часть.
6: Установка/получение переменных
В следующем примере используются три политики назначения сообщений:
Создает в запросе три переменные потока со статическими значениями.
Получает переменные потока динамически во второй политике в потоке запроса.
Добавляет их в полезную нагрузку ответа.
<!--Policy#1: Set variables in the request -->
<AssignMessagename="AM-set-variables">
<!--CreateavariablenamedmyAppSecret-->
<AssignVariable>
<Name>myAppSecret</Name>
<Value>42</Value>
</AssignVariable>
<!--Createavariablenamedconfig.environment-->
<AssignVariable>
<Name>config.environment</Name>
<Value>test</Value>
</AssignVariable>
<!--Createavariablenamedconfig.protocol-->
<AssignVariable>
<Name>config.protocol</Name>
<Value>gopher</Value>
</AssignVariable>
</AssignMessage>
В первой политике элемент <AssignVariable> создает и устанавливает три переменные в запросе. Каждый элемент <Name> указывает имя переменной, а <Value> — ее значение.
Вторая политика использует элемент <AssignVariable> для считывания значений и создания трех новых переменных:
<!--Policy#2: Get variables from the request -->
<AssignMessagecontinueOnError="false"enabled="true"name="get-variables">
<AssignTocreateNew="false"transport="http"type="request"/>
<!--GetthevalueofmyAppSecretandcreateanewvariable,secret-->
<AssignVariable>
<Name>secret</Name>
<Ref>myAppSecret</Ref>
<Value>0</Value>
</AssignVariable>
<!--Getthevalueofconfig.environmentandcreateanewvariable,environment-->
<AssignVariable>
<Name>environment</Name>
<Ref>config.environment</Ref>
<Value>default</Value>
</AssignVariable>
<!--Getthevalueofconfig.protocolandcreateanewvariable,protocol-->
<AssignVariable>
<Name>protocol</Name>
<Ref>config.protocol</Ref>
<Value>default</Value>
</AssignVariable>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</AssignMessage>
Во второй политике элемент <Ref> ссылается на исходную переменную, а элементы <Name> указывают имена новых переменных. Если переменная, на которую ссылается элемент <Ref> недоступна, можно использовать значение, указанное элементом <Value> .
Чтобы опробовать этот набор правил:
Добавьте политики № 1 и № 2 в поток запросов. Убедитесь, что политика № 1 расположена перед политикой № 2.
Добавьте третью политику в поток ответа .
Третий вариант политики использует элемент <Set> для добавления переменных в ответ. В следующем примере формируется XML-данные в ответе, который Edge возвращает клиенту:
В следующем примере предположим, что политика ServiceCallout находится в запросе к API-прокси, и ответ вызова содержит несколько заголовков с одинаковым именем ( Set-Cookie ). Если предположить, что переменная ответа ServiceCallout имеет значение по умолчанию calloutResponse , то следующая политика получит значение второго заголовка Set-Cookie .
<AssignMessagename="AM-Payload-from-SC-header">
<Set>
<PayloadcontentType="application/json">
{"Cookies from Service Callout":" {calloutResponse.header.Set-Cookie.2}"}</Payload>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo>response</AssignTo>
</AssignMessage>
Чтобы вывести все значения заголовка, используйте следующую переменную:
{calloutResponse.header.Set-Cookie.values}
Для каждого дочернего элемента в этом справочнике приведены дополнительные примеры. Еще больше примеров можно найти в примере AssignMessage на GitHub.
ссылка на дочерний элемент
В этом разделе описываются дочерние элементы элемента <AssignMessage> .
<Add>
Добавляет информацию к запросу или ответу, которая указывается элементом <AssignTo> .
Элемент <Add> добавляет к сообщению новые свойства, которых нет в исходном сообщении. Чтобы изменить значения существующих свойств, используйте элемент <Set> .
В следующем примере используется элемент <FormParams> для получения значений трех параметров строки запроса из исходного запроса и установки их в качестве параметров формы в запросе к целевой конечной точке:
В этом примере в предварительном потоке запроса используется <Add> . Если вы посмотрите результаты в таком инструменте, как инструмент трассировки , запрос к https://example-target.com/get станет https://example-target.com/get?myParam=42 .
Дочерние элементы <Add> поддерживают динамическую подстановку строк, известную как шаблонизация сообщений .
В этом примере параметры строки запроса из исходного запроса добавляются в качестве параметров формы с другими именами. Затем исходные параметры запроса удаляются. Apigee отправит измененный запрос на целевую конечную точку.
Вы можете использовать инструмент трассировки , чтобы просмотреть ход выполнения запроса. Вы увидите, что тело запроса содержит закодированные в URL-формате данные формы, которые изначально были переданы в качестве параметров строки запроса:
username=nick&zip_code=90210&default_language=en
Использовать <FormParams> можно только при соблюдении следующих условий:
HTTP-метод: POST
Тип сообщения: Запрос
Один (или оба) из следующих вариантов:
Данные формы: задайте какое-либо значение или "" (пустую строку). Например, в curl добавьте -d "" к вашему запросу.
Заголовок Content-Length : Установите значение 0 (если в исходном запросе нет данных; в противном случае — текущая длина в байтах). Например, при использовании curl добавьте к запросу -H "Content-Length: 0" .
Например:
curl -vL -X POST -d "" -H "Content-Type: application/x-www-form-urlencoded"
https://ahamilton-eval-test.apigee.net/am-test
При добавлении <FormParams> Edge устанавливает заголовок Content-Type запроса в значение "application/x-www-form-urlencoded" перед отправкой сообщения в целевой сервис.
В следующем примере к сообщению запроса добавляется заголовок partner-id , и этому заголовку присваивается значение переменной потока verifyapikey.VAK-1.developer.app.partner-id .
Использовать <QueryParams> можно только при соблюдении следующих условий:
HTTP-метод: GET
Тип сообщения: Запрос
Кроме того, параметры запроса можно задавать только в том случае, если атрибут type элемента <AssignTo> содержит сообщение запроса. Задание параметров в ответе не имеет никакого эффекта.
Если вы зададите в своей политике пустой массив параметров запроса ( <Add><QueryParams/></Add> ), политика не добавит никаких параметров запроса. Это то же самое, что и пропуск <QueryParams> .
<AssignTo>
Определяет, с каким объектом работает политика AssignMessage. Доступные варианты:
Сообщение запроса:request , полученный API-прокси.
Ответное сообщение:response полученный от целевого сервера.
Пользовательское сообщение: пользовательский объект запроса или ответа.
Обратите внимание, что в некоторых случаях вы не можете изменить объект, на который воздействует политика AssignMessage. Например, вы не можете использовать <Add> или <Set> для добавления или изменения параметров запроса ( <QueryParams> ) или параметров формы ( <FormParams> ) в ответе. Вы можете изменять параметры запроса и параметры формы только в самом запросе.
Если вы не указываете <AssignTo> или если вы указываете элемент <AssignTo> , но не указываете текстовое значение для этого элемента, политика будет действовать в соответствии с запросом или ответом по умолчанию, в зависимости от того, где выполняется политика. Если политика выполняется в потоке запроса, она влияет на сообщение запроса. Если она выполняется в потоке ответа, политика по умолчанию влияет на ответ.
Элемент <AssignTo> использует следующий синтаксис:
При создании нового объекта запроса или ответа другие элементы политики AssignMessage (такие как <Add> , <Set> и <Copy> ) воздействуют на этот новый объект запроса.
Вы можете получить доступ к новому объекту запроса в других политиках позже в процессе выполнения, или отправить новый объект запроса во внешний сервис с помощью политики ServiceCallout .
Пример 3 s16
В следующем примере создается новый объект запроса с именем "MyRequestObject":
При создании нового объекта запроса или ответа другие элементы политики AssignMessage (такие как <Add> , <Set> и <Copy> ) воздействуют на этот новый объект запроса.
Вы можете получить доступ к новому объекту запроса в других политиках позже в процессе выполнения, или отправить новый объект запроса во внешний сервис с помощью политики ServiceCallout .
В следующей таблице описаны атрибуты объекта <AssignTo> :
Атрибут
Описание
Необходимый?
Тип
createNew
Определяет, будет ли данная политика создавать новое сообщение при присвоении значений.
Если значение равно "true", то политика создает новую переменную типа, указанного параметром type (либо "request", либо "response"). Если имя новой переменной не указано, то политика создает новый объект запроса или ответа на основе значения type .
Если ответ «ложный», то политика реагирует одним из двух способов:
Если переменная <AssignTo> может быть преобразована в объект запроса или ответа, обработка продолжается. Например, если политика находится в потоке запроса, переменной является объект запроса. Если политика находится в ответе, переменной является объект ответа.
Если <AssignTo> не может быть разрешено или разрешается в тип, отличный от сообщения, то политика выдает ошибку.
Если createNew не указан, политика реагирует одним из двух способов:
Если текстовое значение поля <AssignTo> соответствует сообщению, то обработка переходит к следующему шагу.
Если текстовое значение переменной <AssignTo> не может быть определено или определяется как тип, отличный от сообщения, создается новая переменная типа, указанного в type .
Необязательный
Логический
transport
Указывает тип транспорта для сообщения запроса или ответа.
Значение по умолчанию — "http" (единственное поддерживаемое значение).
Необязательный
Нить
type
Указывает тип нового сообщения, если createNew имеет значение "true". Допустимые значения: "request" или "response".
Если этот атрибут опустить, Edge создаст либо запрос, либо ответ, в зависимости от того, на каком этапе выполнения этой политики будет запущен процесс.
Необязательный
Нить
<AssignVariable>
Присваивает значение переменной потока. Если переменная потока не существует, то <AssignVariable> создает её.
Значение, которое вы присваиваете переменной потока, может быть одним из следующих:
Строковый литерал: Используйте дочерний элемент <Value> для указания строкового значения для переменной потока.
Переменная потока: Используйте дочерний элемент <Ref> , чтобы указать значение существующей переменной потока в качестве целевой переменной потока. Полный список переменных потока, которые можно использовать в качестве источника, см. в справочнике по переменным потока .
Шаблон сообщения: Используйте дочерний элемент <Template> , чтобы указать шаблон сообщения для интерполяции, чтобы получить значение, которое будет помещено в целевую переменную потока.
Элемент <AssignVariable> использует следующий синтаксис:
Используйте элемент <Ref> для указания исходной переменной. Если переменная, на которую ссылается <Ref> недоступна, Edge использует значение, указанное элементом <Value> . Если вы определяете <Template> , он имеет приоритет над другими дочерними элементами.
Пример 1 s18
В следующем примере новой переменной myvar присваивается буквальное значение "42":
В следующем примере значение переменной потока request.header.user-agent присваивается целевой переменной потока myvar , а значение параметра запроса country — целевой переменной потока Country :
Один из распространенных способов использования <AssignVariable> — это установка значения по умолчанию для параметра запроса, заголовка или другого значения, передаваемого вместе с запросом. Это делается с помощью комбинации дочерних элементов <Ref> и <Value> . Для получения дополнительной информации см. примеры использования <Ref> .
Указывает имя целевой переменной потока (например, переменной, значение которой устанавливается политикой AssignMessage). Если переменная с именем, указанным в <AssignVariable> не существует, политика создаст переменную с этим именем.
Указывает источник назначения в виде переменной потока. Переменная потока может быть одной из предопределенных переменных потока (перечисленных в справочнике по переменным потока ) или пользовательской переменной потока, созданной вами.
Значение элемента <Ref> всегда интерпретируется как переменная потока; в качестве значения нельзя указать строковый литерал. Для присвоения строкового значения используйте вместо этого элемент <Value> .
При указании переменной потока с помощью <Ref> опустите заключающие скобки "{}", которые обычно используются для ссылки на переменную потока. Например, чтобы присвоить значение вашей новой переменной значение переменной потока client.host :
Do this (no brackets):
<Ref>client.host</Ref>
Do NOT do this (brackets):
<Ref>{client.host}</Ref>
Чтобы задать значение по умолчанию для целевой переменной потока, используйте <Value> в сочетании с <Ref> . Если переменная потока, указанная в <Ref> , не существует, не может быть прочитана или имеет значение null, Edge присвоит целевой переменной потока значение из <Value> .
В следующем примере значение переменной потока request.header.user-agent присваивается целевой переменной потока myvar , а значение параметра запроса country — переменной Country :
В этом примере для Edge не указано значение по умолчанию (или резервное значение) ни для одного из назначений.
Пример 2 s23
В следующем примере значение переменной потока request.header.user-agent присваивается целевой переменной потока myvar , а значение параметра запроса country — переменной Country :
В этом примере, если значения переменной потока request.header.user-agent или параметра запроса Country равны null, нечитаемы или имеют некорректный формат, Edge присваивает новым переменным значение "ErrorOnCopy".
Пример 3 s24
Типичный пример использования ` <AssignVariable> ` — установка значения по умолчанию для параметра запроса, заголовка или другого параметра, передаваемого в запросе. Например, вы создаете прокси-сервер API погоды, в котором запрос принимает один параметр запроса с именем «w». Этот параметр содержит идентификатор города, для которого вы хотите получить информацию о погоде. URL-адрес запроса имеет следующий вид:
http://myCO.com/v1/weather/forecastrss?w=city_ID
Чтобы задать значение по умолчанию для параметра "w", создайте политику AssignMessage следующим образом:
В этом примере переменная ` <AssignVariable> получает значение request.queryparam.w и присваивает его себе. Если переменная потока равна `null`, то есть параметр запроса `w` был опущен в запросе, то в этом примере используется значение по умолчанию из элемента <Value> `. Таким образом, вы можете отправить запрос к этому API-прокси, в котором параметр запроса `w` будет опущен:
http://myCO.com/v1/weather/forecastrss
...и при этом API-прокси должен возвращать корректный результат.
В отличие от использования <Value> , значение <Ref> должно быть переменной потока, например, свойством объекта request , response или target объекта. Значение также может быть созданной вами пользовательской переменной потока.
Если вы укажете переменную потока, которая не существует, со значением <Ref> , и значение <IgnoreUnresolvedVariables> будет равно "true", Edge выдаст ошибку.
Задает шаблон сообщения . Шаблон сообщения позволяет выполнять подстановку строковых переменных при выполнении политики и может комбинировать строковые литералы с именами переменных, заключенными в фигурные скобки. Кроме того, шаблоны сообщений поддерживают такие функции , как экранирование и преобразование регистра.
Используйте атрибут ref для указания переменной потока, значением которой является шаблон сообщения. Например, вы можете сохранить шаблон сообщения в качестве пользовательского атрибута в приложении разработчика . Когда Edge идентифицирует приложение разработчика после проверки ключа API или токена безопасности (с помощью дополнительной политики), элемент ` <AssignVariable> может использовать шаблон сообщения из пользовательского атрибута приложения, который доступен в качестве переменной потока из политики безопасности.
В следующем примере используется синтаксис шаблонизации сообщений для объединения двух контекстных переменных, разделенных строковым литералом (дефисом):
В следующем примере задается переменная потока, значением которой является предопределенный шаблон сообщения. Используйте этот параметр, если хотите внедрить предопределенный шаблон во время выполнения без необходимости изменения политики:
В следующем примере задается переменная потока и текстовое значение. В этом случае, если ссылочная переменная не равна null, это значение используется в качестве шаблона. Если ссылочное значение равно null, то в качестве шаблона используется текстовое значение (в данном случае, {system.uuid}-{messageid} ). Этот шаблон полезен для предоставления значения «переопределения», когда в некоторых случаях необходимо переопределить шаблон по умолчанию (текстовую часть) значениями, которые устанавливаются динамически. Например, условное выражение может получить значение из карты ключ-значение и установить ссылочную переменную в это значение:
Определяет значение целевой переменной потока, заданной с помощью <AssignVariable> . Значение всегда интерпретируется как строковый литерал; вы не можете использовать переменную потока в качестве значения, даже если заключите значение в квадратные скобки ("{}"). Чтобы использовать переменную потока, используйте <Ref> вместо неё.
При использовании в сочетании с элементом <Ref> , <Value> выступает в качестве значения по умолчанию (или резервного значения). Если <Ref> не указан, не может быть разрешен или имеет значение null, используется значение <Value> .
В следующем примере значение переменной потока request.header.user-agent присваивается переменной потока myvar , а значение параметра запроса country — переменной Country :
Если какое-либо из присваиваний не удастся, переменная <AssignVariable> вместо этого присвоит переменной потока значение "ErrorOnCopy".
<Copy>
Копирует значения из сообщения, указанного в атрибуте source, в сообщение, указанное в элементе <AssignTo> . Если в элементе <AssignTo> не указан целевой объект, то данная политика копирует значения в запрос или ответ, в зависимости от того, на каком этапе выполнения процесса выполняется эта политика.
В следующем примере из сообщения request копируются заголовок, три параметра формы, путь и все параметры запроса в новый, пользовательский запрос с именем newRequest :
Поскольку такие элементы, как <Payload> и <Verb> отсутствуют, политика не копирует эти части сообщения.
Пример 2 s32
В следующем примере сначала удаляется все содержимое существующего response сообщения, а затем все значения из другого сообщения с именем secondResponse копируются в response сообщение:
Если source не указан, по умолчанию используется значение message , которое может отличаться в зависимости от потока выполнения политики. Если политика выполняется в потоке запроса, то переменная message ссылается на объект request . Если политика выполняется в потоке ответа, то переменная message ссылается на объект response .
Если исходная переменная не может быть разрешена или имеет тип, отличный от сообщения, <Copy> не отвечает.
Копирует параметры формы из запроса, указанного атрибутом source элемента <Copy>, в запрос, указанный элементом <AssignTo> . Этот элемент не влияет на ответ.
В этом примере копируются "f1", "f2" и второе значение "f3". Если "f3" имеет только одно значение, то оно не копируется.
Использовать <FormParams> можно только при соблюдении следующих условий:
HTTP-метод: POST
Тип сообщения: Ответ
Один (или оба) из следующих вариантов:
Данные формы: задайте какое-либо значение или "" (пустую строку). Например, в curl добавьте -d "" к вашему запросу.
Заголовок Content-Length : Установите значение 0 (если в исходном запросе нет данных; в противном случае — текущая длина). Например, при использовании curl добавьте к запросу -H "Content-Length: 0" .
При копировании <FormParams> , <Copy> устанавливает Content-Type сообщения в значение "application/x-www-form-urlencoded" перед отправкой сообщения в целевой сервис.
Копирует заголовки HTTP из сообщения запроса или ответа, указанного атрибутом source элемента <Copy>, в сообщение запроса или ответа, указанное элементом <AssignTo> .
Определяет, следует ли копировать путь из исходного запроса в целевой запрос. Этот элемент не влияет на ответ.
Если значение равно "true", эта политика копирует путь из сообщения запроса, указанного атрибутом source элемента <Copy>, в сообщение запроса, указанное элементом <AssignTo> .
Определяет, следует ли копировать полезную нагрузку из источника в пункт назначения. Источником и пунктом назначения могут быть запросы или ответы.
Если значение равно "true", эта политика копирует полезную нагрузку из сообщения, указанного атрибутом source элемента <Copy>, в сообщение, указанное элементом <AssignTo> .
Копирует параметры строки запроса из запроса, указанного атрибутом source элемента <Copy>, в запрос, указанный элементом <AssignTo> . Этот элемент не влияет на ответ.
Значение по умолчанию
н/д
Необходимый?
Необязательный
Тип
Массив элементов <QueryParam> или пустой массив
Родительский элемент
<QueryParam>
Дочерние элементы
Никто
Элемент <QueryParams> использует следующий синтаксис:
Определяет, следует ли копировать фразу-причину из исходного ответа в целевой ответ. Этот элемент не влияет на запрос.
Если значение равно "true", эта политика копирует ReasonPhraseиз ответа, указанного атрибутом source элемента <Copy>, в ответ, указанный элементом <AssignTo> .
В следующем примере параметру <ReasonPhrase> присваивается значение true . При указанных источнике и элементе <AssignTo> , параметр <Copy> копирует фразу причины из именованного ответного сообщения в объект response :
Определяет, копируется ли код состояния из ответа источника в ответ получателя. Этот элемент не влияет на запрос.
If "true", this policy copies the status code from the response message specified by the <Copy> element's source attribute to the response message specified by the <AssignTo> element.
The following example sets <Version> to "true" on the request, which copies the version from the default request object to a new, custom request object:
You can use <Version> only when the following criteria are met:
Message type: Request
<DisplayName>
Используйте в дополнение к атрибуту name , чтобы обозначить политику в редакторе прокси-сервера пользовательского интерфейса управления другим, более естественно звучащим именем.
Элемент <DisplayName> является общим для всех политик.
Значение по умолчанию
н/д
Необходимый?
Необязательно. Если <DisplayName> опущен, будет использоваться значение атрибута name политики.
Тип
Нить
Родительский элемент
< PolicyElement >
Дочерние элементы
Никто
Элемент <DisplayName> использует следующий синтаксис:
Set to true to ignore unresolved variables and continue processing; otherwise false . The default value is false .
Setting <IgnoreUnresolvedVariables> to true is different from setting the <AssignMessage> 's continueOnError to true in that it is specific to setting and getting values of variables. If you set continueOnError to true , then Edge ignores all errors, not just errors encountered when using variables.
Элемент <IgnoreUnresolvedVariables> использует следующий синтаксис:
Because <IgnoreUnresolvedVariables> is set to true , if the possibly-defined-variable variable is not defined, this policy will not throw a fault.
<Remove>
Removes headers, query parameters, form parameters, and/or the message payload from a message. The message can be a request or a response. You specify which message <Remove> acts on by using the <AssignTo> element.
A common use case for <Remove> is to delete a query parameter or header that contains sensitive information from the incoming request object, to avoid passing it to the backend server.
Determines whether <Remove> deletes the payload in the request or response, which is specified by the <AssignTo> element. Set to "true" to clear the payload; otherwise "false". The default value is "false".
You can use <QueryParams> only when the following criteria are met:
HTTP verb: GET
Message type: Request
<Set>
Sets information in the request or response message, which is specified by the <AssignTo> element. <Set> overwrites headers or query or form parameters that already exist in the original message. Headers and query and form parameters in an HTTP message may hold multiple values. To add additional values for a header or parameter, use the <Add> element instead.
The following example sets a specific header. When this policy is attached in the Request flow, it will allow the upstream system to receive an additional header that was not included in the original inbound request.
Overwrites existing form parameters on a request and replaces them with the new values that you specify with this element. This element has no effect on a response.
You can use <FormParams> only when the following criteria are met:
HTTP verb: POST
Message type: Request
If you define empty form parameters in your policy ( <Add><FormParams/></Add> ), the policy does not add any form parameters. This is the same as omitting the <FormParams> .
<Set> changes the Content-Type of the message to "application/x-www-form-urlencoded" before sending it to the target endpoint.
If you define empty headers in your policy ( <Set><Headers/></Set> ), the policy does not set any headers. This will have the same effect as omitting <Headers> .
Defines the message body for a request or response, which is specified by the <AssignTo> element. The payload can be any valid content type, such as plain text, JSON, or XML.
In previous versions of Apigee, you could not use curly braces to denote variable references within JSON payloads. In those releases, you needed to use the variablePrefix and variableSuffix attributes to specify delimiter characters, and use those to wrap variable names, like so:
The content of <Payload> is treated as a message template. This means that the AssignMessage policy replaces variables wrapped in curly braces with the value of the referenced variables at runtime.
The following example uses the curly braces syntax to set part of the payload to a variable value:
You can use <QueryParams> only when the following criteria are met:
HTTP verb: GET
Message type: Request
If you define empty query parameters in your policy ( <Set><QueryParams/></Set> ), the policy does not set any query parameters. This is the same as omitting <QueryParams> .
Sets the reason phrase on the response. This is normally done for debugging in combination with <StatusCode> . This element has no effect on a request.
The content of <ReasonPhrase> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable, as the following example shows:
The content of <StatusCode> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable, as the following example shows:
The content of <Verb> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable.
The following example uses a variable to populate a verb:
The content of <Version> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable.
You can use <Version> only when the following criteria are met:
Message type: Request
The following example creates a custom request object with Assign Message:
Creates a new request message object called "MyCustomRequest".
On MyCustomRequest, this policy:
Copies the value of the user-agent HTTP header from the incoming request to the new message. Because <Copy> uses an absolute reference to the user-agent flow variable, there is no need to specify the source attribute to <Copy> .
Sets the address query parameter on the custom message to the value of the incoming request's addy query parameter.
Sets the HTTP verb to GET .
Sets <IgnoreUnresolvedVariables> to "false". When <IgnoreUnresolvedVariables> is "false", if one of the variables the policy tries to add does not exist, Edge will stop processing in the API flow.
Example 2 s98
Here's another example demonstrating how to create a custom request object with Assign Message:
This example creates a new custom request called "partner.request". It then sets the <Verb> and <Payload> on the new request.
You can access a custom request message in another AssignMessage policy that occurs later in the flow. The following example gets the value of the custom request message's user-agent header:
Convert REST request to SOAP request by setting SOAP Payload using the AssignMessage policy policy at API runtime.
Error codes
В этом разделе описаны коды ошибок и сообщения об ошибках, которые возвращаются, а также переменные ошибок, которые устанавливаются Edge, когда эта политика вызывает ошибку. Эту информацию важно знать, если вы разрабатываете правила обработки ошибок. Дополнительные сведения см. в разделах Что нужно знать об ошибках политики и Обработка ошибок .
Ошибки выполнения
Эти ошибки могут возникнуть при выполнении политики.
Код неисправности
Статус HTTP
Причина
Исправить
steps.assignmessage.SetVariableFailed
500
Политике не удалось установить переменную. См. строку ошибки, чтобы узнать имя неразрешенной переменной.
steps.assignmessage.VariableOfNonMsgType
500
Эта ошибка возникает, если атрибуту source в элементе <Copy> присвоена переменная, которая не имеет типа message .
Переменные типа сообщения представляют собой все HTTP-запросы и ответы. Встроенные переменные потока Edge request , response и message имеют тип message. Дополнительные сведения о переменных сообщения см. в справочнике по переменным .
Эти ошибки могут возникнуть при развертывании прокси-сервера, содержащего эту политику.
Название ошибки
Причина
Исправить
InvalidIndex
Если индекс, указанный в элементах <Copy> и/или <Remove> политики назначения сообщений, равен 0 или отрицательному числу, развертывание прокси-сервера API завершается неудачно.
Если дочерний элемент <Name> пуст или не указан в элементе <AssignVariable> , развертывание прокси-сервера API завершается неудачей, поскольку отсутствует допустимое имя переменной, которой можно присвоить значение. Требуется допустимое имя переменной.
Полезная нагрузка, указанная в политике, недействительна.
Переменные неисправности
Эти переменные устанавливаются, когда эта политика вызывает ошибку во время выполнения. Дополнительные сведения см. в разделе Что нужно знать об ошибках политики .
Переменные
Где
Пример
fault.name=" fault_name "
fault_name — это имя ошибки, как указано в таблице ошибок времени выполнения выше. Имя неисправности — это последняя часть кода неисправности.
fault.name Matches "UnresolvedVariable"
assignmessage. policy_name .failed
policy_name — указанное пользователем имя политики, вызвавшей ошибку.
assignmessage.AM-SetResponse.failed = true
Пример ответа об ошибке
{"fault":{"detail":{"errorcode":"steps.assignmessage.VariableOfNonMsgType"},"faultstring":"AssignMessage[AM-SetResponse]: value of variable is not of type Message"}}
For a more advanced example of how to override the target.url from the ProxyEndpoint, see this Apigee Community article .
To see a "set path" in action in a ServiceCallout policy , check out this Learn by doing example in the Apigee GitHub samples. Just clone the repository and follow the instructions in that topic. The example uses AssignMessage policy to set a request path, then uses a Service Callout policy to make the request to an external service.
The AssignMessage policy changes or creates new request and response messages during the API proxy Flow. The policy lets you perform the following actions on those messages:
Add new form parameters, headers, or query parameters to a message
Copy existing properties from one message to another
Remove headers, query parameters, form parameters, and/or message payloads from a message
With AssignMessage policy, you typically add, change, or remove properties of either the request or response. However, you can also use AssignMessage policy to create a custom request or response message and pass it to an alternative target, as described in Create custom request messages .
Варианты использования
There are many situations in which you might want to modify a request or a response message during processing by Apigee Edge. For example:
Define a default value for a query string parameter or other type of input.
Strip HTTP headers from a request message before the message is forwarded to the backend service.
Add HTTP headers before a response is sent to the consumer app.
Insert JSON or XML message content before a response is sent.
Generate complete request or response messages. For example, you might use a ServiceCallout policy to invoke a remote API from an API proxy. You can use the AssignMessage policy to create a custom request message and assign it to a variable. Then, use Service Callout to send that message to the remote API.
Add headers to requests and responses for debugging and troubleshooting.
The AssignMessage policy can create or change messages or flow variables. Use this policy to modify request messages before sending them via a proxy to upstream systems, or to modify response messages before relaying them to API consumer applications.
When you insert a new AssignMessage policy in the Edge UI, the template contains stubs for all possible operations. Typically, you select which operation(s) you want to perform with this policy and remove the rest of the child elements. For example, if you want to perform a copy operation, use the <Copy> element and remove <Add> , <Remove> , and other child elements from the policy to make it more readable.
Этот элемент имеет следующие атрибуты, общие для всех политик:
Атрибут
По умолчанию
Необходимый?
Описание
name
Н/Д
Необходимый
Внутреннее имя политики. Значение атрибута name может содержать буквы, цифры, пробелы, дефисы, символы подчеркивания и точки. Это значение не может превышать 255 символов.
При необходимости используйте элемент <DisplayName> , чтобы пометить политику в редакторе прокси-сервера пользовательского интерфейса управления другим именем на естественном языке.
continueOnError
ЛОЖЬ
Необязательный
Установите значение «false», чтобы возвращать ошибку при сбое политики. Это ожидаемое поведение для большинства политик. Установите значение «true», чтобы выполнение потока продолжалось даже после сбоя политики.
enabled
истинный
Необязательный
Установите значение «true», чтобы применить политику. Установите значение «false», чтобы «отключить» политику. Политика не будет применяться, даже если она остается присоединенной к потоку.
asyncnot_interested
ЛОЖЬ
Устаревший
Этот атрибут устарел.
The following table provides a high-level description of the child elements of <AssignMessage> :
Adds information to the message object that is specified by the <AssignTo> element.
<Add> adds headers or parameters to the message that don't exist in the original message. To overwrite existing headers or parameters, use the <Set> element.
This example does not create a new message. Instead, it modifies an existing response message by adding an HTTP header.
Because this example specifies response as the variable name in the <AssignTo> element, this policy modifies the response object that was originally set with data returned by the target server.
The HTTP header added to the response message by this policy is derived from a variable populated by the LookupCache policy . Therefore the response message modified by this Assign Message policy contains an HTTP header that indicates whether the results have been pulled from the cache or not. Setting headers in the response can be handy for debugging and troubleshooting.
4: Set dynamic content
You can use Assign Message to embed dynamic content in the payload of response and request messages.
To embed Edge flow variables in an XML payload, wrap the designated variable in curly braces, like this: {prefix.name} .
The following example embeds the value of the user-agent HTTP header flow variable in an XML element called User-agent :
For JSON payloads, you can insert variables using the variablePrefix and variableSuffix attributes with delimiter characters as shown in the following example:
It's a best practice to strip the apikey query parameter from the request message when you use the VerifyAPIKey policy for user authentication. You do this to prevent sensitive key information from being passed to the backend target.
6: Set/get variables
The following example uses three Assign Message policies:
Creates three flow variables in the request, with static values
Gets the flow variables dynamically in a second policy in the request flow
Sets them in the payload of the response
<!--Policy#1: Set variables in the request -->
<AssignMessagename="AM-set-variables">
<!--CreateavariablenamedmyAppSecret-->
<AssignVariable>
<Name>myAppSecret</Name>
<Value>42</Value>
</AssignVariable>
<!--Createavariablenamedconfig.environment-->
<AssignVariable>
<Name>config.environment</Name>
<Value>test</Value>
</AssignVariable>
<!--Createavariablenamedconfig.protocol-->
<AssignVariable>
<Name>config.protocol</Name>
<Value>gopher</Value>
</AssignVariable>
</AssignMessage>
In the first policy, the <AssignVariable> element creates and sets three variables in the request. Each <Name> element specifies a variable name, and <Value> specifies the value.
The second policy uses the <AssignVariable> element to read in the values and creates three new variables:
<!--Policy#2: Get variables from the request -->
<AssignMessagecontinueOnError="false"enabled="true"name="get-variables">
<AssignTocreateNew="false"transport="http"type="request"/>
<!--GetthevalueofmyAppSecretandcreateanewvariable,secret-->
<AssignVariable>
<Name>secret</Name>
<Ref>myAppSecret</Ref>
<Value>0</Value>
</AssignVariable>
<!--Getthevalueofconfig.environmentandcreateanewvariable,environment-->
<AssignVariable>
<Name>environment</Name>
<Ref>config.environment</Ref>
<Value>default</Value>
</AssignVariable>
<!--Getthevalueofconfig.protocolandcreateanewvariable,protocol-->
<AssignVariable>
<Name>protocol</Name>
<Ref>config.protocol</Ref>
<Value>default</Value>
</AssignVariable>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</AssignMessage>
In the second policy, the <Ref> element references the source variable, and <Name> elements specify the names of the new variables. If the variable referenced by the <Ref> element is not accessible, you can use the value specified by the <Value> element.
To try out this set of policies:
Add policies #1 and #2 to the request flow. Be sure to put policy #1 before policy #2.
Add the third policy in the response flow.
The third policy uses the <Set> element to add the variables to the response. The following example constructs an XML payload in the response that Edge returns to the client:
In the following example, let's say that a ServiceCallout policy is in the API proxy request, and the callout response contains multiple headers of the same name ( Set-Cookie ). Assuming the Service Callout's response variable is the default calloutResponse , the following policy gets the second Set-Cookie header value.
<AssignMessagename="AM-Payload-from-SC-header">
<Set>
<PayloadcontentType="application/json">
{"Cookies from Service Callout":" {calloutResponse.header.Set-Cookie.2}"}</Payload>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo>response</AssignTo>
</AssignMessage>
To list all header values, use the following variable instead:
{calloutResponse.header.Set-Cookie.values}
Each child element in this reference has additional examples. For even more examples, see AssignMessage example on GitHub.
ссылка на дочерний элемент
This section describes the child elements of <AssignMessage> .
<Add>
Adds information to the request or response, which is specified by the <AssignTo> element.
The <Add> element adds new properties on the message that don't exist in the original message. To change the values of existing properties, use the <Set> element.
The following example uses the <FormParams> element to get the values of three query string parameters from the initial request and set them as form parameters on the target endpoint request:
This example uses <Add> in the request preflow. If you look at the results in a tool such as the Trace tool , the request to https://example-target.com/get becomes https://example-target.com/get?myParam=42 .
The child elements of <Add> support dynamic string substitution, known as message templating .
This example gets the query string parameters from the originating request and adds them as form parameters with different names. Then it removes the original query parameters. Apigee will send the modified request to the target endpoint.
You can use the Trace tool to look at the flow. You'll see that the body of the request contains the URL-encoded form data, which was originally passed in as query string parameters:
username=nick&zip_code=90210&default_language=en
You can use <FormParams> only when the following criteria are met:
HTTP verb: POST
Message type: Request
One (or both) of the following:
Form data: Set to some value, or "" (the empty string). For example, with curl , add -d "" to your request.
Content-Length header: Set to 0 (if no data is in the original request; otherwise, the current length, in bytes). For example, with curl add -H "Content-Length: 0" to your request.
Например:
curl -vL -X POST -d "" -H "Content-Type: application/x-www-form-urlencoded"
https://ahamilton-eval-test.apigee.net/am-test
When you add <FormParams> , Edge sets the request's Content-Type header to "application/x-www-form-urlencoded" before sending the message to the target service.
The following example adds a partner-id header to the request message, and assigns the value of the verifyapikey.VAK-1.developer.app.partner-id flow variable to that header.
You can use <QueryParams> only when the following criteria are met:
HTTP verb: GET
Message type: Request
In addition, you can only set query parameters when the <AssignTo> element's type attribute is a request message. Setting them on the response has no effect.
If you define an empty array of query parameters in your policy ( <Add><QueryParams/></Add> ), the policy does not add any query parameters. This is the same as omitting <QueryParams> .
<AssignTo>
Determines which object the AssignMessage policy operates on. The options are:
Request message: The request received by the API proxy
Response message: The response returned from the target server
Custom message: A custom request or response object
Note that in some cases, you cannot change the object on which the AssignMessage policy acts. For example, you cannot use <Add> or <Set> to add or change query parameters ( <QueryParams> ) or form parameters ( <FormParams> ) on the response. You can only manipulate query parameters and form parameters on the request.
If you do not specify <AssignTo> , or if you specify the <AssignTo> element, but do not specify a text value for the element, the policy acts on the default request or response, which is based on where the policy executes. If the policy executes in the request flow, it affects the request message. If it executes in the response flow, the policy affects the response by default.
When you create a new request or response object, the other elements of the AssignMessage policy policy (such as <Add> , <Set> , and <Copy> ) act on that new request object.
You can access the new request object in other policies later in the flow, or send the new request object to an external service with a ServiceCallout policy .
Example 3 s16
The following example creates a new request object named "MyRequestObject":
When you create a new request or response object, the other elements of the AssignMessage policy policy (such as <Add> , <Set> , and <Copy> ) act on that new request object.
You can access the new request object in other policies later in the flow, or send the new request object to an external service with a ServiceCallout policy .
The following table describes the attributes of <AssignTo> :
Атрибут
Описание
Необходимый?
Тип
createNew
Determines whether this policy creates a new message when assigning values.
If "true", then the policy creates a new variable of the type specified by type (either "request" or "response"). If you do not specify the name of the new variable, then the policy creates a new request or response object, based on the value of type .
If "false", then the policy responds in one of two ways:
If <AssignTo> can resolve the variable name to a request or response, then it continues processing. For example, if the policy is in a request flow, the variable is the request object. If the policy is in a response, the variable is the response object.
If <AssignTo> cannot be resolved, or resolves to a non-message type, then the policy throws an error.
If createNew is not specified, the policy responds in one of two ways:
If the text value of <AssignTo> resolves to a message, then processing advances to the next step.
If the text value of <AssignTo> cannot be resolved, or resolves to a non-message type, a new variable of type specified in type is created.
Необязательный
Логический
transport
Specifies the transport type for the request or response message type.
The default value is "http" (the only supported value).
Необязательный
Нить
type
Specifies the type of the new message, when createNew is "true". Valid values are "request" or "response".
If you omit this attribute, then Edge creates either a request or a response, depending on where in the flow this policy executes.
Необязательный
Нить
<AssignVariable>
Assigns a value to a flow variable. If the flow variable does not exist, then <AssignVariable> creates it.
The value that you assign to the flow variable can be one of the following:
Literal string: Use the <Value> child element to specify a literal string value for the flow variable.
Flow variable: Use the <Ref> child element to specify the value of an existing flow variable for the destination flow variable. For a complete list of flow variables that can be used as a source, see Flow variables reference .
Message template: Use the <Template> child element to specify a message template to interpolate, to get the value to place into the destination flow variable.
The <AssignVariable> element uses the following syntax:
Use the <Ref> element to specify the source variable. If the variable referenced by <Ref> is not accessible, Edge uses the value specified by the <Value> element. If you define <Template> , it takes precedence over the other child elements.
Example 1 s18
The following example sets the value of a new variable, myvar , to the literal value "42":
The following example assigns the value of the flow variable request.header.user-agent to the destination flow variable myvar and the value of the query parameter country to the destination flow variable Country :
A common use for <AssignVariable> is to set a default value for a query parameter, header, or other value that can be passed in with the request. You do this with a combination of both the <Ref> and <Value> child elements. For more information, see the examples for <Ref> .
Specifies the name of the destination flow variable (eg, the variable whose value is set by the AssignMessage policy). If the variable named in <AssignVariable> does not exist, the policy creates one with that name.
Specifies the source of the assignment as a flow variable. The flow variable can be one of the pre-defined flow variables (as listed in the Flow variables reference ), or a custom flow variable that you created.
The value of <Ref> is always interpreted as a flow variable; you cannot specify a literal string as the value. To assign a literal string value, use the <Value> element instead.
When you specify a flow variable with <Ref> , omit the enclosing brackets "{}" that you would normally use to reference a flow variable. For example, to set the value of your new variable to the value of the client.host flow variable:
Do this (no brackets):
<Ref>client.host</Ref>
Do NOT do this (brackets):
<Ref>{client.host}</Ref>
To define a default value for the destination flow variable, use <Value> in combination with <Ref> . If the flow variable specified by <Ref> does not exist, cannot be read, or is null, then Edge assigns the value of <Value> to the destination flow variable instead.
The following example assigns the value of the flow variable request.header.user-agent to the destination flow variable myvar and the value of the query parameter country to the Country variable:
In this example, Edge does not have a default (or fallback value) specified for either assignment.
Example 2 s23
The following example assigns the value of the flow variable request.header.user-agent to the destination flow variable myvar and the value of the query parameter country to the Country variable:
In this example, if the values of the request.header.user-agent flow variable or the Country query parameter are null, unreadable, or malformed, Edge assigns the value "ErrorOnCopy" to the new variables.
Example 3 s24
A common use case for <AssignVariable> is to set the default value of a query parameter, header, or other value that can be passed in with the request. For example, you create a weather API proxy where the request takes a single query parameter named "w". This parameter contains the ID of the city for which you want the weather. The request URL has the form:
http://myCO.com/v1/weather/forecastrss?w=city_ID
To define a default value for "w", create an AssignMessage policy like the following:
In this example, <AssignVariable> gets the value of request.queryparam.w and assigns it to itself. If the flow variable is null, meaning the "w" query parameter was omitted from the request, then this example uses the default value from the <Value> element. Therefore, you can make a request to this API proxy that omits the "w" query parameter:
http://myCO.com/v1/weather/forecastrss
...and still have the API proxy return a valid result.
Unlike when using <Value> , the value of <Ref> must be a flow variable, such as a property of a request , response , or target object. The value can also be a custom flow variable that you created.
If you specify a flow variable that does not exist for the value of <Ref> , and the value of <IgnoreUnresolvedVariables> is "true", Edge throws an error.
Specifies a message template . A message template allows you to perform variable string substitution when the policy executes, and can combine literal strings with variable names wrapped in curly braces. In addition, message templates support functions such as escaping and case conversion.
Use the ref attribute to specify a flow variable where the value of the variable is a message template. For example, you could store a message template as a custom attribute on a developer app . When Edge identifies the developer app after it verifies the API key or security token (through an additional policy), the <AssignVariable> element could use the message template from the app's custom attribute, which is available as a flow variable from the security policy.
The following example specifies a flow variable, where the value of the variable is a pre-defined message template. Use this option if you want to inject a pre-defined template at runtime without having to modify the policy:
The following example specifies a flow variable and a text value. In this case, if the referenced variable is non-null, that value is used as the template. If the referenced value is null, then the text value (in this case, {system.uuid}-{messageid} ) is used as the template. This pattern is useful to provide an "override" value, where in some cases you want to override the default template (the text part) with values that are set dynamically. For example, a conditional statement might grab a value from a key-value map and set the referenced variable to that value:
Defines the value of the destination flow variable set with <AssignVariable> . The value is always interpreted as a literal string; you cannot use a flow variable as the value, even if you wrap the value in brackets ("{}"). To use a flow variable, use <Ref> instead.
When used in combination with the <Ref> element, <Value> acts as the default (or fallback) value. If <Ref> is not specified, is unresolvable, or is null, the value of <Value> is used.
The following example assigns the value of the flow variable request.header.user-agent to the flow variable myvar and the value of the query parameter country to the Country variable:
If either assignment fails, <AssignVariable> instead assigns the value "ErrorOnCopy" to the destination flow variable.
<Copy>
Copies values from the message specified by the source attribute to the message specified by the <AssignTo> element. If you do not specify a target with <AssignTo> , then this policy copies the values to the request or the response, depending on where in the flow this policy executes.
The following example copies a header, three form parameters, the path, and all query parameters from the request message to a new, custom request named newRequest :
Because elements like <Payload> and <Verb> are not present, the policy does not copy those parts of the message.
Example 2 s32
The following example first removes everything in the existing response message, then copies all the values from a different message called secondResponse into the response message:
If source is not specified, it defaults to message , which takes a different value depending on the flow in which the policy executes. If the policy executes within the request flow, then the message variable refers to the request object. If the policy executes within the response flow, then the message variable refers to the response object.
If the source variable cannot be resolved, or resolves to a non-message type, <Copy> fails to respond.
Copies form parameters from the request specified by the <Copy> element's source attribute to the request specified by the <AssignTo> element. This element has no effect on a response.
This example copies "f1", "f2", and the second value of "f3". If "f3" has only one value, then it is not copied.
You can use <FormParams> only when the following criteria are met:
HTTP verb: POST
Message type: Response
One (or both) of the following:
Form data: Set to some value, or "" (the empty string). For example, with curl , add -d "" to your request.
Content-Length header: Set to 0 (if no data is in the original request; otherwise, the current length. For example, with curl add -H "Content-Length: 0" to your request.
When you copy <FormParams> , <Copy> sets the message's Content-Type to "application/x-www-form-urlencoded" before sending the message to the target service.
Copies HTTP headers from the request or response message specified by the <Copy> element's source attribute to the request or response message specified by the <AssignTo> element.
Determines whether the path should be copied from the source request to the destination request. This element has no effect on a response.
If "true", this policy copies the path from the request message specified by the <Copy> element's source attribute to the request message specified by the <AssignTo> element.
Determines whether the payload should be copied from the source to the destination. The source and destination can be requests or responses.
If "true", this policy copies the payload from the message specified by the <Copy> element's source attribute to the message specified by the <AssignTo> element.
Copies query string parameters from the request specified by the <Copy> element's source attribute to the request specified by the <AssignTo> element. This element has no effect on a response.
Значение по умолчанию
н/д
Необходимый?
Необязательный
Тип
An array of <QueryParam> elements or an empty array
Родительский элемент
<QueryParam>
Дочерние элементы
Никто
The <QueryParams> element uses the following syntax:
Determines whether the reason phrase should be copied from the source response to the destination response. This element has no effect on a request.
If "true", this policy copies the ReasonPhrasefrom the response specified by the <Copy> element's source attribute to the response specified by the <AssignTo> element.
The following example sets <ReasonPhrase> to true . With the source and <AssignTo> element as specified, this causes <Copy> to copy the reason phrase from the named response message to the response object:
Determines whether the status code is copied from the source response to the destination response. This element has no effect on a request.
If "true", this policy copies the status code from the response message specified by the <Copy> element's source attribute to the response message specified by the <AssignTo> element.
The following example sets <Version> to "true" on the request, which copies the version from the default request object to a new, custom request object:
You can use <Version> only when the following criteria are met:
Message type: Request
<DisplayName>
Используйте в дополнение к атрибуту name , чтобы обозначить политику в редакторе прокси-сервера пользовательского интерфейса управления другим, более естественно звучащим именем.
Элемент <DisplayName> является общим для всех политик.
Значение по умолчанию
н/д
Необходимый?
Необязательно. Если <DisplayName> опущен, будет использоваться значение атрибута name политики.
Тип
Нить
Родительский элемент
< PolicyElement >
Дочерние элементы
Никто
Элемент <DisplayName> использует следующий синтаксис:
Set to true to ignore unresolved variables and continue processing; otherwise false . The default value is false .
Setting <IgnoreUnresolvedVariables> to true is different from setting the <AssignMessage> 's continueOnError to true in that it is specific to setting and getting values of variables. If you set continueOnError to true , then Edge ignores all errors, not just errors encountered when using variables.
Элемент <IgnoreUnresolvedVariables> использует следующий синтаксис:
Because <IgnoreUnresolvedVariables> is set to true , if the possibly-defined-variable variable is not defined, this policy will not throw a fault.
<Remove>
Removes headers, query parameters, form parameters, and/or the message payload from a message. The message can be a request or a response. You specify which message <Remove> acts on by using the <AssignTo> element.
A common use case for <Remove> is to delete a query parameter or header that contains sensitive information from the incoming request object, to avoid passing it to the backend server.
Determines whether <Remove> deletes the payload in the request or response, which is specified by the <AssignTo> element. Set to "true" to clear the payload; otherwise "false". The default value is "false".
You can use <QueryParams> only when the following criteria are met:
HTTP verb: GET
Message type: Request
<Set>
Sets information in the request or response message, which is specified by the <AssignTo> element. <Set> overwrites headers or query or form parameters that already exist in the original message. Headers and query and form parameters in an HTTP message may hold multiple values. To add additional values for a header or parameter, use the <Add> element instead.
The following example sets a specific header. When this policy is attached in the Request flow, it will allow the upstream system to receive an additional header that was not included in the original inbound request.
Overwrites existing form parameters on a request and replaces them with the new values that you specify with this element. This element has no effect on a response.
You can use <FormParams> only when the following criteria are met:
HTTP verb: POST
Message type: Request
If you define empty form parameters in your policy ( <Add><FormParams/></Add> ), the policy does not add any form parameters. This is the same as omitting the <FormParams> .
<Set> changes the Content-Type of the message to "application/x-www-form-urlencoded" before sending it to the target endpoint.
If you define empty headers in your policy ( <Set><Headers/></Set> ), the policy does not set any headers. This will have the same effect as omitting <Headers> .
Defines the message body for a request or response, which is specified by the <AssignTo> element. The payload can be any valid content type, such as plain text, JSON, or XML.
In previous versions of Apigee, you could not use curly braces to denote variable references within JSON payloads. In those releases, you needed to use the variablePrefix and variableSuffix attributes to specify delimiter characters, and use those to wrap variable names, like so:
The content of <Payload> is treated as a message template. This means that the AssignMessage policy replaces variables wrapped in curly braces with the value of the referenced variables at runtime.
The following example uses the curly braces syntax to set part of the payload to a variable value:
You can use <QueryParams> only when the following criteria are met:
HTTP verb: GET
Message type: Request
If you define empty query parameters in your policy ( <Set><QueryParams/></Set> ), the policy does not set any query parameters. This is the same as omitting <QueryParams> .
Sets the reason phrase on the response. This is normally done for debugging in combination with <StatusCode> . This element has no effect on a request.
The content of <ReasonPhrase> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable, as the following example shows:
The content of <StatusCode> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable, as the following example shows:
The content of <Verb> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable.
The following example uses a variable to populate a verb:
The content of <Version> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable.
You can use <Version> only when the following criteria are met:
Message type: Request
The following example creates a custom request object with Assign Message:
Creates a new request message object called "MyCustomRequest".
On MyCustomRequest, this policy:
Copies the value of the user-agent HTTP header from the incoming request to the new message. Because <Copy> uses an absolute reference to the user-agent flow variable, there is no need to specify the source attribute to <Copy> .
Sets the address query parameter on the custom message to the value of the incoming request's addy query parameter.
Sets the HTTP verb to GET .
Sets <IgnoreUnresolvedVariables> to "false". When <IgnoreUnresolvedVariables> is "false", if one of the variables the policy tries to add does not exist, Edge will stop processing in the API flow.
Example 2 s98
Here's another example demonstrating how to create a custom request object with Assign Message:
This example creates a new custom request called "partner.request". It then sets the <Verb> and <Payload> on the new request.
You can access a custom request message in another AssignMessage policy that occurs later in the flow. The following example gets the value of the custom request message's user-agent header:
Convert REST request to SOAP request by setting SOAP Payload using the AssignMessage policy policy at API runtime.
Error codes
В этом разделе описаны коды ошибок и сообщения об ошибках, которые возвращаются, а также переменные ошибок, которые устанавливаются Edge, когда эта политика вызывает ошибку. Эту информацию важно знать, если вы разрабатываете правила обработки ошибок. Дополнительные сведения см. в разделах Что нужно знать об ошибках политики и Обработка ошибок .
Ошибки выполнения
Эти ошибки могут возникнуть при выполнении политики.
Код неисправности
Статус HTTP
Причина
Исправить
steps.assignmessage.SetVariableFailed
500
Политике не удалось установить переменную. См. строку ошибки, чтобы узнать имя неразрешенной переменной.
steps.assignmessage.VariableOfNonMsgType
500
Эта ошибка возникает, если атрибуту source в элементе <Copy> присвоена переменная, которая не имеет типа message .
Переменные типа сообщения представляют собой все HTTP-запросы и ответы. Встроенные переменные потока Edge request , response и message имеют тип message. Дополнительные сведения о переменных сообщения см. в справочнике по переменным .
Эти ошибки могут возникнуть при развертывании прокси-сервера, содержащего эту политику.
Название ошибки
Причина
Исправить
InvalidIndex
Если индекс, указанный в элементах <Copy> и/или <Remove> политики назначения сообщений, равен 0 или отрицательному числу, развертывание прокси-сервера API завершается неудачно.
Если дочерний элемент <Name> пуст или не указан в элементе <AssignVariable> , развертывание прокси-сервера API завершается неудачей, поскольку отсутствует допустимое имя переменной, которой можно присвоить значение. Требуется допустимое имя переменной.
Полезная нагрузка, указанная в политике, недействительна.
Переменные неисправности
Эти переменные устанавливаются, когда эта политика вызывает ошибку во время выполнения. Дополнительные сведения см. в разделе Что нужно знать об ошибках политики .
Переменные
Где
Пример
fault.name=" fault_name "
fault_name — это имя ошибки, как указано в таблице ошибок времени выполнения выше. Имя неисправности — это последняя часть кода неисправности.
fault.name Matches "UnresolvedVariable"
assignmessage. policy_name .failed
policy_name — указанное пользователем имя политики, вызвавшей ошибку.
assignmessage.AM-SetResponse.failed = true
Пример ответа об ошибке
{"fault":{"detail":{"errorcode":"steps.assignmessage.VariableOfNonMsgType"},"faultstring":"AssignMessage[AM-SetResponse]: value of variable is not of type Message"}}
For a more advanced example of how to override the target.url from the ProxyEndpoint, see this Apigee Community article .
To see a "set path" in action in a ServiceCallout policy , check out this Learn by doing example in the Apigee GitHub samples. Just clone the repository and follow the instructions in that topic. The example uses AssignMessage policy to set a request path, then uses a Service Callout policy to make the request to an external service.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 2026-08-27 UTC."],[],[]]