generated from nathanwoodburn/python-webserver-template
This commit is contained in:
90
server.py
90
server.py
@@ -23,7 +23,6 @@ HSD_PORT = os.getenv("HSD_PORT", "12037")
|
||||
HSD_API_KEY = os.getenv("HSD_API_KEY", "y5cSK42tgVCdt4E58jkHjI3nQ9GU32bC")
|
||||
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
@@ -42,6 +41,8 @@ def HSD_URL():
|
||||
return f"http://x:{HSD_API_KEY}@{HSD_HOST}:{HSD_PORT}"
|
||||
|
||||
# Assets routes
|
||||
|
||||
|
||||
@app.route("/assets/<path:path>")
|
||||
def send_assets(path):
|
||||
if path.endswith(".json"):
|
||||
@@ -135,6 +136,7 @@ def api_status():
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/chain")
|
||||
def api_chain():
|
||||
"""
|
||||
@@ -153,6 +155,7 @@ def api_chain():
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/mempool")
|
||||
def mempool():
|
||||
"""
|
||||
@@ -169,6 +172,7 @@ def mempool():
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/<datatype>/<blockid>")
|
||||
def api_block_or_header(datatype, blockid):
|
||||
"""
|
||||
@@ -188,6 +192,7 @@ def api_block_or_header(datatype, blockid):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/coin/<coinhash>/<index>")
|
||||
def api_coin(coinhash, index):
|
||||
"""
|
||||
@@ -203,6 +208,7 @@ def api_coin(coinhash, index):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/coin/address/<address>")
|
||||
def api_coin_address(address):
|
||||
"""
|
||||
@@ -218,6 +224,7 @@ def api_coin_address(address):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/tx/<txid>")
|
||||
def api_transaction(txid):
|
||||
"""
|
||||
@@ -233,6 +240,7 @@ def api_transaction(txid):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/tx/address/<address>")
|
||||
def api_transaction_address(address):
|
||||
"""
|
||||
@@ -248,6 +256,7 @@ def api_transaction_address(address):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/name/<name>")
|
||||
def api_name(name):
|
||||
"""
|
||||
@@ -274,6 +283,7 @@ def api_name(name):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/namehash/<namehash>")
|
||||
def api_namehash(namehash):
|
||||
"""
|
||||
@@ -287,19 +297,13 @@ def api_namehash(namehash):
|
||||
}
|
||||
response = requests.post(url, json=data)
|
||||
if response.status_code == 200:
|
||||
# Check if error is null
|
||||
if 'error' in response.json() and response.json()['error'] is not None:
|
||||
return jsonify({"error": response.json()['error']}), 400
|
||||
|
||||
# Check if result is empty
|
||||
if 'result' not in response.json() or not response.json()['result']:
|
||||
return jsonify({"error": "Name not found"}), 404
|
||||
return jsonify(response.json()['result']), 200
|
||||
return jsonify(response.json()), 200
|
||||
else:
|
||||
return jsonify({"error": "Failed to get name data", "status_code": response.status_code}), response.status_code
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/nameresource/<name>")
|
||||
def api_nameresource(name):
|
||||
"""
|
||||
@@ -326,6 +330,7 @@ def api_nameresource(name):
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/namesummary/<name>")
|
||||
def api_namesummary(name):
|
||||
"""
|
||||
@@ -376,19 +381,20 @@ def api_namesummary(name):
|
||||
summary["value"] = summary["value"] / 1000000
|
||||
|
||||
if 'stats' in name_info['info']:
|
||||
summary["blocksUntilExpire"] = name_info['info']['stats'].get('blocksUntilExpire', None)
|
||||
summary["blocksUntilExpire"] = name_info['info']['stats'].get(
|
||||
'blocksUntilExpire', None)
|
||||
|
||||
if 'owner' in name_info['info']:
|
||||
owner_hash = name_info['info']['owner'].get('hash', None)
|
||||
owner_index = name_info['info']['owner'].get('index', None)
|
||||
if owner_hash is not None and owner_index is not None:
|
||||
# Fetch the owner address using the coin endpoint
|
||||
owner_response = requests.get(f"{HSD_URL()}/coin/{owner_hash}/{owner_index}")
|
||||
owner_response = requests.get(
|
||||
f"{HSD_URL()}/coin/{owner_hash}/{owner_index}")
|
||||
if owner_response.status_code == 200:
|
||||
owner_data = owner_response.json()
|
||||
summary["owner"] = owner_data.get('address', None)
|
||||
|
||||
|
||||
# Get resources
|
||||
data = {
|
||||
"method": "getnameresource",
|
||||
@@ -412,10 +418,10 @@ def api_namesummary(name):
|
||||
|
||||
return jsonify(summary), 200
|
||||
|
||||
|
||||
except requests.RequestException as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/v1/help")
|
||||
def api_help():
|
||||
"""
|
||||
@@ -425,20 +431,30 @@ def api_help():
|
||||
{"endpoint": "/api/v1/status", "description": "Check HSD node status"},
|
||||
{"endpoint": "/api/v1/chain", "description": "Get chain status"},
|
||||
{"endpoint": "/api/v1/mempool", "description": "Get mempool status"},
|
||||
{"endpoint": "/api/v1/block/<blockid>", "description": "Get block data by block height or hash"},
|
||||
{"endpoint": "/api/v1/header/<blockid>", "description": "Get header data by block height or hash"},
|
||||
{"endpoint": "/api/v1/coin/<coinhash>/<index>", "description": "Get coin info"},
|
||||
{"endpoint": "/api/v1/coin/address/<address>", "description": "Get coins for address"},
|
||||
{"endpoint": "/api/v1/block/<blockid>",
|
||||
"description": "Get block data by block height or hash"},
|
||||
{"endpoint": "/api/v1/header/<blockid>",
|
||||
"description": "Get header data by block height or hash"},
|
||||
{"endpoint": "/api/v1/coin/<coinhash>/<index>",
|
||||
"description": "Get coin info"},
|
||||
{"endpoint": "/api/v1/coin/address/<address>",
|
||||
"description": "Get coins for address"},
|
||||
{"endpoint": "/api/v1/tx/<txid>", "description": "Get transaction info"},
|
||||
{"endpoint": "/api/v1/tx/address/<address>", "description": "Get transactions for address"},
|
||||
{"endpoint": "/api/v1/tx/address/<address>",
|
||||
"description": "Get transactions for address"},
|
||||
{"endpoint": "/api/v1/name/<name>", "description": "Get name info"},
|
||||
{"endpoint": "/api/v1/namehash/<namehash>", "description": "Get name by hash"},
|
||||
{"endpoint": "/api/v1/nameresource/<name>", "description": "Get name resource"},
|
||||
{"endpoint": "/api/v1/namehash/<namehash>",
|
||||
"description": "Get name by hash"},
|
||||
{"endpoint": "/api/v1/nameresource/<name>",
|
||||
"description": "Get name resource"},
|
||||
{"endpoint": "/api/v1/namesummary/<name>",
|
||||
"description": "Get a summary of a name"},
|
||||
{"endpoint": "/api/v1/help", "description": "List all API endpoints"},
|
||||
{"endpoint": "/api/v1/namesummary/<name>", "description": "Get a summary of a name"},
|
||||
|
||||
]
|
||||
return jsonify({"api": api_endpoints}), 200
|
||||
|
||||
|
||||
@app.route("/api/v1")
|
||||
@app.route("/api/v1/")
|
||||
@app.route("/api/v1/<catch_all>")
|
||||
@@ -451,6 +467,37 @@ def api_index(catch_all=None):
|
||||
# endregion
|
||||
|
||||
|
||||
# region Demo routes
|
||||
|
||||
demo_data = {
|
||||
"status": "/api/v1/status",
|
||||
"chain": "/api/v1/chain",
|
||||
"mempool": "/api/v1/mempool",
|
||||
"block": "/api/v1/block/210241",
|
||||
"header": "/api/v1/header/210241",
|
||||
"coin": "/api/v1/coin/e6fc6b6759761cfa310c8260de11aacd88481795b4794e1231b0434825763ec8/10",
|
||||
"coin/address": "/api/v1/coin/address/hs1qz3fnjn70fs7rdxt57fhrl4yzsqngg55sqyz83a",
|
||||
"tx": "/api/v1/tx/e6fc6b6759761cfa310c8260de11aacd88481795b4794e1231b0434825763ec8",
|
||||
"tx/address": "/api/v1/tx/address/hs1qz3fnjn70fs7rdxt57fhrl4yzsqngg55sqyz83a",
|
||||
"name": "/api/v1/name/woodburn",
|
||||
"namehash": "/api/v1/namehash/368d90d6a3cf9fa3a588d0e4c15d2d265896d2c0bf514644f2e9c86df2f00350",
|
||||
"nameresource": "/api/v1/nameresource/woodburn",
|
||||
"namesummary": "/api/v1/namesummary/woodburn",
|
||||
"help": "/api/v1/help"
|
||||
}
|
||||
|
||||
|
||||
@app.route("/demo/v1/<path:api_name>")
|
||||
def demo(api_name):
|
||||
demo_url = demo_data.get(api_name, None)
|
||||
if not demo_url:
|
||||
return render_template("404.html"), 404
|
||||
return render_template("demo.html", url=demo_url)
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
# region Error Catching
|
||||
# 404 catch all
|
||||
@app.errorhandler(404)
|
||||
@@ -468,5 +515,6 @@ def add_cors_headers(response):
|
||||
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
|
||||
return response
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000, host="127.0.0.1")
|
||||
|
||||
105
templates/demo.html
Normal file
105
templates/demo.html
Normal file
@@ -0,0 +1,105 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Fire HSD | Nathan.Woodburn</title>
|
||||
<link rel="icon" href="/assets/img/favicon.png" type="image/png">
|
||||
<link rel="stylesheet" href="/assets/css/index.css">
|
||||
<link rel="stylesheet" href="/assets/css/bootstrap.min.css">
|
||||
<style>
|
||||
/* Extra styling for index page */
|
||||
.intro {
|
||||
max-width: 600px;
|
||||
margin: 0 auto 2em auto;
|
||||
padding: 1.5em;
|
||||
background: rgba(40, 40, 40, 0.5);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
|
||||
font-size: 1.15em;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.api-table-container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
footer {
|
||||
margin-top: 4em;
|
||||
text-align: center;
|
||||
color: #aaa;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
margin-bottom: 1em;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body class="bg-dark text-light">
|
||||
<div class="centre" style="margin-top: 2em;">
|
||||
<img src="/assets/img/favicon.png" alt="Fire HSD Logo" class="logo">
|
||||
<h1>Fire HSD</h1>
|
||||
<span style="font-size:1.2em; color:#f0f0f0;">A free public API for Handshake (HSD)</span>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="demo-endpoint">
|
||||
<!-- Card with demo URL and example output -->
|
||||
<h2 style="text-align: center;">Example API request</h2>
|
||||
<div class="card text-bg-secondary mb-3" style="width: fit-content; max-width: 90%; margin: 0 auto;">
|
||||
<div class="card-header">{{url}}</div>
|
||||
<div class="card-body">
|
||||
<pre class="card-text" id="output"></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Fetch the demo URL and display it
|
||||
fetch('{{url}}')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching demo URL:', error);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div style="text-align: center; margin-top: 2em;">
|
||||
|
||||
<h1>Support Fire HSD</h1>
|
||||
If you'd like to help keep the service running and growing,
|
||||
consider
|
||||
donating:<br />
|
||||
<div class="btn-group-vertical btn-group-sm gap-1" role="group"><a class="btn btn-primary" role="button"
|
||||
target="_blank" href="https://paypal.me/nathanwoodburn">PayPal</a><a class="btn btn-primary"
|
||||
role="button" target="_blank" href="https://donate.stripe.com/8wM6pv0VD08Xe408ww">Card (via
|
||||
Stripe)</a><a class="btn btn-primary" role="button" target="_blank"
|
||||
href="https://nathan.woodburn.au/donate?c=hns">HNS</a><a class="btn btn-primary" role="button"
|
||||
target="_blank" href="https://nathan.woodburn.au/donate?c=btc">BTC</a><a class="btn btn-primary"
|
||||
role="button" target="_blank" href="https://nathan.woodburn.au/donate">Other Donation Options</a></div>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<footer>
|
||||
© 2025 <a href="https://nathan.woodburn.au" style="color: #aaa;" target="_blank">Nathan.Woodburn/</a>
|
||||
— <a href="https://git.woodburn.au/nathanwoodburn/firehsd" style="color:#aaa;" target="_blank">Source</a>
|
||||
</footer>
|
||||
<script>
|
||||
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -84,6 +84,11 @@
|
||||
— <a href="https://git.woodburn.au/nathanwoodburn/firehsd" style="color:#aaa;" target="_blank">Source</a>
|
||||
</footer>
|
||||
<script>
|
||||
function getDemoUrl(endpoint) {
|
||||
// Remove trailing placeholders like <name>, <blockid>, <txid>, etc.
|
||||
return endpoint.replace(/\/<[^>]+>/g, '').replace("api","demo")
|
||||
}
|
||||
|
||||
function renderApiEndpoints(apiList) {
|
||||
const container = document.getElementById('api-endpoints');
|
||||
// Create table element
|
||||
@@ -103,8 +108,14 @@
|
||||
thDescription.style.padding = '8px';
|
||||
thDescription.style.borderBottom = '1px solid #ccc';
|
||||
thDescription.textContent = 'Description';
|
||||
const thEndpointDemo = document.createElement('th');
|
||||
thEndpointDemo.style.padding = '8px';
|
||||
thEndpointDemo.style.borderBottom = '1px solid #ccc';
|
||||
thEndpointDemo.textContent = 'Example Usage';
|
||||
|
||||
headerRow.appendChild(thEndpoint);
|
||||
headerRow.appendChild(thDescription);
|
||||
headerRow.appendChild(thEndpointDemo);
|
||||
thead.appendChild(headerRow);
|
||||
table.appendChild(thead);
|
||||
|
||||
@@ -124,8 +135,20 @@
|
||||
tdDescription.style.borderBottom = '1px solid #eee';
|
||||
tdDescription.textContent = api.description;
|
||||
|
||||
const tdEndpointDemo = document.createElement('td');
|
||||
tdEndpointDemo.style.padding = '8px';
|
||||
tdEndpointDemo.style.borderBottom = '1px solid #eee';
|
||||
const demoLink = document.createElement('a');
|
||||
demoLink.href = getDemoUrl(api.endpoint);
|
||||
demoLink.textContent = 'Try it';
|
||||
demoLink.target = '_blank';
|
||||
demoLink.classList.add('btn', 'btn-secondary', 'btn-sm');
|
||||
tdEndpointDemo.appendChild(demoLink);
|
||||
|
||||
row.appendChild(tdEndpoint);
|
||||
row.appendChild(tdDescription);
|
||||
row.appendChild(tdEndpointDemo);
|
||||
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
table.appendChild(tbody);
|
||||
|
||||
Reference in New Issue
Block a user