0

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

Chris
  • 18,724
  • 6
  • 46
  • 80
pulli
  • 11
  • 1

2 Answers2

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

Leonardo Lima
  • 373
  • 2
  • 10
  • thank you....I am new to building endpoints on python. this makes me understand the whole scenario. – pulli Jan 14 '22 at 15:03
0

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.

Working Example

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)
Chris
  • 18,724
  • 6
  • 46
  • 80
  • Thank you Chris.. I see you used uvicorn to import fastapi...also I noticed you used async , Just a ques, so if we dont use async you think the code will work? – pulli Jan 14 '22 at 15:12
  • Yes, it would work. In brief, when you declare an endpoint with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server). Please have a look at [this answer](https://stackoverflow.com/a/71517830/17865804) for more details on `def` vs `async def`. – Chris Oct 07 '22 at 10:24