用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参数化
相关推荐
微笑星河q7 分钟前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
QuZhengRong30 分钟前
【AI】Agent 全栈进阶|AgentScope 沙箱源码解析
python·学习·ai·agent·沙箱
Eider19981 小时前
Python基础语法之并发相关3
开发语言·python
FRing031 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
CS_Zero2 小时前
DeepSeek V4.1 Flash 1017 (Batch) 新手极速上手指南
开发语言·batch·deepseek
山楂树の2 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
Risehuxyc2 小时前
C# 发展历史
开发语言·c#
M--Y2 小时前
LangGraph 架构基石:持久化与运行控制
python·langchain·大模型·llm·持久化·langgraph
用户019027581613 小时前
新浪财经 / 东方财富股票接口不稳、被限?稳定替代方案
python
七夜zippoe3 小时前
Nexent 知识库:调优靠 Chunk 与重排
开发语言·python·ai智能体·nexent·知识库与rag