This document outlines the comprehensive architecture plan for the "API Documentation Generator," a system designed to automate and streamline the creation of professional, detailed, and interactive API documentation. This plan focuses on core components, data flow, key features, technology considerations, and operational aspects to ensure a robust, scalable, and user-friendly solution.
The primary objective of the API Documentation Generator is to transform various API definition sources (e.g., OpenAPI specifications, code annotations) into high-quality, consumable documentation. This includes detailed endpoint descriptions, request/response examples, authentication guides, and SDK usage examples, presented in multiple formats.
Key Objectives:
The API Documentation Generator will be built upon a modular architecture, enabling flexibility, scalability, and maintainability.
This layer is responsible for ingesting API definitions from various sources.
Once input is received, this engine processes and validates its structure.
A standardized, technology-agnostic internal data model representing the API.
This layer allows for adding supplementary content and customizing the documentation beyond what's available in the raw API definition.
* Extended descriptions for APIs, endpoints, parameters.
* Detailed tutorials and guides.
* Manual request/response examples.
* SDK usage examples (if not auto-generated).
* Glossaries, FAQs, and other supporting documentation.
Responsible for transforming the enriched IR into renderable content using predefined or custom templates.
Generates the final documentation in various formats and manages its persistence.
The primary interface for users to interact with the generator.
Manages secure access to the generator and its functionalities.
graph TD
A[API Definition Sources] --> B(Input & Source Integration Layer)
B --> C(Parsing & Validation Engine)
C --> D(Intermediate Representation - IR)
D -- User Input/Customization --> E(Enrichment & Customization Layer)
E --> F(Template Engine & Renderer)
F --> G(Output Formatter & Storage Layer)
G --> H[Published Documentation]
I[User Interface / API] -- Manage APIs, Templates, Trigger Generation --> A
I -- Manage Custom Content --> E
I -- Access Generated Docs --> H
Explanation:
The generator will support a comprehensive set of features:
This section outlines a recommended technology stack, chosen for its robustness, scalability, and developer ecosystem.
Rationale:* Mature ecosystems for web services, data processing, and integration with various tools. Python is strong for data parsing and scripting, Node.js for high-concurrency I/O operations.
* Python: pyyaml, jsonschema, openapi-spec-validator
* Node.js
As part of the "API Documentation Generator" workflow, we are now executing the generate_code step. This deliverable provides a comprehensive, detailed, and production-ready Python-based API documentation generator. It takes an OpenAPI Specification as input and produces well-structured, professional HTML documentation, including endpoint descriptions, request/response examples, authentication guides, and API call snippets.
This document outlines and provides the code for a robust API documentation generator. This tool is designed to automate the process of creating high-quality, interactive API documentation from a standard OpenAPI Specification (OAS).
The goal of this generator is to transform a machine-readable OpenAPI Specification into human-readable, professional HTML documentation. It focuses on clarity, completeness, and ease of navigation, ensuring that developers can quickly understand and integrate with your API.
The generator follows a standard pipeline:
Key Architectural Components:
main.py: The entry point and orchestrator, handling command-line arguments, loading the spec, and coordinating the parsing and rendering.api_parser.py: Responsible for loading and normalizing the OpenAPI specification, extracting key information like endpoints, schemas, and security schemes.doc_renderer.py: Manages the Jinja2 environment, loads templates, and renders the processed API data into HTML files.code_examples.py: Generates generic API call examples (e.g., cURL, Python requests, JavaScript fetch) based on endpoint definitions.templates/: A directory containing Jinja2 template files (.html) that define the structure and presentation of the documentation.static/: (Conceptual) A directory for static assets like CSS, JavaScript, and images, which would be copied to the output directory.
api-doc-generator/
├── src/
│ ├── api_parser.py
│ ├── code_examples.py
│ ├── config.py
│ ├── doc_renderer.py
│ ├── main.py
│ └── templates/
│ ├── base.html
│ ├── index.html
│ ├── endpoint.html
│ ├── schema.html
│ └── components/
│ ├── _header.html
│ ├── _sidebar.html
│ ├── _footer.html
│ ├── _method_card.html
│ └── _schema_details.html
├── static/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── main.js
├── example_api_spec.yaml
├── requirements.txt
└── README.md
requirements.txt
PyYAML>=6.0
Jinja2>=3.1.2
To install the dependencies:
pip install -r requirements.txt
src/config.pyThis file holds configuration constants for the generator.
# src/config.py
import os
# Base directory for the project
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Path to the templates directory
TEMPLATES_DIR = os.path.join(BASE_DIR, 'src', 'templates')
# Path to the static assets directory
STATIC_DIR = os.path.join(BASE_DIR, 'static')
# Default output directory for generated documentation
DEFAULT_OUTPUT_DIR = os.path.join(BASE_DIR, 'docs')
# Default OpenAPI spec file name
DEFAULT_SPEC_FILE = 'example_api_spec.yaml'
# Default title for the documentation
DEFAULT_DOC_TITLE = "API Documentation"
src/api_parser.pyHandles the loading and parsing of the OpenAPI specification. It extracts and structures the data needed for templating.
# src/api_parser.py
import yaml
import json
import os
from collections import defaultdict
class OpenAPIParser:
"""
Parses an OpenAPI Specification file (YAML or JSON) and extracts relevant
information for documentation generation.
"""
def __init__(self, spec_path):
if not os.path.exists(spec_path):
raise FileNotFoundError(f"OpenAPI spec file not found: {spec_path}")
self.spec_path = spec_path
self.spec = self._load_spec()
self.api_data = {} # Stores processed API data
def _load_spec(self):
"""Loads the OpenAPI spec from the given path."""
with open(self.spec_path, 'r', encoding='utf-8') as f:
if self.spec_path.endswith(('.yaml', '.yml')):
return yaml.safe_load(f)
elif self.spec_path.endswith('.json'):
return json.load(f)
else:
raise ValueError("Unsupported spec file format. Must be .yaml, .yml, or .json")
def _resolve_ref(self,
Welcome to the official documentation for the PantheraHive Product Catalog API. This API allows you to programmatically manage your product catalog, including retrieving product information, adding new products, updating existing ones, and deleting products.
This document provides detailed information on available endpoints, authentication methods, request/response structures, and examples to help you integrate seamlessly with our services.
The PantheraHive Product Catalog API provides a robust and flexible interface for managing your product data. It is designed for developers who need to integrate product information into their applications, e-commerce platforms, or internal systems.
Key Features:
All API requests should be made to the following base URL:
https://api.pantherahive.com/v1
The PantheraHive Product Catalog API uses API Key authentication. To authenticate your requests, you must include your unique API Key in the X-API-Key header for every request.
How to obtain your API Key:
Example Request Header:
X-API-Key: YOUR_API_KEY_HERE
Content-Type: application/json
Important:
This section details all available API endpoints, their methods, parameters, and example requests/responses.
Retrieve a paginated list of all products in the catalog.
/productsGETQuery Parameters:
| Parameter | Type | Required | Description | Example |
| :-------- | :------ | :------- | :---------------------------------------------- | :------------- |
| limit | Integer | No | Maximum number of products to return (default: 10, max: 100) | ?limit=20 |
| offset | Integer | No | Number of products to skip (for pagination) | ?offset=10 |
| category| String | No | Filter products by category | ?category=electronics |
| min_price| Decimal | No | Filter products by minimum price | ?min_price=50.00 |
| max_price| Decimal | No | Filter products by maximum price | ?max_price=200.00|
Example Request (cURL):
curl -X GET \
'https://api.pantherahive.com/v1/products?limit=5&category=electronics' \
-H 'X-API-Key: YOUR_API_KEY_HERE'
Example Response (200 OK):
{
"data": [
{
"id": "prod_001",
"name": "Panthera Smartwatch X1",
"description": "Next-generation smartwatch with health tracking.",
"category": "electronics",
"price": 299.99,
"currency": "USD",
"stock": 150,
"sku": "PH-SMART-X1",
"created_at": "2023-10-26T10:00:00Z",
"updated_at": "2023-10-26T10:00:00Z"
},
{
"id": "prod_002",
"name": "Panthera Wireless Earbuds Pro",
"description": "Premium noise-cancelling earbuds.",
"category": "electronics",
"price": 149.99,
"currency": "USD",
"stock": 300,
"sku": "PH-EARBUDS-PRO",
"created_at": "2023-10-25T14:30:00Z",
"updated_at": "2023-10-25T14:30:00Z"
}
],
"meta": {
"total": 25,
"limit": 5,
"offset": 0,
"next_offset": 5
}
}
Retrieve detailed information for a specific product using its unique ID.
/products/{product_id}GETPath Parameters:
| Parameter | Type | Required | Description | Example |
| :----------- | :----- | :------- | :-------------------------- | :------------- |
| product_id | String | Yes | The unique ID of the product | prod_001 |
Example Request (cURL):
curl -X GET \
'https://api.pantherahive.com/v1/products/prod_001' \
-H 'X-API-Key: YOUR_API_KEY_HERE'
Example Response (200 OK):
{
"id": "prod_001",
"name": "Panthera Smartwatch X1",
"description": "Next-generation smartwatch with health tracking.",
"category": "electronics",
"price": 299.99,
"currency": "USD",
"stock": 150,
"sku": "PH-SMART-X1",
"created_at": "2023-10-26T10:00:00Z",
"updated_at": "2023-10-26T10:00:00Z"
}
Example Response (404 Not Found):
{
"error": {
"code": "PRODUCT_NOT_FOUND",
"message": "Product with ID 'non_existent_id' not found."
}
}
Add a new product to the catalog.
/productsPOSTRequest Body (application/json):
| Parameter | Type | Required | Description | Example |
| :--------- | :------ | :------- | :--------------------------------------------- | :---------------- |
| name | String | Yes | Name of the product | "Panthera Laptop Pro" |
| description| String | Yes | Detailed description of the product | "High-performance laptop for professionals." |
| category | String | Yes | Product category (e.g., "electronics", "books") | "electronics" |
| price | Decimal | Yes | Price of the product | 1299.99 |
| currency | String | Yes | Currency code (e.g., "USD", "EUR") | "USD" |
| stock | Integer | Yes | Current stock quantity | 50 |
| sku | String | No | Stock Keeping Unit (unique identifier) | "PH-LAPTOP-PRO" |
| image_url| String | No | URL to the product image | "https://example.com/laptop.jpg" |
Example Request (cURL):
curl -X POST \
'https://api.pantherahive.com/v1/products' \
-H 'X-API-Key: YOUR_API_KEY_HERE' \
-H 'Content-Type: application/json' \
-d '{
"name": "Panthera Laptop Pro",
"description": "High-performance laptop for professionals.",
"category": "electronics",
"price": 1299.99,
"currency": "USD",
"stock": 50,
"sku": "PH-LAPTOP-PRO",
"image_url": "https://example.com/laptop_pro.jpg"
}'
Example Response (201 Created):
{
"id": "prod_003",
"name": "Panthera Laptop Pro",
"description": "High-performance laptop for professionals.",
"category": "electronics",
"price": 1299.99,
"currency": "USD",
"stock": 50,
"sku": "PH-LAPTOP-PRO",
"image_url": "https://example.com/laptop_pro.jpg",
"created_at": "2023-11-01T09:15:00Z",
"updated_at": "2023-11-01T09:15:00Z"
}
Example Response (400 Bad Request - Missing Field):
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid request body.",
"details": [
{
"field": "name",
"message": "Product name is required."
}
]
}
}
Update specific fields of an existing product.
/products/{product_id}PUT (for full replacement) or PATCH (for partial update)Path Parameters:
| Parameter | Type | Required | Description | Example |
| :----------- | :----- | :------- | :-------------------------- | :------------- |
| product_id | String | Yes | The unique ID of the product | prod_001 |
Request Body (application/json) - for PATCH (partial update):
| Parameter | Type | Required | Description | Example |
| :--------- | :------ | :------- | :--------------------------------------------- | :---------------- |
| name | String | No | New name of the product | "Panthera Smartwatch X2" |
| description| String | No | Updated description | "Advanced smartwatch with improved battery." |
| price | Decimal | No | New price of the product | 319.99 |
| stock | Integer | No | New stock quantity | 120 |
Example Request (cURL - PATCH):
curl -X PATCH \
'https://api.pantherahive.com/v1/products/prod_001' \
-H 'X-API-Key: YOUR_API_KEY_HERE' \
-H 'Content-Type: application/json' \
-d '{
"name": "Panthera Smartwatch X2",
"price": 319.99,
"stock": 120
}'
Example Response (200 OK):
{
"id": "prod_001",
"name": "Panthera Smartwatch X2",
"description": "Next-generation smartwatch with health tracking.",
"category": "electronics",
"price": 319.99,
"currency": "USD",
"stock": 120,
"sku": "PH-SMART-X1",
"created_at": "2023-10-26T10:00:00Z",
"updated_at": "2023-11-01T11:00:00Z"
}
Remove a product from the catalog.
/products/{product_id}DELETEPath Parameters:
| Parameter | Type | Required | Description | Example |
| :----------- | :----- | :------- | :-------------------------- | :------------- |
| product_id | String | Yes | The unique ID of the product | prod_002 |
Example Request (cURL):
curl -X DELETE \
'https://api.pantherahive.com/v1/products/prod_002' \
-H 'X-API-Key: YOUR_API_KEY_HERE'
Example Response (204 No Content):
A successful deletion will return an empty response body with a 204 No Content status code.
Example Response (404 Not Found):
{
"error": {
"code": "PRODUCT_NOT_FOUND",
"message": "Product with ID 'non_existent_id' not found."
}
}
The PantheraHive Product Catalog API uses standard HTTP status codes to indicate the success or failure of an API request. In case of an error, a JSON response body will provide more details.
| HTTP Status Code | Description | Error Code (JSON) |
| :--------------- | :----------------------------------- | :-------------------- |
| 200 OK | The request was successful. | |
| 201 Created |
\n