快速搭建python HTTP Server测试环境
这里用python http.server搭建一个api测试环境,自定义请求处理程序,以模拟不同api相应。
1 服务代码
/api/data,端口8000,GET
返回json数据为"{"message": "This is a sample API response"}"
代码示例如下,保存为server.py。
import http.server
import socketserver
import jsonPORT = 8000class APIRequestHandler(http.server.SimpleHTTPRequestHandler):def do_GET(self):if self.path == '/api/data':data = {'message': 'This is a sample API response'}self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()self.wfile.write(json.dumps(data).encode('utf-8'))else:self.send_response(404)with socketserver.TCPServer(("", PORT), APIRequestHandler) as httpd:print(f"Serving at port {PORT}")httpd.serve_forever()
2 运行测试
1)运行服务
启动python服务
python server.py
2)测试服务
发送请求
curl 'http://localhost:8000/api/data'
服务返回
{"message": "This is a sample API response"}
reference
---
Python Simple HTTP Server:轻松搭建HTTP服务
https://bettercoding404.github.io/python-simple-http-server/