Build a Simple Flask Mock Server to Simulate APIs Quickly
Learn how to set up a local Flask-based mock server that handles GET and POST requests, returns customizable JSON or text responses, supports configurable URL paths, simulates network latency, and can be tested via browser, curl, Postman, or Python scripts.
Function Goals
Start a local HTTP service
Support GET and POST requests
Customizable response content (JSON or text)
Configurable URL paths and response data
Support delayed responses to simulate network latency
Install Flask
pip install flaskExample: Simple Mock Server (mock_server.py)
from flask import Flask, request, jsonify
import time
app = Flask(__name__)
# Mock data
MOCK_DATA = {
"/api/login": {
"success": True,
"message": "登录成功",
"data": {"token": "abc123xyz"}
},
"/api/user/profile": {
"id": 1,
"name": "张三",
"email": "[email protected]"
},
"/api/users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
DELAY = 0.5 # seconds
@app.before_request
def before_request():
"""Log each request"""
print(f"[请求] {request.method} {request.path}")
@app.after_request
def after_request(response):
"""Add artificial delay after each response"""
time.sleep(DELAY)
return response
@app.route('/', methods=["GET", "POST"])
def mock_api(endpoint):
"""General mock endpoint"""
full_path = f"/{endpoint}"
if full_path in MOCK_DATA:
return jsonify(MOCK_DATA[full_path])
else:
return jsonify({"error": "接口未定义", "path": full_path}), 404
if __name__ == "__main__":
print("Mock Server 正在运行,监听地址: http://localhost:5000")
app.run(host="0.0.0.0", port=5000, debug=True)Example explanation:
How to Test This Mock Server?
Method 1: Browser – Open http://localhost:5000/api/login in a browser.
Method 2: Postman or curl – Run curl -X GET http://localhost:5000/api/users.
Method 3: Python requests script – Use the following script:
import requests
url = "http://localhost:5000/api/login"
response = requests.get(url)
print("状态码:", response.status_code)
print("响应内容:", response.json())Advanced: Load MOCK Data from File
import json
import os
MOCK_FILE = "mock_data.json"
if os.path.exists(MOCK_FILE):
with open(MOCK_FILE, "r", encoding="utf-8") as f:
MOCK_DATA = json.load(f)
else:
MOCK_DATA = {}Example mock_data.json content:
{
"/api/login": {
"success": true,
"token": "abc123xyz"
},
"/api/logout": {
"message": "登出成功"
}
}How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
