Implement interface test with python (1. Use POST and GET request api)

Keywords: Python encoding

As we all know, there are many ways to use Python for interface testing, such as POST, GET and other methods to request API parameters.

Next is User collection information api of Douban books To learn the two libraries of Python 3 + urllib to implement api request instances under POST and GET, attach code comments:

I. interface related information. As follows:

Picture from Jianshu 1

2. We can change the name to the user name of Abbey, the boss of Douban, namely https://api.doublan.com/v2/book/user/abbei/collections to see what books Abbey likes to read

1. Request api with post method

#coding:utf-8

#auther:xiaozhong

#Data:2017-11-12 15:30

""""use post Method request api: It is safe to pass parameters in the request content in this way"""

importurllib.request,urllib# Import these two libraries

url ='https://API. Doublan. COM / V2 / book / user / ahbei / collections' -- this is the url to request

data={'status':'read','rating':4,'tag':'Novel'}# According to the parameters provided in the api document, let's get the three-star Books marked with "novel" in the books Abei read, and store these parameter values in a dict

#data = urllib.parse.urlencode(data) # Code parameters

data = urllib.parse.urlencode(data).encode(encoding='UTF8')

url2 = urllib.request.Request(url,data)# Use. Request to send the POST request, indicating that the request target is the previously defined url, and the request content is placed in the data

response = urllib.request.urlopen(url2)# Open the result returned in the previous step with. urlopen to get the response content after the request

apicontent = response.read()#Read out the response content with read()

print('use post Method request api')

print(apicontent)#Print what you read

2. Request api with get method

#coding:utf-8

#auther:xiaozhong

#Data:2017-11-12 15:30

""""use get Method request api: In this way, the parameters are placed directly in the url in"""

url ='https://api.douban.com/v2/book/user/ahbei/collections'

data = {'status':'read','rating':3,'tag':'Novel'}

data = urllib.parse.urlencode(data)

url = url +'?'+ data

""""Follow post The only difference is this sentence?hold url and data The content of,

The result is https://api.douban.com/v2/book/user/ahbei/collecti

ons?status=read&rating=3&tag=%E5%B0%8F%E8%AF%B4"""

response = urllib.request.urlopen(url2)# Open the result returned in the previous step with. urlopen to get the response content after the request

apicontent = response.read()#Read out the response content with read()

print('use get Method request api')

print(apicontent)#Print what you read

III. operation result analysis

As can be seen from the figure below, the request results of POST and GET are consistent

Picture from Jianshu 2

Posted by xpressmail on Tue, 10 Dec 2019 15:56:47 -0800