'How to create a API server with endpoints in Python?

Using python, I would like to create API server with two endpoints , namely /metric and /healthz.

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

/healthz - needs to return ok



Solution 1:[1]

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leonardo Lima
Solution 2