当前位置:网站首页>Postman tutorial - teach you API interface testing by hand

Postman tutorial - teach you API interface testing by hand

2022-06-23 20:27:00 Jiangchuan

First article :Postman Use the tutorial - API Preliminary study on interface automatic test

Postman It's a set API Interface testing tool , Its power lies in its flexible interface test function , Greatly improved API Test efficiency . This tutorial will go from simple to deep , Lead everyone to learn how to use Postman Conduct interface test .

API What is it? ?

API English is Application Programming Interface Acronym for . Don't be frightened by such a long word , The literal translation means : The interface between programs . I prefer to put API Understood as a , Contracts between procedures . of API What it is and its significance will not be discussed here ,

Postman What is it? ?

Postman Is a API Develop collaboration tools , It can help you test and develop API,Postman Provides testing API Friendly interface and function , Easy to use , Safe and reliable .Postman yes API Of interface test tools Top 3, Because it's simple, reliable and free , There are currently more than 800 Million developers and users use . especially API Batch test function , In recent major version updates , The user experience has been greatly improved .Postman It is a development tool that every front-end and back-end developer must master .

One . How to install Postman

How to install Postman

Go to Postman Download for free on the official website , Installation is very stupid , I don't want to start writing here , If there are any problems with the installation process , Welcome to ask questions in the comment area .

Postman Support Windows、Mac and Linux, You can also run directly in the browser , Cross platform , Easy to use .

Two . API Simulation tools GoRest

This tutorial uses simulation API Tools GoRest To simulate API test .GoRest There are many usage scenarios , such as , When the back-end interface is not ready , We can use GoRest Simulation test , Or you don't want to build a server for the time being , I don't want to build a back-end , You can also use GoRest To test .

GoRest It can be understood that the back-end engineer helped you set up the back-end server , And it's completely measured , It's almost impossible to have Bug.GoRest Except that the data is simulated , all API The response is completely true , You can go through API The returned data of the call determines whether there is a problem with your front end .

API Simulation tools GoRest

GoRest Of API call URL And the rules .

Usually API from BaseURL + Endpoint constitute . For example, the first one in the figure above Resources:

https://gorest.co.in/public/v1/users

This API By https://gorest.co.in + /public/v1/users namely BaseURL +Endpoint Composed of . Generally, we can start from API The address shows the general idea of calling for information , This paragraph URL Is to call GoRest About users Information about .

Next section , We use GET Request to call this API , See if the returned result is consistent with users Information related .

3、 ... and . use Postman Send out the first GET request

1. GET Request basic operation

GET The request is API One of the most frequently used requests in ,GET Request only requests to read data from the database , The data in the server will not be modified .

Next , Let's create a basic GET request

GET Request basic operation

(1) Click on the main interface 「+」 Number , Create a new request page

(2) choice GET Request command

(3) Input API Address :

https://gorest.co.in/public/v1/users

stay GoRest API In design GET The request does not require authentication ( Next section POST The request will explain API Authentication ), All of us directly click 「Send」 You can access the server information remotely .

GET Request basic operation

Click on 「Send」, We can see below Body Shows GET API Return value , The first paragraph is users Information Overview , Here is a group user Information .

What should we do if we just want to see and retrieve the information of one of the users ? We can do it in API URL With parameters .

2. Parameterized GET request

Parameterized GET request

If we want to check ID by 2043 User information for , We just need the... In the request page Params( Parameters ) On the tab KEY - VALUE Fill in the corresponding parameters in the , after Postman Will be automatically API URL Generate the parameters you fill in , send URL Bring parameters GET request .

https://gorest.co.in/public/v1/users?id=2043

After setting up , Click on 「Send」

Parameterized GET request

We can see , The return value contains only the user id by 2043 User information for .

3. GET Multi condition query in request

Sometimes , We need to use API Perform multi condition query , Like looking for name The value is kalacloud.com , meanwhile gender The value is male Users of .( hot tip : This format is a general way of writing , But in the end, it depends on API How do developers agree on how to call )

BaseURL + ResourceName + ? + key1 = value1 + & + key 2 = value 2 ……

Lord URL Then use ? Connection parameters , Use... Between parameters & Connector connection .

https://gorest.co.in/public-api/users/?name=kalacloud.com&gender=male
GET Multi condition query in request

Of course , We can go straight to Postman Of Params Fill in KEY - VALUE

GET Multi condition query in request

Give Way Postman Help us generate , And then click 「Send」

GET Multi condition query in request

You can see API GET Transferred the two we set VALUE It's worth it data Information .

hot tip , You can click on... In the upper right corner 「Bulk Edit」 Batch editing of parameters

