postman preliminary and common scripts

Posted by 121212 on Wed, 09 Mar 2022 14:14:11 +0100

The design of docking interface parameters is simple and easy.

A brief introduction to Postman

  • Chrome post is a powerful API for debugging web requests.
  • Postman can send any type of http request and support GET/PUT/POST/DELETE. Any number of headers can be attached to the request header.
  • Postman supports different authentication mechanisms (basic, digest, OAuth).
  • Postman is very simple and easy to use. You can send a request by filling in the URL, header, body, etc.
  • No Chinese support.
  • Postman uses the interface in chrome.
  • Postman is based on js language.

Official address

  1. Official website address:
  2. Official document address:
  3. Official address of problem feedback:
  4. Official git address:
  5. Official case study:
  6. Official blog:
  7. Official download address:

The versions are:

  1. chrome plug-in version
  2. mac version
  3. linux Version (32 / 64)
  4. windows client version (32 / 64)


  1. The package used to run the postman script.
  2. Based on nodejs.
  3. Designed for postman.
  4. Powerful function, can generate html and other reports, and can do continuous integration.

1, postman download and installation

1. Download

  • (1) First: Baidu online disk download address:


Extraction code: w465

  • Second: download from the official website:

Click me to open the official website of postman to download

2. Installation

  • windows version, download and install all the way.

  • After installation, open it and register an account to use it.

To register an account, you need a personal email. You need to take a user name and set a password

2, Familiar with postman interface

1. Collection bar


2. Request bar


3. New column


4. Useful little buttons


3, Detailed function introduction

1. Global settings

(1) Global settings entry

  • Entrance 1:


  • Entrance 2:


(2) Global settings -- Genaral

Global settings - Genaral: you can set font size, SSL certificate authentication, etc


(3) Global settings -- Theme

You can set two themes: default white and dark


(4) Global settings -- View version


2. Assemble

(1) New collection


(2) Edit fields when creating a new set

You can edit the name, description, authentication, pre script, post script and variable of the collection.

Generally, you can only edit the name, description and.


(3) What operations can a collection do?

Rename, edit, add interface request, add folder, copy, export, delete


3. Interface request

(1) url of the interface request


(2) Send interface request


(3) Save interface request

There are two types: save and save as


(4) Input parameter of get request

The input parameters of the get request should be written in Params:


(5) Input parameters of post request

  • The input parameters of the post request should be placed in the body


  • post input parameter types supported by postman


  • Differences between commonly used urlencoded and form data types:

<tr style="font-weight: bolder">
<td>Post requests have different parameter transfer methods</td>
<td>If not specified, the default method is key1 = value1 & key2 = Value2</td>
<td>It is generally used for form file upload</td>

(6) Pre script

  • The pre script is placed in the pre request script:


(7) Post script

  • Put the post script in Tests:


(8) Response data

  • Pretty view:


  • Raw view:


  • Preview view:


(9) Run set

  • A. Operation entrance:


  • B. Understanding of operation collection interface:


  • C. After running a collection, you will see the running results:


  • D. Click the orange button "Run Summary" in the figure below to view the summary results:

  • E. Summary result display:

4, Assertion of common scripts in postman

1. Status code and description

==(1) The status code is 200==

