Environment postman что это






Что пишут в блогах
Стоимость в цвете — 2500 рублей самовывозом (доставка еще 500-600 рублей, информация по ней будет чуть позже)
Заказать — https://shop.testbase.ru/buy/book. Пока самовывоз (см ниже где и когда!!). С почтой разберемся чуть позже.
Где: Кострома / онлайн
2 декабря буду выступать в Костроме. Приходите увидеться очно, или подключайтесь онлайн.
Онлайн-тренинги
Что пишут в блогах (EN)
Blogposts:
Разделы портала
Про инструменты

Оригинал статьи
Перевод: Ольга Алифанова
Сегодня мы поговорим о множестве способов использовать переменные в Postman. Мы будем пользоваться ранее созданной нами коллекцией запросов, поэтому посмотрите предыдущие статьи, прежде чем читать дальше.
Первое, что нужно понимать о переменных в Postman: они организуются в окружения. Postman-окружение – это просто коллекция переменных, которые можно использовать в коллекции Postman. Создать окружение очень просто. Нажмите на значок шестеренки в правом верхнем углу окна, а затем на кнопку «Add». Дайте окружению имя (например, «Pet Store»), а затем нажмите на «Add».
Окружение ничем вам не поможет, пока вы не создадите в нем переменные, поэтому давайте этим и займемся. После добавления нового окружения вы должны были вернуться в окно «Manage Environments». Нажмите на вашем окружении, чтобы отредактировать его. В секции «key» введите petId, а в «value» введите 100. Нажмите на кнопку «Update», и вот вы добавили новую переменную.
Закройте окно «Manage Environments». В правом верхнем углу вы увидите выпадающее меню, и сейчас там написано «No Environment». Кликните на селекторе и выберите «Pet Store». Теперь при запуске запросов в вашей коллекции они будут выполняться в окружении «Pet Store».
У нас уже настроена одна переменная – petId, равная 100. Давайте посмотрим, как мы можем ее использовать!
Во-первых, ее можно использовать в URL. В запросе «Verify Add Pet» измените URL с http://petstore.swagger.io/v2/pet/100 на http://petstore.swagger.io/v2/pet/<
Переменную можно также использовать в заголовках запроса. В этой коллекции мы не будем этим заниматься, но пример такого использования – это отправка токена авторизации вместе с запросом. Вместо того, чтобы каждый раз вводить токен, вы можете сохранить его как переменную по имени «token», а затем передавать ее в заголовке вот так: <
Возвращаясь к нашей переменной petId: мы можем использовать ее в теле запроса. Откройте запрос «Add Pet» и измените тело запроса, чтобы оно выглядело так:
Мы заменили id 100 на нашу переменную. Можно отметить, как это полезно для тестирования. Предположим, мы решили не добавлять питомца с id 100, а предпочли другое значение. Это легко изменить, потому что нам нужно изменить одну переменную в одном месте (в окружении Pet Store), а не менять ее в каждом запросе, где использовался id 100. Не забудьте сохранить ваш запрос «Add Pet».
Еще мы можем использовать переменную в правилах. Вернитесь к запросу «verify Add Pet» и добавьте вот такое правило в секцию «Tests»:
var jsonData = JSON.parse(responseBody);
tests[«Correct pet ID is returned»] = jsonData.id == environment.petId;
Как можно заметить, это правило отличается от прочих правил нашего запроса. Другие правила написаны в новом стиле правил Postman, а это – в старом (если кто-то знает, как написать это правило в новом стиле, сообщите, пожалуйста!). Это правило сравнивает id, который возвращен телом ответа (jsonData.id) с id, установленной в качестве переменной окружения (environment. petId). Сохраните этот запрос и прогоните его, и увидите, как правило отработает.
И, наконец, мы можем устанавливать переменные окружения в зависимости от тела ответа на запрос. Давайте продублируем наш запрос «Add Pet» (см. статью «Создание коллекции Postman» для инструкций), и переименуем копию в «Add Pet With No Id». Мы будем использовать этот запрос для добавления питомца без указания id, чтобы программа назначила его самостоятельно. Измените тело запроса вот так:
Обратите внимание, что id, находившийся в начале запроса (petId) теперь удален. Теперь перейдите во вкладку «Tests» и добавьте там инструкцию:
var jsonData = JSON.parse(responseBody);
Это правило интерпретирует JSON-данные и устанавливает значение id, возвращенное сервером, в качестве новой переменной окружения по имени «newPetId». Обратите внимание, что и эта инструкция написана в старом стиле. Давайте сохраним наш запрос и запустим его. После прогона запроса нажмите на иконку глаза в правом верхнем углу экрана. Это быстрый просмотр окружения, позволяющий вам увидеть его переменные. Вы должны увидеть новую переменную newPetId со значением, присвоенным id вашего свежесозданного питомца! Эта фича позволяет вам не мучиться с созданием переменной заранее: Postman сделает это за вас!
Мы рассмотрели только одну переменную – petId. Вы можете добавить переменные для имени питомца, ссылок на фото, тип статуса, и чего угодно еще. Попрактикуйтесь в вашей коллекции запросов. Чем больше переменных вы создадите, тем легче будет поддерживать ваши тесты.
Больше информации по этой теме вы можете получить в курсе Тестирование REST API
Managing environments
An environment is a set of variables you can use in your Postman requests. You can use environments to group related sets of values together and manage access to shared Postman data if you are working as part of a team.
Environments quick start
A typical use of environments could work as follows:
You can use the current value of your environment variables to ensure that sensitive data values such as credentials are not accidentally shared. By using environments rather than global variables, you can control visibility of your data values within your workspace and team.
You will see the selected environment status at the top-right of Postman, with any active environment selected in the drop-down. In Environments on the left you can access all environments, and click the check-mark button to make an environment active. Select an environment to open it for editing in a tab.
To the right next to the drop-down you will also see the Environment quick look (eye) button. The quick look lists variables for the active environment, and any global variables you have declared (or that are shared via your workspace).
To create a new environment, select Environments on the left and click the + plus button.
Enter a name for your environment, and initialize it with any variables you need—you can alternatively specify variables for the environment later.
Click Save to save any environment variables you have added.
Adding environment variables
You can add variables to an active (currently selected) environment by opening the environment from the left of Postman and editing in the tab that opens.
Edit the variable names and values inline, or use the X button to delete a variable. Enter the name and values for a new variable on a new line. Save when your changes are complete.
Alternatively, open the environment quick look (the eye button at the top right) and edit inline.
If you are working with environment variables as part of a team, you will only be able to change initial values if you have edit access to the environment. You can access all variables in environments shared with you, but may have readonly access to initial values if you have viewer role.
Enter a name for your variable, and specify Initial and Current values for it—by default the current value will copy the initial value.
To update the synced variable with your local value, set the initial value to the current value by clicking . to the right of the variable row and choosing Persist. To reset your local (current) value with the synced value shared with your workspace / collaborators, click Reset. You can persist or reset all values in the environment using Persist All and Reset All.
You can access your environment variables from the Postman UI and from your request elements, including the URL, parameters, body data, and test scripts.
To see all of your environments, click Environments on the left of Postman.
Here you can add, share, duplicate, download, manage access, delete, and remove a shared environment from a workspace. You can also access your global variables by clicking Globals.
To view the variables in an environment, click its name. You can edit, add, and remove variables from the environment here.
Selecting an active environment
To use the variables in an environment, select it from the drop-down list at the top right of Postman.
To check a variable value at a glance, use the quick look (eye button).
When you have an environment selected in the drop-down, Postman will treat it as the active environment, and will run all requests against that environment (if your requests reference environment variables).
To use an environment variable value in a request, reference it by name, surrounded with double curly braces:
You can use the same variable notation in request URLs, parameters, headers, and body data.
Hover over a variable reference to see its current value.
If more than one variable with the same name is available to a request, Postman will use the value from the variable with narrowest scope. This means that if you have an environment variable with the same name as a collection or global variable, Postman will use the environment variable, but local and data variable values will supersede environment values. The value of any overridden variables will display with a strikethrough.
You can access current environment variable values in your Pre-request and Tests code.
Editing environment variables
You can edit variables either by opening an environment from Environments on the left, or by opening the environment quick look (eye button) at the top right of Postman, and clicking Edit.
You will only be able to edit environments where you have editor access.
Edit the environment name, or the names and values of your variables, bearing in mind that Initial Values will be synced with your Postman account and shared with any collaborators who have access to the environment. Click Save when your edits are complete.
If you have viewer access to an environment, you will see a padlock icon next to the name to indicate that it is readonly, and you will only be able to edit the current value, which is visible only to you and not synced with your Postman account or workspace. To edit initial values you will need to Request Access.
You can edit current values for variables in an active (currently selected) environment directly via the environment quick look. Click the pencil icon to edit your chosen value.
You can also update environment variable values from your test scripts.
Setting environment variables from scripts
Your Pre-request and Tests scripts can update environment variable values.
Use pm.environment to set an environment variable in the active (currently selected) environment:
You can only create new variables from a script in an environment that you have edit access to. If you update or unset a value in a script with viewer access to the environment, that change will only be visible to you and not shared with your team.
If you use scripts to set environment variable values, these will be reflected for all requests referencing the variables. For example, you can use environments in conjunction with the collection runner and monitors to share updated values throughout a run for a series of requests as well as after it completes.
Working with environments as a team
You can use environments to collaborate on your API development and testing processes with team members. Environments allow you to access shared resources and to configure visibility of restricted data such as specific server locations, and sensitive information like API keys.
In a shared workspace, any global variables you create and update will be available to others in the workspace. You can use the Current Value of global variables to restrict certain values from collaborators, but by default the Initial Value of a global variable is generally accessible throughout the workspace.
You can move environments to shared workspaces to collaborate with your team.
You must be an editor on an environment, or the workspace admin, to move an environment to another workspace.
Use the search bar to find the workspace you’d like to move the environment to, or filter by workspace visibility by selecting the icon to the right of the search bar.
You can share environments to personal, private, team, and public workspaces that you have access to. Shared private, team, and public workspaces allow you to collaborate with others.
You cannot move environments from team, private, or public workspaces to a personal workspace.
Refer to Roles and permissions for information on workspace access control within your team.
Select the workspace, then Move Environment.
Note that monitors, mock servers, and integrations in the original workspace that are using the environment may no longer work and will need to be re-configured in the new workspace. Collections and APIs that use the environment must be moved separately.
You can also remove a shared environment from a workspace by clicking . next to the environment name and choosing Move to move it to a different workspace or Delete to delete it entirely.
Managing environment roles
If you use personal credentials in your requests and the requests are pulling these from a shared environment (for example a variable storing an API secret value), you can restrict visibility of your credentials by only storing them in the current value of the variable. If you are managing an environment that’s shared across a team, you can restrict edit access so that most of your team only has viewer role on the environment, which prevents them from accidentally updating the shared value and leaking credentials. Similarly, you can prevent accidental changes to values by restricting the number of team members who have edit access to your environment.
In order to effectively leverage environments to preserve security and minimize the risk of accidental changes to variables, group your variables into environments you want to share as a coherent set, and then configure each user role so that access is only granted where it’s required, and that you can source any accidental changes.
When you open an environment without edit access you will see an option to Request Access, and will only be able to edit Current Values.
Default access allows collaborators to use variable values in their requests, but they can only edit the initial value of a variable if they have edit access to the environment as a whole.
Using an environment in viewer role
If you have view access to an environment, you will be able to access the value of the variables to use them in your requests, but will not be able to update the Initial Value, which is shared with your team. You can update the Current Value, but this is not shared with anyone on your team or synced with your Postman account.
If you are using sensitive data like API credentials, it’s safer to use the current value of an environment variable for these. You will not be able to Persist the current values to update the initial values of environment variables without edit access to the environment. You can use the Reset option to update your local current values with the shared initial value at any time.
Requesting environment access
If you need to update the initial value of a variable in an environment you have readonly access to, you can request edit access. Open the environment from Environments on the left of Postman and click Request Access.
Select the team member you want to submit the request to, and choose Editor from the drop-down list. Click Request Access. You will receive an email when your request is approved.
Using an environment in editor role
If you have edit access to an environment, you can update the variable values from the Postman UI and from your scripts. If you are using sensitive data such as personal or development / test credentials, make sure you only update these in the current value of a variable so that you do not accidentally share this information with your team.
When you edit the initial value of a shared environment variable, your updated value will be reflected for everyone who has access to the environment, so ensure that you only do this when you are happy for your value to be synced with the Postman servers.
If you uncheck (deselect) a variable in your environment, it will only be available to collaborators who also have edit access to the environment (and its enabled / disabled status will be reflected for them). Anyone with the viewer role for the environment will not see the unchecked variable.
With editor role, you can configure access for other team members. If you need to specify access but do not have the editor role, you can request access.
Shared environments allow you to leverage collaboration within Postman. Check out some more resources on how you can work with team members on your API development projects:
Postman. Смена окружений, предварительная настройка авторизации, установка переменных.
В предыдущей статье была затронута тема менеджмента коллекций, как лучше всё разложить по полочкам и какие виды коллекций можно создать. Также коснулись темы импорта и экспорта. Эта статья расскажет вам, как сделать предустановки для запросов, как менять окружения, на которые будут отправляться запросы. Рассмотрим способ предавторизации перед запросом, а также попробуем разобраться с инкрементом значений в теле запроса.
Смена окружений с помощью переменных
Обычно у проекта есть несколько окружений, как минимум dev + production, в лучшем случае — больше. И существуют ситуации, когда API следует протестировать на нескольких окружениях, но есть ли смысл создавать коллекции под каждое окружение? В случае с Postman — нет, так как там существует поддержка окружений (environments).
Чтобы использовать окружения, следует каждое из них настроить. Например, есть production окружение (я буду использовать открытое API от разработчиков Postman — Postman Echo https://postman-echo.com) и для настройки нужно выполнить следующие шаги:
Готово, окружение создано. Чтобы его использовать, необходимо иметь уже готовую коллекцию с заполненными запросами. Покажу всё на той же коллекции запросов к API Postman-Echo.
Также можно установить любое другое предустановленное окружение (Development, QA и т.д), нужно только выбрать его в правом верхнем выпадающем меню и изменить переменную, которая будет подставлять нужный Base URL.
Установка авторизации перед запросом
Настало время разобраться с тем, как установить значения для логина пользователя без запроса на логин. В предыдущей статье про менеджмент коллекций в списке запросов были постоянно повторяющиеся запросы “Login”. Рассмотрим, как установить авторизацию перед выполнением любого запроса, без постоянных запросов Login.
Представим, есть запрос на получение информации о пользователе. Сам запрос представляет из себя схему GET->URL без всяких Params, в которых иногда можно прописывать Username и Password. В нашем случае в “Params” эти переменные отсутствуют. Залогиниться в таком случае поможет вкладка “Authorization”.
При переключении на эту вкладку сразу видно, какой тип авторизации будет использован. В основном логин происходит либо по Token, либо по связке Username — Password (что в итоге тоже приводит к получению токена, но архитектура API может работать по-разному). В примере авторизация будет успешной по связке Username — Password. В левой части окна нужно выбрать тип “Basic Auth” и в правой части указать валидные Username и Password. После ввода этих данных и нажатия на кнопку “Preview Request”, получившийся token подставится во вкладку Headers и будет доступен. После этого, можно отсылать запрос и получить информацию о пользователе.
Теперь во всех запросах этой коллекции будет предустановлен полученный token при предавторизации.
Рассмотрим вид авторизации по токену. Он мало чем отличается от предыдущего метода, но для него нам предварительно понадобится получить токен пользователя через отдельный Login запрос.
— Выполнить запрос Login для получения токена
Теперь в любом другом запросе, где нужно, чтобы пользователь был изначально залогинен, во вкладке Authorization нужно выбрать тип авторизации — bearer token, ну а справа ввести тот токен, который был получен в запросе авторизации.
Запрос на авторизацию так же будет происходить перед выполнением основного запроса, как и в случае с введенными Username + Password. Остальные типы авторизации работают примерно по такому же сценарию.
Инкремент значений в теле запроса
В примере разберу запрос из коллекции Postman-echo “POST Raw Text” из папки “Request Methods” где нужно отправить в запросе POST текст, который вернётся в ответе от сервера вместе с другой информацией о создании записи.
Спасибо за прочтение статьи. Рекомендую ознакомиться с предыдущими статьями на тему Postman:
Я надеюсь, эти статьи помогут тебе в дальнейшем развитии в тестировании API. Успехов!






