bulk-edit

Params Batch editing mode .

Four . stay Postman Sent in POST request

In this section, we talk about POST request ,POST Request and GET The biggest difference between requests is GET Request to read data only in read-only form , and POST The request will modify the data in the server , For example, create new users , Create user information , Uploading pictures and other operations are done with POST Accomplished .

1. POST Before request , Use Postman Yes API authentication

POST No longer just reading data , It involves writing data , This sensitive operation , It must involve account authentication .

GoRest simulation API Tool use HTTP Basic Authentication Authentication method

GoRest simulation API The tool has two authentication methods

This authentication method can be directly placed in Headers China and Israel Key - Value In the form of , This tutorial demonstrates a slightly more complex OAuth2 Authentication method , So that we can learn more .

First, in the GoRest Registered account , Then click on the top 「Rest Console」 Enter the control page , We can get our own... On this page Auth Token, This is API The key used for authentication .

postman-api-token

stay Postman Request page Auth In the label , Select the authentication type (Type) by OAuth 2.0, And then in Access Token Fill in this paragraph on the web page Value after , Select... In the request type POST, Input API Request address

https://gorest.co.in/public/v1/users

And then click 「Send」

HTTP The response code returns 422

If HTTP The response code returns 422, Indicates that the authentication is successful , Just didn't fill in the data .

hot tip : Used in this case GoRest API Is to test first Token Whether it is right , And then we're testing body Etc . There are also cases where the submitted information is checked for correctness before authentication API, It depends. API How do developers set , So in this case 422 It doesn't mean authentication is successful . So be careful , all 4XX Response code beginning with , You can understand that there was a mistake .

Authentication failed

If you return 401 Description authentication failed (Authentication failed) Yours Token Maybe the copy is wrong , Please check and try again .

After successful authentication , Next section , We go through API POST Request to write the first set of data to the server database .

(2) use Postman Send out the first POST request

Previous section , We go through API Token Authentication success , Now let's set... On the request page POST Request information .

use Postman Send out the first POST request

1. Request command selection POST, Then fill in the address column API Address :

https://gorest.co.in/public/v1/users

2. stay 「Auth」 The tab is set according to the previous section of this article API authentication Access Token

3. stay Body Choose from raw And then choose JSON Format .

4. Put the following JSON Fill in the edit box with the code , This is this POST Content sent to the server .

5. We will register a new user , User information is included in this JSON In the text .

{
  "name": "kalacloud",
  "gender": "Male",
  "email": "[email protected]",
  "status": "Active"
}

Last , Click on 「Send」, send out POST request .

post-api-id-2151

We can see API Return information , New users have been registered in the server , new user ID by 2151, And return the user registration information we just submitted .

If you see a similar result , So congratulations , Your first POST The request was successfully accepted by the server , You passed API Registered a new user on the server .

5、 ... and . use Postman Send the first PUT Update request

PUT The request is generally used to update the existing resources of the server , If there is no corresponding resource in the server , that PUT The corresponding resource will be created ( Special reminder : although PUT It has the function of creating new resources , But whether it can be created successfully , Ultimately, it depends on what you call API Whether this function is supported )

Open your Postman So let's create one PUT request .

  • Click on 「+」 Number , Create a new request page
  • Request type selection 「PUT」
  • According to section 4 we use POST Resource requested to be created ID by 1475 , According to GoRest API The documentation of , Modify the of the resource API The address is https://gorest.co.in/public/v1/users/{{ID}} , So we use PUT modify ID by 1475 The request address of the resource should be written :
https://gorest.co.in/public/v1/users/1475
  • Choice in Body Fill in the label JSON Resource modification information in format . We will 1475 The mailbox in is by [email protected] It is amended as follows [email protected], So we are Body Fill in the following code .
{
  "name": "kalacloud",
  "gender": "Male",
  "email": "[email protected]",
  "status": "Active"
}
  • choice Auth label , Conduct API authentication , The authentication method is detailed in Section IV of this paper 《 Use Postman Yes API authentication 》
  • Click on 「Send」 send out PUT request
use Postman Send the first PUT Update request
  • As shown in the figure above , You can see red 4 Location The response code returns 200 , This explanation PUT The request has been executed successfully .
  • Back to Body In information ,email The field has been updated to [email protected]

6、 ... and . use Postman Send the first PATCH Update request

PATCH Requests are generally used for partial updates of server resources , It is relative to the PUT Less data submitted , Not to mention the whole data , Just submit the fields that need to be modified . of PUT and PATCH More differences between , See Section 7 of this article .

