如何在Python中创建带有端点的API服务器?

问题描述 投票:0回答:2

使用Python,我想创建一个具有以下端点的API服务器:

/metric
- 需要返回API服务器被调用的次数

/health
- 需要返回
ok

python api rest
2个回答
1
投票

由于您没有指定任何框架或给出任何初始代码,因此这里有一个使用 Flask 的简单示例来说明它的情况:

from flask import Flask

app = Flask(__name__)
count = 0

@app.route('/metric')
def metric():
    global count
    count += 1
    return str(count)

@app.route('/healthz')
def health():
    return "ok"

app.run()

要安装 Flask,请运行:

pip3 install flask

运行Python代码并在浏览器上访问

http://127.0.0.1:5000/metric
http://127.0.0.1:5000/healthz


0
投票

FastAPI是一个不错的选择。 FastAPI 是“用于构建 API 的快速(高性能)Web 框架”。它提供了交互式 API 文档(由 Swagger UI 提供)来可视化 API 的资源并与之交互。

工作示例

您可以在 http://127.0.0.1:8000/docs 访问交互式 API 自动文档。您还可以直接从浏览器访问 API 端点,例如,http://127.0.0.1:8000/metric

import uvicorn
from fastapi import FastAPI

app = FastAPI()
hits = 0

@app.get("/metric")
async def metric():
    global hits
    hits+=1
    return {"hits": hits}

@app.get("/health")
async def health():
    return "ok"
    
if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)
© www.soinside.com 2019 - 2024. All rights reserved.