一、GET请求
python
# get
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)
print(response.json())
运行结果:
二、POST请求
python
#post
response = requests.post('https://jsonplaceholder.typicode.com/posts', json={
"title": "测试标题",
"body": "测试内容",
"userId": 1
},headers={'Content-Type': 'application/json'})
print(response.status_code)
print(response.json())
运行结果:

三、写断言,模拟一个测试用例
python
#写一个测试用例
def test_get():
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
assert response.status_code == 200,f"状态码错误,状态码为{response.status_code}"
assert 'title' in response.json() ,f"返回数据中没有title标题"
print('test_get测试通过')
test_get()
运行结果:

四、用Session保持登录状态
注意: 有些接口需要先登录才能操作。Requests用Session对象保存Cookie,和浏览器自动记cookie一样
python
session = requests.Session()
# 先登录(假设有这个登录接口)
login_response = session.post(
"https://example.com/api/login",
json={"username": "admin", "password": "123456"}
)
# 再用同一个session去访问需要权限的接口
profile_response = session.get("https://example.com/api/profile")
五、Postman的对比
| Postman做的事 | Requests代码怎么实现 |
|---|---|
| 选GET/POST/PUT/DELETE | requests.get() / .post() / .put() / .delete() |
| 填URL | url="https://..." |
| 填Headers | headers={"Content-Type": "application/json"} |
| 选Body → raw → JSON | json={"key": "value"} |
| 看状态码 | response.status_code |
| 看返回Body | response.json() 或 response.text |
| Tests写断言 | Python的assert语句 |
| Collection Runner批量跑 | 用for循环,或后面学Pytest参数化 |