Swagger and API Monitoring
Last Updated :
29 Jan, 2024
API monitoring is like having a watchful guardian for your digital communication paths, playing a big role in making software work well. It keeps an eye on how things are going, manages mistakes, makes sure everything responds quickly, checks everything in real-time, makes the user experience better, and fixes problems before they become big issues.
In the world of making software today, both Swagger (now called the OpenAPI Specification) and API monitoring are really important. Swagger helps make a plan for how to build APIs, making it easier to create them and check how well they work. API monitoring keeps an eye on APIs all the time, making sure they keep working well. Together, these tools help a lot in creating, explaining, testing, and making sure APIs work great in the digital world.
What is API Monitoring?
API Monitoring is like a watchman for your digital stuff. It checks how everything is doing in real time, making sure it works well and responds fast. It keeps an eye on things like how often there are mistakes and if everything is working smoothly. By catching problems early, it helps fix things before you even notice, making sure your digital experience is good and the software works well.
Swagger and API Monitoring
Below, we will understand how the Swagger and API Monitoring work step-by-step with one example by creating Public API and Private API and how we manage it.
Step 1: Create a Virtual Environment
First, create the virtual environment using the below commands
python -m venv env .\env\Scripts\activate.ps1
Step 2: Install Necessary Library
To set up the required dependencies, begin by installing Flask, Flasgger, and Prometheus_client using the following commands:
pip install flask
pip install flasgger
pip install prometheus_client
Step 3: Import the Necessary Library
Using the below command import the Necessary Library
Python3
from flask import Flask, jsonify, request
from flasgger import Swagger
from prometheus_client import Counter, generate_latest, REGISTRY, start_http_server
Step 4: Create the Prometheus metrics
Prometheus metrics are a standardized method to measure and monitor software system performance. In API monitoring, they enable real-time tracking, helping proactively resolve issues and ensuring optimal API health for a reliable user experience.
In below code we defines a Prometheus metrics endpoint in a Flask app at the '/metrics' route. When accessed, it returns Prometheus metrics data using the `generate_latest` function from the provided `REGISTRY`. The endpoint is documented using Swagger/OpenAPI. We can see the Prometheus metrics by below accessing below url
http://127.0.0.1:8000/metrics
Python3
# Prometheus metrics endpoint
@app.route('/metrics', methods=['GET'])
def metrics():
"""
Prometheus Metrics Endpoint
---
responses:
200:
description: Prometheus metrics data
"""
return generate_latest(REGISTRY)
Step 3: Create Public API
Below , code defines a Flask endpoint at '/public' with a Swagger documentation comment. When accessed via a GET request, the endpoint increments a 'http_requests_total' counter (assumed to be defined elsewhere) and responds with a JSON object containing a 'data' field with the string value 'This is a public endpoint'.
Python3
# Public endpoint
@app.route('/public', methods=['GET'])
def public_endpoint():
"""
Public Endpoint
---
responses:
200:
description: A public endpoint response
content:
application/json:
schema:
type: object
properties:
data:
type: string
"""
requests_counter.inc() # Increment the requests counter
return jsonify({'data': 'This is a public endpoint'})
Output :

Step 4: Create Private API
Below, code defines a Flask endpoint at '/private' with Swagger documentation. When accessed via a GET request, it increments a 'http_requests_total' counter (assumed to be defined elsewhere). The endpoint expects an 'apikey' parameter in the query, and it responds with a JSON object containing a 'data' field if the provided API key is 'abc'. If the API key is invalid, it returns a JSON object with an 'error' field .
Python3
# Private endpoint
@app.route('/private', methods=['GET'])
def private_endpoint():
"""
Private Endpoint
---
parameters:
- in: query
name: apikey
type: string
required: true
description: API Key for authentication
responses:
200:
description: A private endpoint response
content:
application/json:
schema:
type: object
properties:
data:
type: string
401:
description: Unauthorized access
content:
application/json:
schema:
type: object
properties:
error:
type: string
"""
requests_counter.inc() # Increment the requests counter
api_key = request.args.get('apikey')
# You can check the API key here before granting access
if api_key != 'abc':
return jsonify({'error': 'Invalid API key'}), 401
return jsonify({'data': 'This is a private endpoint'})
Output :

