用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参数化
相关推荐
Python私教21 小时前
Django 接入 AI 大模型实战:从零做一个流式聊天网站
人工智能·python·django
Python私教21 小时前
Django 接入 MCP 实战:让 AI 安全调用数据库和业务接口
人工智能·python·django
Python私教21 小时前
Django 搭建 AI 本地知识库:文档上传、向量检索与智能问答
人工智能·python·django
luj_176821 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
always_TT21 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
xcLeigh1 天前
Go入门:变量声明的五种方式详解
java·开发语言·golang
zmzb01031 天前
C++课后习题训练记录Day175
开发语言·c++
脱胎换骨-军哥1 天前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
枕星而眠1 天前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
lipku1 天前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播