用python写一个api接口
时间: 2024-06-09 12:11:19 浏览: 9
好的,以下是一个简单的 Python Flask 框架搭建的API接口示例:
首先,安装 Flask 模块:
```
pip install flask
```
然后,编写 Python 代码:
```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello_world():
return 'Hello, World!'
@app.route('/add', methods=['POST'])
def add_numbers():
num1 = request.form['num1']
num2 = request.form['num2']
result = int(num1) + int(num2)
return str(result)
if __name__ == '__main__':
app.run(debug=True)
```
这个 API 接口有两个路由:`/hello` 和 `/add`。
`/hello` 是一个 GET 请求,返回字符串 "Hello, World!"。
`/add` 是一个 POST 请求,接收两个数字参数 num1 和 num2,将它们相加并返回结果。
最后,运行 Python 文件,API 接口就可以通过访问 `http://localhost:5000` 进行测试。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)