DEV Community

Suave Bajaj
Suave Bajaj

Posted on

πŸš€ My First Flask API – Lightweight Monitoring Data Server (with Deep Dive)

Hey folks! πŸ‘‹

I recently built my first API using Flask and wanted to share the experience β€” not just the code, but also how it works, what each part does, and how you can run it yourself. If you're learning Flask or curious about simple data-serving APIs, this might help!


🧠 What This API Does

This Flask API serves precomputed monitoring data for various backend services (like Kafka, RabbitMQ, etc.) using .json files. Here's what it can do:

βœ… 1. Returns JSON Files Containing Health Data

  • Data for each service is stored as JSON files in a structured directory.
  • You can query the API with parameters like stackname, service, and time to get specific metrics.
  • Example:

/getdata?stackname=retail&service=kafka&time=20240708

This returns the contents of:

/data-files/retail/kafka_20240708.json

βœ… 2. Compares Two Time Periods for the Same Service

  • You can compare a service's performance between two timestamps:

/getdata/comparison?stackname=retail&service=kafka&start_time=20240701&end_time=20240707

This returns:

/data-files/retail/comparisons/kafka_20240701_vs_20240707.json

Useful for catching trends, regressions, or improvements.


βœ… 3. Displays a Landing Page with All Available Endpoints

  • Visit the root / to get a helpful summary:
{ "message": "πŸ‘‹ Welcome to the API!", "available_endpoints": { "/getdata/comparison": "GET with params: stackname, service, start_time, end_time", "/getdata": "GET with params: stackname, service, time" }, "available_services": [ "elasticsearch", "rabbitmq", "pods", "responsetime", "logsearch", "kafka", "database", "asciapp", "consul" ], "status": "running" } 
Enter fullscreen mode Exit fullscreen mode

πŸ” Code Walkthrough

app.py

from flask import Flask from datahandler import DataHandler handler = DataHandler() app = Flask(__name__) app.add_url_rule('/getdata/comparison', 'getcomparisondata', handler.get_comparison_data) app.add_url_rule('/getdata', 'stackdata', handler.get_stack_data) app.add_url_rule('/', 'landingpage', handler.get_landing_page) if __name__ == '__main__': app.run(debug=True, port=8080) 
Enter fullscreen mode Exit fullscreen mode

datahandler.py

from flask import request, send_file, abort, Response, json import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) files_file_path = os.path.abspath(os.path.join(BASE_DIR, "..", "data-files")) config_path = os.path.abspath(os.path.join(BASE_DIR, "..", "config", "data_config.json")) with open(config_path) as f: config = json.load(f) class DataHandler: valid_data_paths = config.get("valid_data_paths", []) def get_comparison_data(self): stackname = request.args.get('stackname') service = request.args.get('service') start_time = request.args.get('start_time') end_time = request.args.get('end_time') file_name = f"{stackname}_{service}_{start_time}_vs_{end_time}.json" path = os.path.join(files_file_path, stackname, "comparisons", file_name) return send_file(path, mimetype='application/json') def get_stack_data(self): stackname = request.args.get('stackname') service = request.args.get('service') time = request.args.get('time') if service in self.valid_data_paths: file_name = f"{stackname}_{service}_{time}.json" path = os.path.join(files_file_path, stackname, file_name) return send_file(path, mimetype='application/json') return abort(400, description="Invalid data type") def get_landing_page(self): data = { "message": "Welcome to the API!", "available_endpoints": { "/getdata/comparison": "GET with params: stackname, service, start_time, end_time", "/getdata": "GET with params: stackname, service, time" }, "available_services": self.valid_data_paths, "status": "running" } return Response(json.dumps(data, indent=2), mimetype='application/json') 
Enter fullscreen mode Exit fullscreen mode

▢️ How to Run It

Install Flask:

pip install flask 
Enter fullscreen mode Exit fullscreen mode

Run the python code

python app.py 
Enter fullscreen mode Exit fullscreen mode

Open your browser and visit or use the POSTMAN tool to get the details

http://localhost:8080/ 
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ What Does Each Line in app.run() Do?

app.run(debug=True, port=8080) 
Enter fullscreen mode Exit fullscreen mode
Argument What It Does
debug=True Auto-reloads the app on code changes and shows detailed error messages. Great for dev, not for prod.
port=8080 Runs the app on port 8080 instead of the default 5000.
host='0.0.0.0' (optional) Allows access from any IP address (e.g., Docker or public cloud).
app.run(host='0.0.0.0', port=8080, debug=True) 
Enter fullscreen mode Exit fullscreen mode

πŸ”— Query Parameters in Flask

You pass arguments like this:

/getdata?stackname=prod&service=pods&time=0708 
Enter fullscreen mode Exit fullscreen mode

And extract them in code:

request.args.get('stackname') request.args.get('service') request.args.get('time') 
Enter fullscreen mode Exit fullscreen mode

You can also give default values:

request.args.get('service', 'default_service') 
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ Lessons I Learned

  • How to use Flask routing and send_file() for static JSON
  • The importance of modular design (datahandler.py)
  • Building an API without needing a full DB
  • Making endpoints self-documenting for easy testing and consumption

Top comments (0)