当编写接口自动化脚本时,我们可以使用Python中的requests库来发送HTTP请求并处理响应。下面是一个简单的例子,用于向某个API发送GET请求并打印响应内容:
```python
import requests
# 发送GET请求
response = requests.get('http://api.example.com/users')
# 打印响应内容
print(response.json())
```
如果需要向API发送POST请求,可以使用`requests.post`方法,并传递请求体数据作为参数。以下是一个发送POST请求的示例:
```python
import requests
# 请求体数据
data = {
'username': 'testuser',
'password': 'testpass'
}
# 发送POST请求
response = requests.post('http://api.example.com/login', data=data)
# 打印响应内容
print(response.json())
```
除了使用requests库发送请求外,还可以使用其他第三方库来处理请求和响应。例如,可以使用unittest库编写测试用例并执行接口测试。以下是一个使用unittest库的示例,用于测试某个API的返回状态码是否为200:
```python
import re