Using Python, I would like to create an API server with the following endpoints:
/metric
- needs to return the number of times the API server has been called
/health
- needs to return ok
Since you don't specify any framework ou give any initial code, here's a simple example using Flask on how it would be:
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()
To install Flask, run:
pip3 install flask
Run the python code and access on your browser http://127.0.0.1:5000/metric
and http://127.0.0.1:5000/healthz
FastAPI is a great option. FastAPI is a "fast (high-performance), web framework for building APIs". It provides interactive API documentation (provided by Swagger UI) to visualize and interact with the API’s resources.
You can access the interactive API autodocs at http://127.0.0.1:8000/docs. You can also access the API endpoints directly from the browser at, for instance, 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)