Open your Postman So let's create one PATCH request .

  • Click on 「+」 Number , Create a new request page
  • Request type selection 「PATCH」
  • According to section 4 we use POST Resource requested to be created ID by 1475 , According to GoRest API The documentation of , Modify the of the resource API The address is https://gorest.co.in/public/v1/users/{{ID}} , So we use PATCH modify ID by 1475 The request address of the resource should be written , I'm here with PUT The method of requesting to modify resources is the same .
https://gorest.co.in/public/v1/users/1475

Choice in Body Fill in the label JSON Resource modification information in format . In the last section, we have ID by 1475 The mailbox of the resource is changed to [email protected] , Then we use PATCH Please change this email address to [email protected]

{
"email":"[email protected]" 
}
  • choice Auth label , Conduct API authentication , The authentication method is detailed in Section IV of this paper 《 Use Postman Yes API authentication 》
  • Click on 「Send」 send out PATCH request
use Postman Send the first PATCH Update request
  • As shown in the figure above , You can see red 4 Location The response code returns 200 , This explanation PATCH The request has been executed successfully .
  • Back to Body In information ,email The field has been updated to [email protected]

7、 ... and . PUT and PATCH The difference between

stay HTTP Agreement ,PUT and PATCH Are commands used to update server resources , But they have different formats and uses .

PUT request : It is generally used to update the existing resources of the server , If there is no corresponding resource in the server , that PUT The corresponding resource will be created ( Special reminder : although PUT It has the function of creating new resources , But whether it can be created depends ultimately on what you call API Whether this function is supported )

PATCH request : Used to locally update the existing resources of the server , It doesn't have to be like PUT Update a little bit of resources and submit all field information ,PATCH You can submit the update information of which field you want to update .

Illustrate with examples PUT and PATCH The difference between :

PUT and PATCH The difference between

The same is to update the Email Information ,PUT You need to bring all the information in the resource , Then update ( Upper figure )

and PATCH Then only the updated part needs to be submitted , That is, only submit email information ( The figure below )

PUT and PATCH The difference between

that , If PUT image PATCH Similarly, what happens when only partial information of resources is submitted ? Meeting 400 Report errors .

PUT and PATCH The difference between

PUT No matter how many changes , You must write all the fields of the modified resource , Otherwise 400 Report errors .

8、 ... and . use Postman Send the first DELETE Delete request

We talked about obtaining (GET), establish (POST), to update (PUT / PATCH) request , Then let's say delete (DELETE) request . seeing the name of a thing one thinks of its function ,DELETE Request execution can delete the entire resource . Let's just do it once and you'll see .

Open your Postman , Follow this tutorial to create a DELETE request .

  • Click on 「+」 Number , Create a new request page
  • Request type selection 「DELETE」
  • Let's take what we just created above ID by 1475 Completely delete your resources . according to GoRest API The documentation of , Delete the of the resource API Request address is https://gorest.co.in/public/v1/users/{{ID}} , So we use PATCH Delete ID by 1475 The request address of the resource should be written :
https://gorest.co.in/public/v1/users/1475
  • choice Auth label , Conduct API authentication , The authentication method is detailed in Section IV of this paper 《 Use Postman Yes API authentication 》
  • Click on 「Send」 send out DELETE request , Delete the corresponding resource .
use Postman Send the first DELETE Delete request

As shown in the figure above , Submit DELETE After the request , The response code is 204 , Back to body It's empty , Delete successful .

hot tip : stay GoRest In the documentation of , In particular DELETE Delete the status of the return value .

use Postman Send the first DELETE Delete request

API What is the return status , Also look at API How do developers agree , Not just return 200 It's the success .

Nine . Postman Global variable in 、 environment variable 、 Setting of set variables

1. Postman Setting the meaning of variables

Postman There are many variables in , We can abstract some important values into variables , It's convenient for us to do scenes / Conditional switching . such as , We can baseURL Pull it out , Set... In the environment variable 「 Production environment variables 」 and 「 Test environment variables 」, after , We just need to switch labels to quickly switch data from one environment to another , Very convenient .

2. Postman Three commonly used variable forms

  • Global variables : Once a global variable is declared , Can be applied to Postman Of all tests in API in . Any request can use global variables directly , Its scope is global .
  • environment variable :Postman Environment variables can be understood as a set of options , When this set of environment variable options is selected , Will take effect , Perfect for 「 Production environment 」 and 「 Test environment 」 Application scenarios such as switching between .
  • Set variable : Set variables are for sets (Collections) Effective , There may be under a set N strip API request , Set variables can modify the values of all variables under the set at one time .

The scope of the above three variables is from large to small overall situation > aggregate > Environmental Science , When three variable forms act on one at the same time API When testing the strip ,Postman The minimum scope variable will be used first .

3. How to be in Postman Set global variables and environment variables

How to be in Postman Set global variables and environment variables
  • Create a new request page , Click on the 「 Little eyes 」 Enter the variable setting page .
  • At the top of the page is 「 environment variable 」, We click Edit to set the environment variable named 「 Karayun _API Test environment 」
  • VARIABLE Set to baseURL,INITIAL VALUE Set to https://gorest.co.in , After saving, we can use {{baseURL}} Variable instead of API URL 了 .
  • At the bottom of the page is 「 Global variables 」,VARIABLE Set to kalacloud_id,INITIAL VALUE Set to 2312 (2312 by GoRest An existing user information in ID), After saving, we can use {{kalacloud_id}} Variable instead of ID The value of .

Let's test the just set 「 Global variables 」 and 「 environment variable 」 Whether to take effect .

  • Create a new one GET Request page , Fill in the address column :
{{baseURL}}/public/v1/users?id={{kalacloud_id}}
  • Click on 「Send」
Create a new one GET Request page , Fill in the address column

The return response code is 200 Indicates that the request was successful , Back to Body Information is ID by 2312 User information for , Indicates that the global and environment variables are in effect .

4. How to be in Postman Set collection variables

Set variables refer to the variables applied in all requests of the whole set , Set variables take precedence over other variable applications and requests , That is, if there are set variables , Then the other variables conflict with the set variables , Priority is given to the execution of set variables .

Set variables are very suitable for temporarily modifying variables in the whole set , To test the set .

Open your Postman, Let's do it together .

How to be in Postman Set collection variables
  • Select a collection , Click on the right side of the collection title 「...」 Select editor .
  • Enter the set settings page , choice Variables Set collection variables
  • here , All request pages under the whole collection , All have this set variable applied .

Ten . How to use Postman Pre-request scripts Pre request script

Pre-request scripts The pre request script is in API Before executing the script , We can temporarily change some of the requested variables . There are two common application scenarios for pre request scripts .(1) Set dynamic request header information . (2) Set dynamic request parameter information . such as , When we want to request a time related resource , We can add... In the pre request script timestamp Field , This is a dynamic value , We can implement it through pre request script .

Illustrate with examples : For example, we are going to be in header Contains a timestamp , We can do this

  • stay Pre-request scripts Add code to get timestamp
pm.environment.set("TimeStampHeader",new Date());
stay Pre-request scripts Add code to get timestamp
  • stay header Add variables in the pre script TimeStampHeader When requested ,Postman The pre script will be executed first to obtain the timestamp , Then assign the timestamp to header in timestamp In the value .
stay Pre-request scripts Add code to get timestamp
  • Then let's implement this GET request , Open the control console , In the console , You can see Request Headers It contains the timestamp we just set 「timestamp」 hot tip : Explanation of the console , In section 12 of this tutorial .
Open the control console

attach : frequently-used Pre-request scripts :

Get variable

// General grammar 
postman.getGlobalVariable("key");       // Get global variables 
postman.getEnvironmentVariable("key");  // Get environment variables   

//postman native app  Special grammar  
pm.globals.get("key");                // Get global variables 
pm.environment.get("key");            // Get environment variables 

Set a variable

// General grammar 
postman.setGlobalVariable("key","value");       // Set global variables 
postman.setEnvironmentVariable("key","value");  // Set the environment variable   

//postman native app  Special grammar  
pm.globals.get("key","value");                // Set global variables 
pm.environment.get("key","value");            // Set the environment variable 

Clear variables

// General grammar 
postman.clearGlobalVariable("key");       // Clear global variables 
postman.clearEnvironmentVariable("key");  // Clear environment variables   

//postman native app  Special grammar  
pm.globals.unset("key");                // Clear global variables 
pm.environment.unset("key");            // Clear environment variables 

Will array 、 Nested objects are stored in the global & In the environment variables

// Store the array in the environment variable 
var array = [1, 2, 3, 4];
postman.setEnvironmentVariable("array", JSON.stringify(array));

// Store nested objects in environment variables 
var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
postman.setEnvironmentVariable("obj", JSON.stringify(obj));

// Get array object from environment variable 
var array = JSON.parse(postman.getEnvironmentVariable("array"));

// Get nested objects from environment variables /json object 
var obj = JSON.parse(postman.getEnvironmentVariable("obj"));

11、 ... and . How to create Postman Tests The test script - Postman Assertion function

stay Postman in Pre-request and Tests It's two brothers , One is to execute... Before calling (Pre-request), One is to execute after the call (Tests), We can do it in Tests Use in JavaScript The verification code helps us verify the results , so to speak Tests yes Postman The assertion function of

1.Postman Tests Practical application of assertions

  • Postman State class assertion
Postman State class assertion

1. So let's create one first GET request , And then click Postman in Tests label , Enter assertion settings .

2. We can preset the assertion code on the right , Let's first click on 「Status code: Code is 200」, You can see that the preset code is written directly into the edit box . This code means , If the call is executed , The response code returned by the server is 200 when , Judgment for PASS The call is successful .

3. Click on 「Send」 perform GET request , The returned assertion can be in Test Results See results in .

4. Green PASS, The response code returned by the server is 200 , Successful call .

  • Postman Result comparison class assertion

Let's add another one with variables JavaScript Assertion settings , Compare whether the expected result is consistent with the actual returned result .

Postman Result comparison class assertion

We just GET Request the ID 2312 User information for , among name The value of is kalacloud

So let's write a JS Judge whether the expectation is consistent with the returned result . Is expected to be name The value of is 「kalacloud」, Write assertions to automatically determine the return result name Whether the value is also 「kalacloud」

1. stay Tests Select... On the right side of the tab 「Response body:JSON value check」, Let's test ID by 2312 In the return value of ,name Is the value of kalacloud

2. We will 「Your Test Name」 Replace with 「 Check ID by 2312 Of name The return value is kalacloud」 Let the name of this test directly reflect what we want to test .

3. Use jsonData.data[0].name Instead of jsonData.value , That is, the first return value is detected name Of value

4. Detect return value : stay to.eql() Enter the value to be detected in the "kalacloud", That is to say, what needs to be detected text.

5. The code is as follows , You can copy it and simply modify it according to your situation , And then in Postman in , Follow the tutorial to test .

Particular attention : there ID = 2312 It's my situation here , You need to modify it according to your situation .

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

pm.test(" Check  ID  by  2312  Of  name  The return value is  kalacloud", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.data[0].name).to.eql("kalacloud");
});
jsondata.value

Twelve . How to be in Postman Use console in

The console can intuitively display a series of information about the current call , We can do it in 「 menu → view → Show Postman Console」 Or click Postman Lower left corner 「Console」 Icon , Open console .

We can do it in Tests Add... To the test script console.log To display the call information we need to display on the console .

console

Pictured above , We are Test Add the following code to the script

console.log(" This test  id  The value is ",pm.variables.get("kalacloud_id"));

You can display the specific variable value hidden under the variable , It's convenient for us to test , Make appropriate judgments .

13、 ... and . How to use Runner Batch test execution , Batch change variable test

When we have a group API And the interrelated relationship between this group , Using manual testing is very inefficient . At this time , We're going to use Postman Batch execution of (Runner) function ,Runner Not only can it be executed in batch API call , You can also change variables in batches . Master this method , Substantial improvement API Test efficiency .

Open your Postman , Follow this tutorial once .

runner-csv
  • This batch API test , Let's import a CSV file , The file contains four groups of user information waiting to be created , take CSV File import Runner To be used in .
runner-post
  • newly build POST Call page , stay Body Write the information you need to create a user , All values are replaced by variables , These variables will come from CSV Read from .
runner
  • newly build GET Call page , Use email As a query KEY The query , If the previous step POST Successful implementation , that GET You can successfully query the corresponding... Of the new user email, Query indicates POST Create success .
runner tests
  • stay 「 Karayun kalacloud.com Batch test 」 Set... In this collection Tests Set global assertion in , Whenever a call is completed , Conduct Tests A judgment .
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
runner-set
  • open 「 Karayun kalacloud.com Batch test 」 Aggregate 「Run Collection」 Settings page for
  • Iterations: This is the test group , We CSV In file 4 Group test items
  • Delay: Delay , General filling 2000 millisecond , Too intensive requests , Easily rejected by the server
  • Data: Here choose the one we just CSV file :kalacloud_users.csv Import test data
  • Click on RUN The blue button starts the batch test
runner-test

You can see from the above picture that ,Postman Submitted in order POST Request and GET request , And continuously tested from CSV File imported 4 Group data . One click batch test , Quite efficient .

fourteen . Postman Interface test summary

This paper starts from GET / POST Start talking about the function , Then I explained in detail API Several functional features required for interface automation testing , overall situation / Environmental Science / Set variable settings , Test assertion , Test set, etc , And finally automated testing tools Runner. These functions together constitute Postman API Interface automation test function .

原网站

版权声明
本文为[Jiangchuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112311744014757.html