Introduction to Postman

Introduction to Postman
 
"API development is complex, Postman makes it easy" © Postdot Technologies, Inc
When you see the description of the tools Postman - breathtaking, the feeling of absolute power awakens over your future brainchild. It seems that the "monsters" grown up in the past will finally fall before you!
 
In this article, we'll talk about Postman and try to write your first script.
as the URL. https://postman-echo.com/get?userId=777 , and leave the method GET. Here and further for simplicity and convenience we will use the echo-server kindly provided by the developers of Postman. Save the query in the "Habra" collection and name it "Get user id", it will simulate getting the user ID from the server. Go to the "Tests" tab and write the following code:
 
//Test the response status and format
pm.test ("Status is ok, response is json", function () {
pm.response.to.be.ok; //status check
pm.response.to.be.json; //format check
});
try {
//save the userId from the json response to the environment variable
pm.environment.set ("userId", pm.response.json (). args.userId);
} catch (e) {
//output an exception to the console
console.log (e);
}

 
Using this script, we checked the status and format of the response, and also saved the user ID from the response in the environment variable for later use in other queries. To test the performance of our test, run the query. In the answer information panel, in the tab "Tests" you should see the green label "PASS", and next there is the inscription "Status is ok, response is json".
 
Step 2
 
Now let's try to insert our user's ID into the json request. Create a new query, specify as the URL. https://postman-echo.com/post , select the POST method, set the type for the request body to raw-application /json, and insert the body itself:
 
{"userId": {{userId}}, "username": "Bob"}
 
Save the query in our collection, and call "Update username", it will request an impromptu endpoint to update the username of the user. Now when you call the query instead of {{userId}}, the system will automatically substitute the value from the environment variable. Let's check that this is the case, and write a small test for our new query:
 
//test the response status and the format
pm.test ("Status is ok, response is json", function () {
pm.response.to.be.ok;
pm.response.to.be.json;
});
//check that the userId of the environment is equal to userId from the response
pm.test ("userId from env is equal to userId from response", function () {
.pm.expect (parseInt (pm.environment.get ("userId"))). to.equal (
pm.response .json (). data.userId
);
});

 
In our new test, we compare the userId received from the server with what is stored in our environment variable, they must match. Run the query and verify that the tests have passed. Well, we move on.
 
Step 3 3 r3r3397.
 
You might notice that the two test scripts have the same format and status checking:
 
pm.test ("Status is ok, response is json", function () {
pm.response.to.be.ok;
pm.response.to.be.json;
});

 
While we have not gone too far, let's fix this situation and transfer these tests to the collection level. Open the editing of our collection, and transfer the format and status checking to the "Tests" tab, and you can delete them from queries. Now these checks will be automatically called before the "Tests" scripts for each query in the collection. So we got rid of copying this check into each request.
 
Step 4
 
We have learned to write and receive environment variables, it's time to move on to something more powerful. Let's use the built-in library tv4 (TinyValidator) and try to check the correctness of the json schema of the object. Create a new query, use as the URL. https://postman-echo.com/post , set the method to POST, specify raw-application /json for the request body, and insert:
 
{
"profile": {
"userId": {{userId}},
"username": "Bob",
"scores":[1, 2, 3, 4, 5],
"age": 2?
"rating": {"min": 2? "max": 100}
}
}

 
After running the request, the echo server should return our json model to us as a response in the "data" field, so we simulate the operation of a real server that could send us information about Bob's profile. The model is ready, we will write a test that verifies the correctness of the scheme:
 
//get the profile from the answer
var profile = pm.response.json (). data.profile;
//describe the scheme of the model
var scheme = {
//specify the type of the object
"type": "object",
//specify the required properties
"required":["userId", "username"],
//describe the properties of
"properties": {
"userId": {"type": "integer"},
"username": {"type": "string"},
"age": {"type": "integer"},
//describe the array
"scores": {
"type": "array",
//type of elements
"items": {"type": "integer"}
},
//describe the nested object
"rating": {
"type": "object",
"properties": {
"min": {"type": "integer"},
"max": {"type": "integer"}
}
}
}
};};
pm.test ('Schema is valid', function () {
//we validate the profile object using rules from scheme
var isValidScheme = tv4.validate (profile, scheme, true, true);
.
//expect the validation result to be true
pm.expect (isValidScheme) .to.be.true;
});

 
Done, we ran the profile of the profile object. Run the query and verify that the tests pass.
 
Step 5
 
We have a small way out of 3 queries and several tests. It's time to completely test it. But before that, let's make a small modification to our first query: replace the value of "777" in the URL to the "{{newUserId}}" and add "newUserId" to the "Habra.Env" environment with the value "777" . Create the users.json file on your computer and put the following json array:
 
[
{"newUserId": 100},
{"newUserId": 200},
{"newUserId": 300},
{"newUserId": 50000}
]

 
Now run Runner. As the "Collection Folder", select "Habra". As "Environment" we will put "Habra.Env". The number of iterations is ? and in the "Data" field, select our users.json file. On this file, "Collection Runner" will understand that it needs to make 4 iterations, and in each iteration it will replace the value of the variable "newUserId" with the value from the array in the file. If you specify a number of iterations greater than the number of elements in the array, then all subsequent iterations will occur with the last value from the data array. In our case, after 4 iterations, the value "newUserId" will always be equal to 50000. Our "Data" file will help us to go all our way with different newUserId, and make sure that everything is executed irrespective of the user.
 
Run our tests by clicking "Run Habra". Congratulations, you have successfully created the collection and tested our improvised way with the help of autotests!
 

 
Testing the collection "Habra"
 
