用python实现postman

一、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参数化
相关推荐
2601_9659584616 分钟前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
AI_小站39 分钟前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
微小冷1 小时前
在不同空间中展示数据(欧式、球面、庞加莱圆盘)
python·双曲空间·微分几何·geomstats·庞加莱圆盘·球面
felixking1 小时前
C++20 协程
开发语言·c++·协程
weixin_431600442 小时前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
讲温控就好了2 小时前
从医疗影像到能源存储——芯片冷却温控技术的跨行业赋能
人工智能·python·能源
DeepVisionary2 小时前
从 Qwen3.8-27B 把原生多模态、原生 FP8、桌面级 Agent 三件事一次集齐,看开源大模型的“工业化拐点“
python·自动化
Zane1994123 小时前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言
固定资产管理系统软件3 小时前
商务局RFID固定资产管理系统的应用价值与落地要点解析
大数据·python
码农颜4 小时前
6.3 主函数流程剖析
开发语言·php