Complete Code
Below, code sets up a Flask app with Swagger documentation, Prometheus metrics, and two endpoints. The '/public' endpoint responds to any request, incrementing a request counter. The '/private' endpoint requires an API key as a query parameter, and only allows access if the key is 'abc'. Prometheus metrics, including an 'http_requests_total' counter, are exposed at the '/metrics' endpoint. The app runs on port 5000, and a Prometheus HTTP server is started on port 8000 for monitoring.
Python3
from flask import Flask, jsonify, request
from flasgger import Swagger
from prometheus_client import Counter, generate_latest, REGISTRY, start_http_server
app = Flask(__name__)
swagger = Swagger(app)
# Prometheus metrics
requests_counter = Counter('http_requests_total', 'Total HTTP requests')
# Prometheus metrics endpoint
@app.route('/metrics', methods=['GET'])
def metrics():
"""
Prometheus Metrics Endpoint
---
responses:
200:
description: Prometheus metrics data
"""
return generate_latest(REGISTRY)
# Public endpoint
@app.route('/public', methods=['GET'])
def public_endpoint():
"""
Public Endpoint
---
responses:
200:
description: A public endpoint response
content:
application/json:
schema:
type: object
properties:
data:
type: string
"""
requests_counter.inc() # Increment the requests counter
return jsonify({'data': 'This is a public endpoint'})
# Private endpoint
@app.route('/private', methods=['GET'])
def private_endpoint():
"""
Private Endpoint
---
parameters:
- in: query
name: apikey
type: string
required: true
description: API Key for authentication
responses:
200:
description: A private endpoint response
content:
application/json:
schema:
type: object
properties:
data:
type: string
401:
description: Unauthorized access
content:
application/json:
schema:
type: object
properties:
error:
type: string
"""
requests_counter.inc() # Increment the requests counter
api_key = request.args.get('apikey')
# You can check the API key here before granting access
if api_key != 'abc':
return jsonify({'error': 'Invalid API key'}), 401
return jsonify({'data': 'This is a private endpoint'})
if __name__ == '__main__':
# Start Prometheus HTTP server on port 8000
start_http_server(8000)
# Run Flask app on port 5000
app.run(debug=True, port=5000)
Run the Server
Using the below command we can run the server and Access the Swagger documentation
python app.py
http://127.0.0.1:5000/apidocs
Output
Conclusion
In conclusion, integrating Swagger with Flask and adding monitoring metrics to API development is crucial for optimal performance. This combination streamlines API design and testing, while tools like Prometheus offer real-time insights. Following the provided steps and code allows firsthand experience in creating a robust and well-monitored API. The demo video aids implementation, ensuring efficiency and reliability in digital communication through Swagger, API monitoring, and best practices.
Similar Reads
What is API Monitoring in Postman ?
API Monitoring is a process that monitors the activity, output, and performance of an API based on Environment, Time, regions, etc. API monitoring plays a significant role in identifying and addressing issues related to API functionality and security before they impact partners or end-users of that
6 min read
Health Endpoint Monitoring Pattern
The Health Endpoint Monitoring Pattern is a software design pattern that has been designed to ensure the continual running of an application. By providing a known path with a .health, .status, or .ping suffix an application allows other systems or monitoring tools to make a request to that path to e
7 min read
Swagger and API Lifecycle Management
In today's world of software development and integration, Application Programming Interfaces (APIs) play a crucial role in enabling communication and data exchange between different systems. However, creating an API involves multiple steps, and effective management throughout its lifecycle is vital
5 min read
What is an API Endpoint ?
The API endpoint is the specific URL where requests are sent to interact with the API. In this article, we will discuss API Endpoint their working and the differences between REST API and GraphQL endpoints. Table of Content What is an API Endpoint?How do API endpoints work?What are some best practic
7 min read
Monitoring and Logging in MERN Stack
Monitoring and logging are crucial for maintaining the health and performance of applications. In the MERN (MongoDB, Express.js, React, Node.js) stack, these practices help in identifying issues, ensuring application stability, and providing insights into user interactions. This article will guide y
5 min read
Advanced Swagger Features
In this article, we'll explore advanced features of Swagger, which is known as the OpenAPI Specification, which has become pivotal in modern API development. Offering a standardized approach to describe, document, and consume RESTful web services, Swagger goes beyond basic functionality. We'll highl
5 min read
What is Prometheus Monitoring ?
In a dynamic era of international reality, important to maintain the capacity and effectiveness of systems. an increasing number of teams rely on robust and distributed architectures, the need for effective tracking solutions has once again to be discussed. Prometheus, an open supply chain monitorin
6 min read
Documenting RESTful APIs with Swagger
RESTful APIs play an important role in communicating between various software components. The interface used to consume APIs significantly impacts the chances of achieving business and technological objectives. In this article, we'll dive into the importance of RESTful API documentation and how Swag
8 min read
Setting Example and Description with Swagger
Swagger is an open-source tool used to document RESTful APIs. It provides a user-friendly interface for developers to understand and interact with APIs, making it easier to design, build, and manage them. Swagger can also generate client SDKs and API documentation in various formats.Swagger is a com
11 min read
Python Swagger Annotations for API Documentation
Your API documentation and specification capabilities can be substantially improved by using Python's FastAPI with Swagger annotations. This comprehensive tutorial covers all the bases, from introduction to execution.In the context of Python, Swagger annotations are often used in combination with fr
4 min read