端午节我写了一个项目,帮助你学习HTTP接口测试。
GitHub地址:
https://github.com/defnngj/learning-API-test
整个项目基于Flask和 Requests实现。
Flask是Python主流的Web框架,以简单著称,它可非常方便的实现API,整个项目中的API都通过一个文件实现。
Requests是模拟HTTP的测试库,同样是Python语言的明星库,它可以以非常简单的方式模拟HTTP请求。
如何开始学习
克隆或下载项目,安装依赖。
$ pip install -r requirements.txt |
启动Flask项目。
$ python api_server.py * Serving Flask app "api_server.py" (lazy loading) * Environment:production WARNING: Do not use thedevelopment server in a production environment. Use a production WSGI serverinstead. * Debug mode: on * Running onhttp://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting withstat * Debugger isactive! * Debugger PIN:208-740-173 |
接下来,你可根据项目文档中所提供的Requests例子,调用启动的服务所提供的接口。
最简单的接口调用。
import requests r = requests.get("http://127.0.0.1:5000/") result = r.json() print(result) |
接口的返回结果。
{"code": 10200, "message": "Welcome toAPI testing"} |
如果,你想知道上面调用的接口是如何实现的,可以查看api_server.py文件。
# 最简单的json格式返回 @app.route('/') def hello_world(): return jsonify({ "code": 10200, "message": "Welcome to API testing" }) |
Flask 实现接口是不是很简单?当然,还有更多复杂的接口实现,不过,这里的所有接口实现忽略了数据库的操作。
如果本项目对你帮助,请帮忙加 star,有什么问题也可以通过issues提问。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理