使用Flask和JavaScript可快速构建网页API。1. 用Flask创建返回JSON的后端接口;2. 编写HTML页面通过fetch调用API实现交互;3. 安装flask-cors解决跨域问题;4. 部署时统一接口前缀、关闭debug并考虑Token验证,完成从开发到上线全流程。

想用Python做网页版API接口,其实并不复杂。你只需要一个轻量的Web框架,比如Flask或FastAPI,再配合前端页面就能实现前后端交互。下面一步步带你从创建API到前端调用,完整走通整个流程。
Flask是Python中最常用的微型Web框架,适合快速开发API。先安装Flask:
pip install flask然后创建一个简单的API服务,例如返回JSON数据:
app.py
立即学习“Python免费学习笔记(深入)”;
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/hello', methods=['GET'])
def hello():
return jsonify({"message": "Hello from Python API!"})
@app.route('/api/submit', methods=['POST'])
def submit():
data = request.get_json()
name = data.get('name')
return jsonify({"response": f"Hi {name}, your data was received!"})
if __name__ == '__main__':
app.run(debug=True)
运行这个脚本后,你的API就在 http://localhost:5000/api/hello 可访问了。
接下来写一个简单的HTML页面,通过JavaScript调用上面的API。
index.html
<!DOCTYPE html>
<html>
<head>
<title>调用Python API</title>
</head>
<body>
<h2>测试API调用</h2>
<button onclick="getHello()">获取问候消息</button>
<br><br>
<input type="text" id="nameInput" placeholder="输入你的名字">
<button onclick="submitData()">提交数据</button>
<p id="result"></p>
<script>
function getHello() {
fetch('http://localhost:5000/api/hello')
.then(response => response.json())
.then(data => {
document.getElementById("result").innerText = data.message;
});
}
function submitData() {
const name = document.getElementById("nameInput").value;
fetch('http://localhost:5000/api/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name })
})
.then(response => response.json())
.then(data => {
document.getElementById("result").innerText = data.response;
});
}
</script>
</body>
</html>
把这个HTML文件放在本地打开,确保Python服务正在运行,就能实现数据交互。
如果前端和Python后端不在同一个域名或端口下,浏览器会阻止请求,出现“CORS”错误。解决方法是启用跨域支持。
安装Flask-CORS扩展:
pip install flask-cors在代码中启用:
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # 允许所有域名访问
这样前端就可以顺利调用API了。
本地测试完成后,你可以将API部署到云服务器或使用平台如Render、Railway、Vercel(配合WSGI)来上线你的Python API。
一些实用建议:
基本上就这些。用Python做网页API,核心就是“后端提供接口 + 前端发起请求”。只要掌握Flask基础和fetch调用,就能快速构建自己的Web服务。不复杂但容易忽略细节,比如CORS和数据格式处理。动手试一次,很快就能上手。
以上就是Python网页版怎样做API接口_Python网页版API接口开发与调用教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号