API接口测试--python实现请求
前面章节讲解到工具postman测试接口,发送请求;本节讲解如何使用python语言发送请求。
一、python发送get请求
安装requests库,pip install request
发送get请求,使用requests里面的get方法。以查询天气为例
url = "http://apis.juhe.cn/simpleWeather/query"
data = {
"key":"c904a499ae9bcda8d4c8383d0c516fa1",
"city":"深圳"
}
header={
"content-type":"application/json"
}
r = requests.get(url,params=data,headers =header)
print(r.text)
get的第一个参数为url,即请求的接口地址;第二个参数为请求数据,如果没有请求数据可以不写,同理headers也是,这个是请求头部,没有也可以不写。
r.text是返回响应的内容,如果需要返回状态码 ,使用 r.status_code
二、python发送post请求
使用python发送post请求,可以使用requests里面的post方法.
1.提交的数据类型为:application/json
import json
import requests
url = "http://localhost:8088/login"
headers = {
"content-type":"application/json"
}
data = {
"user":"admin",
"password":"123456"
}
r = requests.post(url,headers=headers,json=data)
#或者
r = requests.post(url,headers=headers,data=json.dumps(data))
2.提交的数据类型为 application/x-www-form-urlencoded
import requests
url = "http://localhost:8088/login"
headers = {
"content-type":"application/x-www-form-urlencoded"
}
data = {
"user":"admin",
"password":"123456"
}
r = requests.post(url,headers=headers,data=data)
3.提交的数据类型为 multipart/form-data
此数据类型一般用于文件的上传
import requests
url = "http://localhost:8088/post"
files = {'file': open('/home/test.jpg', 'rb')}
r = requests.post(url,headers=headers,files=files)

浙公网安备 33010602011771号