python请求接口_python处理http接口请求

一、安装 requests和jsonpath 模块

安装命令:pip install requests

pip install jsonpath

二、requests 处理常见的接口请求参数类型

1、表单类型的参数:

1)请求参数类型:content-type: application/x-www-form-urlencoded*

2)requests 发送请求,传递表单参数,应该使用 data 去传递

importrequestsfrom jsonpath importjsonpath

url= 'https://***.******.com/v3.3/uaa/login'params={"username": "131********","password": "************"}

headers={"x-app-id": "******"}

res= requests.request('post', url, data=params, headers=headers).json()#使用jsonpath获取登录接口返回的token值,后边请求接口的headers中需要用到

token = jsonpath(res, '$..token')[0]

2、JSON 类型的参数:

1)请求类型为 Content-Type:Application/json

2)requests 发送请求,传递 JSON 参数,就应该使用 JSON 去传递

importrequestsfrom jsonpath importjsonpath

url= 'https://***.******/getExamList'params={"pageNum": 1,"pageSize": 20}

headers={"x-app-id": "******",#依赖登录接口返回的token值

"x-auth-token": token

}

res= requests.request('post', url, json=params, headers=headers)print(res.json())

3、查询字符串参数:

1)常用于 get 请求(其他的请求方法用的少)

2)参数会直接拼接在 url 地址后面

3)requests 发送请求,传递查询字符串参数,要使用 params

url = 'https://***.******/findAll'params={"pageNum": 1,"pageSize": 9999}

headers={"x-app-id": "******",#依赖登录接口返回的token值

"x-auth-token": token

}

res= requests.request('get', url, params=params, headers=headers)print(res.json())

4、文件上传

1)请求参数类型:content-type:application/form-data(postman 请求参数也选择这个)

2)文件参数要使用 files 进行传递

3)文件参数的组装:两种形式****

{"参数名":("文件名",open 以 rb 模式打开文件,"文件类型")}

{("参数名",("文件名",open 以 rb 模式打开文件,"文件类型"))}

importrequests

url= 'http://127.0.0.1:5000/upload'

#请求参数

params ={"nickname":'奔奔',

}

file={'pic':('test.gif',open('test.gif','rb'),'image/gif')

}

response= requests.post(url=url, data=params, files =file)print(response.json())

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值