Now you know how to create scripts and you can write a couple of tests for your project.
 
Separately, I want to note that in a real project we do not keep all requests in the root of the collection, but try to put them into folders. For example, in the folder "Requests" we add all possible requests describing our API, and the tests are stored in a separate folder "Tests". And when we need to test the project, run only "Tests" in "Runner".
 
 
Collection, environment and data from example
 
 
It is useful to know
 
In conclusion, we give the basic commands that you might need while writing scripts. For better assimilation, try to play with them yourself.
 
Setting and obtaining variables
 
//global variables
pm.globals.set ("key", "value");
pm.globals.get ("key");
//environment variables
pm.environment.set ("key", "value");
pm.environment.get ("key");
//local variables
pm.variables.set ("key", "value");
pm.variables.get ("key"); //if there is no local, will search at a level above

 
Testing or asserts
 
//using the anonymous function and special assert constructions
pm.test ("Test name", function () {
pm.response.to.be.success;
pm.expect ("value"). to.be.true;
pm.expect ("other ") .to.equal (" other ");
});
//using a simple condition and array tests
tests[“Название теста”]= ("A"! = "B");
tests[“Название теста 2”]= true;

 
Creating queries
 
//example get request
pm.sendRequest ("https://postman-echo.com/get", function (err, res) {
console.log (err);
console.log (res);
});
//example post request
let data = {
url: "https://postman-echo.com/post",
method: "POST",
body: {mode: "raw", raw: JSON.stringify ({key: "value"})}
};};
pm.sendRequest (data, function (err, res) {
console.log (err);
console.log (res);
});

 
Getting the answer for the main query
 
pm.response.json (); //in the form of json
pm.response.text (); //in the form of the line
responseBody; //in the form of the line

 
The answer is only available in the tab "Tests"
 
Working with the built-in libraries
 
The documentation regulates the presence of a number of built-in libraries, among which is tv4 for the validation of json, xml2js the xml converter in json, crypto-js for encryption, atob, btoa, etc.
 
//connect xml2js
var xml2js = require ("xml2js");
//convert simple xml to json object
xml2js.parseString ("
Hello xml2js!
", function (err, res) {
console.log (res);
});

 
Some of the libraries, for example, like tv? do not require direct connection via require and are accessible by name at once.
 
Getting information about the current script
 
pm.info.eventName; //returns test or prerequest depending on the context
pm.info.iteration; //the current iteration in Runner
pm.info.iterationCount; //total number of iterations
pm.info.requestName; //the name of the current request is
pm.info.requestId; //the internal identifier of the request

 
Managing the sequence of requests from the script
 
It is worth noting that this method works only in the run mode of all scripts.
 
//set the following query to
postman.setNextRequest ("Request name"); //by the name of
postman.setNextRequest (ID); //by the identifier
//stop execution of
requests. postman.setNextRequest (null);

 
After going to the next query, Postman returns to linear sequential query execution.
 
Creating a global helper
 
In some cases, you will want to create functions that must be available in all queries. To do this, in the first query in the "Pre-request Script" section, write the following code:
 
//create and save a helper for global use of
pm.environment.set ("pmHelper", function pmHelper () {
let helpers = {};
.
.s helpers.usefulMethod = function () {
console.log ("It is helper, bro!") ;
};
.
Return helpers;
} + '; PmHelper ();');

 
And in the subsequent scripts we use it like this:
 
//get the object
var pmHelper = eval (pm.environment.get ("pmHelper"));
//call our method
pmHelper.usefulMethod ();

 
This is just a small list of useful commands. The possibilities of scripts are much wider than can be covered in one article. Postman has good "Templates" that you can find when creating a new collection. Do not hesitate to peek and study their implementation. And the official documentation contains answers to most questions.
 
 
Official site
 
Documentation for Postman
 
List of built-in libraries
 
 
Conclusion
 
The main pluses that prompted us to use Postman in our project:
 
 
Visibility - all requests are always at hand, manual testing during development becomes easier
 
Quick start - involving a new player in the team, whether it's a programmer or a tester, passes easily and quickly
 
Tests - the ability to write tests for queries, and then quickly compose from them, as from puzzles, various options and ways of life of the application
 
CI support - the ability to integrate tests in CI with the help of newman (this will be a separate article)
 
 
Among the minuses can be identified:
 
 
Editing the collection is tied to Postman, i.e. for changes, you will need to make the import, edit, and then do the export to the project repository
 
Since the collection is in one large json file, the Review of changes is almost impossible
 
 
Each project has its own approaches and views on testing and development. We saw for ourselves more pluses than minuses, and so we decided to use this powerful tool both for testing and for describing the requests for the API of our project. And from our experience we can say, even if you do not use the testing tools provided by Postman, then having a description of the queries in the form of a collection will be very useful. Postman collections are live, interactive documentation for your API, which will save a lot of time, and at times will speed up development, debugging and testing!
 
P.S .:
 
The basic functionality of Postman is free and meets daily needs, but there are some tools with a number of limitations in the free version:
 
 
Postman API - allows you to access your account data, add, delete and update collections, queries, and other information programmatically, directly through the API. You can apply to him 1000 times a month.
 
Mock Server - allows you to deploy stubs for your API on Postman developer servers. There are 1000 requests per month.
 
Api Monitoring - allows creating collections for monitoring and launching them on a schedule from the Postman developer's servers. The monitoring system will do for you no more than 1000 requests per month
 
Api Documentation - allows you to publish automatically generated documentation on the servers of the Postman application. Limitation of 1000 views per month
 
+ 0 -

Add comment