python接口测试实例
时间: 2025-02-25 09:32:06 浏览: 30
### Python API 测试示例
对于API测试而言,`requests`库是一个非常流行的工具,可以方便地发送HTTP请求并处理响应。下面展示了一个基本的例子来说明如何利用Python进行API测试。
#### 安装依赖包
首先需要安装`requests`库:
```bash
pip install requests
```
#### 发送GET请求
这里有一个简单的例子用于向指定URL发起GET请求,并打印服务器返回的状态码以及JSON格式的数据。
```python
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
print(f"Status Code: {response.status_code}")
if response.ok:
json_data = response.json()
print(json_data)
else:
print("Failed to retrieve data.")
```
#### POST请求提交表单数据
当涉及到创建资源时,则可能需要用到POST方法。此段代码展示了怎样构建一个包含新帖子信息的有效载荷(payload),并通过POST方式将其上传至目标地址。
```python
new_post = {
'title': 'foo',
'body': 'bar',
'userId': 1,
}
url = "https://jsonplaceholder.typicode.com/posts/"
response = requests.post(url, json=new_post)
print(f"Response Status Code: {response.status_code}")
if response.ok:
created_resource_id = response.json().get('id')
print(f"Created resource ID: {created_resource_id}")
else:
print("Failed to create new post.")
```
#### 使用单元测试框架unittest编写自动化测试案例
为了使API测试更加结构化和易于维护,通常会结合像`unittest`这样的标准库来进行断言验证和其他逻辑操作。
```python
import unittest
from requests import get
class TestJsonPlaceholderApi(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.base_url = "https://jsonplaceholder.typicode.com"
def test_get_single_post(self):
url = f"{self.base_url}/posts/1"
resp = get(url)
self.assertEqual(resp.status_code, 200, msg="Unexpected status code!")
self.assertIn('title', resp.json(), msg="'title' field missing from JSON!")
if __name__ == '__main__':
unittest.main()
```
以上就是一些关于Python中执行API测试的基础介绍[^1]。
阅读全文
相关推荐









