Skip to content

Instantly share code, notes, and snippets.

@pmuston
Last active March 7, 2017 13:16
Show Gist options
  • Save pmuston/d86a0577d6b3cf03d2d433596e48c6f5 to your computer and use it in GitHub Desktop.
Save pmuston/d86a0577d6b3cf03d2d433596e48c6f5 to your computer and use it in GitHub Desktop.
Fake API in Python with Flask

Concept

Quickly create a fake API for testing client with Python and Flask.

Inspired by https://github.com/gchaincl/httplab seemed a bit heavyweight for my needs.

You can create responses in httplab.json file. "Responses" maps path to status, headers, body (content) returned (text or json). You can specify a delay for realisim.

{
"Headers": {
"Server": "PyHttpLab"
},
"Delay": 500,
"Responses": {
"": {
"Status": 200,
"Delay": 0,
"Body": "home"
},
"ok": {
"Status": 200,
"Delay": 0,
"Body": "Hello, World",
"Headers": {
"X-Server": "HTTPLab"
}
},
"item/32": {
"Status": 200,
"Delay": 0,
"Body": {
"item": 32,
"title": "item_32"
}
},
"create": {
"Status": 201,
"Delay": 1000,
"Body": {
"created": "ok"
},
"Headers": {
"Content-Type": "application/json"
}
},
"notfound": {
"Status": 404,
"Delay": 0,
"Body": "Page Not Found",
"Headers": {}
}
}
}
# inspired by https://github.com/gchaincl/httplab
import time
from flask import Flask, json, jsonify, request, make_response
app = Flask(__name__)
with open("httplab.json") as f:
config = json.load(f)
indent = config["Indent"] if "Indent" in config else 2
common_headers = config["Headers"] if "Headers" in config else {}
site_delay = config["Delay"] if "Delay" in config else 0
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
if path in config['Responses']:
response = config['Responses'][path]
else:
response = {
"Status": 404,
"Body": "Page {} Not Found".format(path)
}
status = response["Status"] if "Status" in response else 200
body = response["Body"] if "Body" in response else {}
page_headers = response["Headers"] if "Headers" in response else {}
delay = response["Delay"] if "Delay" in response else site_delay
if delay > 0:
delay_secs = delay/1000.0
print("delay {} seconds", delay_secs)
time.sleep(delay_secs)
if isinstance(body, dict):
resp = make_response(json.dumps(response["Body"], indent=indent), status)
resp.headers['Content-Type'] = 'application/json; charset=utf-8'
resp.headers['mimetype'] = 'application/json'
elif isinstance(body, str):
resp = make_response(response["Body"], status)
else:
resp = make_response("None", status)
for key, val in common_headers.items():
resp.headers[key] = val
for key, val in page_headers.items():
resp.headers[key] = val
return resp
if __name__ == "__main__":
app.run(port=10080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment