Home > other >  Create a api server with endpoints in Python
Create a api server with endpoints in Python

Time:01-14

using python,need to create api server with two endpoints , with one endpoint /metric and another /healthz

/metric- needs to print the count how many times this api server is called.

/healthz - needs to return ok

CodePudding user response:

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

CodePudding user response:

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. Example below. You can access the interactive API docs at http://127.0.0.1:8000/docs. You can still access your API through http://127.0.0.1:8000/metric, etc.

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("/healthz")
async def healthz():
    return "ok"
    
if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8000, debug=True)
  •  Tags:  
  • Related