pm.test("Status code is 200", function () {; # 200 is of type int

(2) Status code name (OK, Not Found...)

pm.test("Status code name has string", function () {"Created"); # Created: string type

(3) The actual status code is among the expected status codes

pm.test("The status code is 200 or 201", function () {

2. String assertion in response

**(1) Check whether the response body * * is equal to the string****

pm.test("Response data = Some string", function () {"response_body_string");

==**(2) Check whether the response body * * contains a string****==

pm.test("Body matches string", function () {

3. Check JSON value (※ extremely important ※)

==(1) Check whether the value of a field in the response data is equal to xxx==

pm.test("Your test name", function () {
    var jsonData = pm.response.json();

==(2) Judge whether a field is included under a field in the response (in js language)==


pm.test("Checking response choose_subject Whether the field contains name field",function(){
    var jsonData = pm.response.json();
jsonData.choose_subject.containsKey.every(item => "name" in item); //(don't look at this)

The following is the one with js loop added (it can be ignored):

pm.test("Checking response choose_subject Whether the field contains name field",function(){
    var jsonData = pm.response.json();
    for (i=0; i<jsonData.choose_subject.length; i++ ){ 
        oneJson = jsonData.choose_subject[i];
// jsonData.choose_subject.containsKey.every(item => "name" in item);

==(3) Judge whether the value of a field under a field in the response contains a string (in js language)==


pm.test("The response contains buy_status Field below subject_name The field value includes string Chinese, mathematics and English", function () {
    var jsonData = pm.response.json();

==(4) Judge that the value of a field in the response is not empty (not 0, "", [], {}, etc.)==

pm.test("response content The value of the field cannot be empty", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.content ? true:false).to.eql(true);

4. A key in the header exists

pm.test("Content-Type is present", function () {"Content-Type");

5. Determine the field data type in the response

I'll sort out several types of:

number, string, object, array, boolean, undefind (empty)

pm.test("term_type It's an integer", function () {
    pm.expect(typeof(jsonData.return_list[0].term_type) === "number").to.eql(true);

pm.test("id Is a string", function () {
    pm.expect(typeof(jsonData.return_list[0].id) === "string").to.eql(true);

pm.test("success  Is a Boolean value", function () {
    pm.expect(typeof(jsonData.success) === "boolean").to.eql(true);
pm.test("return_list yes array array", function () {
    pm.expect(jsonData.return_list instanceof Array).to.eql(true);
pm.test("name Field not defined(Or it doesn't exist)", function () {
    var jsonData = pm.response.json();
    pm.expect(typeof( === "undefined").to.eql(true);

Expand js language (for loop):

var jsonData = pm.response.json();
for (i=0; i<jsonData.choose_subject.length; i++ ){ 
    oneJson = jsonData.choose_subject[i];
    console.log(oneJson );       

6. Response time

  • Response time less than 200 ms
pm.test("Response time is less than 200ms", function () {
  • Response time greater than 10 ms
pm.test("Response time less than 200 ms", function () {

7. json advanced

(1) Get JSON data using TinyValidator

var schema = {
     "items": {
     "type": "boolean"
var data1 = [true, false];
var data2 = [true, 123];

pm.test('Schema is valid', function() {
  pm.expect(tv4.validate(data1, schema));
  pm.expect(tv4.validate(data2, schema));

(2) JSON schema validator

var Ajv = require('ajv'),
    ajv = new Ajv({logger: console}),
    schema = {
        "properties": {
            "alpha": {
                "type": "boolean"

pm.test('Schema is valid', function() {
    pm.expect(ajv.validate(schema, {alpha: true}));
    pm.expect(ajv.validate(schema, {alpha: 123}));

(3) Convert XML body to JSON object

var jsonObject = xml2Json(responseBody);

8. Decoding base64 encoded data

var intermediate,
    base64Content, // assume this has a base64 encoded value
    rawContent = base64Content.slice('data:application/octet-stream;base64,'.length);

intermediate = CryptoJS.enc.Base64.parse(base64content); // CryptoJS is an inbuilt object, documented here:
pm.test('Contents are valid', function() {
  pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)); // a check for non-emptiness

5, postman advanced script

1. Send request (pm.sendRequest)

(1) Send get request

//const is the definition constant
const url = '';
// Send get request
pm.sendRequest(url, function (err, res) { //The first two exceptions must be named, but the second one must be named err
  console.log(err ? err : res.text());  // The console prints the request text. res.text(),res.json()

(2) Send form post request

//Construct a login request
const loginRequest = {
    url: '',
    method: "POST",
    body: {
        mode: 'urlencoded',  // The mode is the form url encoding mode
        urlencoded: 'name=Zhang San&password=123456'

// Send request
pm.sendRequest(loginRequest, function (err, res) {
    console.log(err ? err : res.text());

(3) Send JSON format request

// Construct a registration request
const regRequest = {
  url: '',
  method: 'POST',
  header: 'Content-Type: application/json',  //Note that the type used by the content should be declared in the Header
  body: {
    mode: 'raw',  // Use raw format
    raw: JSON.stringify({ name: 'Small', password: '123456' }) //To convert a JSON object to text, send

// Send request
pm.sendRequest(regRequest, function (err, res) {
  console.log(err ? err : res.json());  // The response is in JSON format. You can use res.json() to get the JSON object

(4) Send XML format request

Sending XML format is similar to sending JSON format, as long as you specify the content format and send the corresponding content

//Construction request
const demoRequest = {
  url: '',
  method: 'POST',
  header: 'Content-Type: application/xml',  // Request header specifies the content format
  body: {
    mode: 'raw',
    raw: '<xml>hello</xml>'  // Send xml as text

//Send request
pm.sendRequest(demoRequest, function (err, res) {
  console.log(err ? err : res.json());

2. Change interface request order

Usefulness: sometimes we don't want collections to execute interfaces in strict order. At this time, you can change the order of interface requests.

give an example:

If there are three interfaces A, B and C under your collection, the return field of interface A has A content_type,

When content_ When type = 1, we expect to execute B interface and then C interface to end;

When content_ When type = 2, we expect the direct execution of C interface to end;

(1) General mode

  • postman.setNextRequest('name of interface request ');
//Change interface execution order
postman.setNextRequest("Send with script post request");

(2) Branching mode

var jsonData = pm.response.json()

if(jsonData.args.a == 'a'){

(3) Polling mode

Scenario: when the response data of this interface is "{} \ n", execute this interface again until the response data changes

if(pm.response.text() == "{}\n"){
    postman.setNextRequest("Name of its own interface");

3. Print the request url, input parameter and response information in the script

(1) Print all information of the request (including url, input parameters, headers, etc.)


(2) url of the print request


The url of the get request is parameterized;

The url of the post request has no parameters

(3) Print all input parameters of get request

For example, the url of the get request is:



(4) Print all input parameters of the get request and one input parameter

For example, the url of the get request is:


I want to print the value of sid input parameter:

  • The first method:
  • The second method:

In the above method, when the input parameter sequence changes, the wrong value will be taken. In order to get the correct value, it is optimized as follows:

var keys = request.url.split('?')[1].split('&');//Get all the parameters and form an array

for(index in keys){
    key = keys[index].split('=')[0]; //Get the key of parameter pair
    value = keys[index].split('=')[1]; //Get value of parameter pair
    if(key === 'sid'){ //When the key of the parameter pair = the sid I want
        let sid = value; Customize a variable called sid,The value is equal to the value of the above parameter pair value

(5) Get all input parameters of post parameter


(6) Get the parameter "mobile" in the input parameter of the post parameter


(7) Get the headers of the request


4. Print response information in script

(1) Get all response information


(2) Get the headers of the response


(3) Acquisition and response code


5. Calculate array length

function count(o){
    var t = typeof o;
    if(t == 'string'){ //Calculates the length of the string
        return o.length;
    }else if(t == 'object'){//Calculate the length of the array
        var n = 0;
        for(var i in o){
        return n;
    return false;

var lesson = jsonData.lessons[0];
console.log(count(lesson));//Call the count method

6, Get a returned HTML file for verification

var html, titleText;
// load the response body as HTML using cheerio
// and using cheerio's jQuery like .find API, get the H1 tag
html = cheerio(responseBody);
titleText = html.find('h1').text();
// add a test that ensures that there is some H1 content
tests["page must have h1 heading"] = Boolean(titleText);


Topics: PostMan