DEV Community

ANKUSH CHOUDHARY JOHAL
ANKUSH CHOUDHARY JOHAL

Posted on • Originally published at johal.in

AI-Powered API Documentation: Generate Docs With LangChain 0.3, Swagger 4.0, and Claude 3.5

AI-Powered API Documentation: Generate Docs With LangChain 0.3, Swagger 4.0, and Claude 3.5

Manual API documentation is a persistent pain point for development teams: it’s time-consuming, error-prone, and often falls out of sync with live API changes. Traditional workflows require engineers to manually update Swagger/OpenAPI specs, cross-reference endpoint logic, and validate schema accuracy—tasks that eat into core development time.

This guide walks through building an AI-powered documentation pipeline using LangChain 0.3 (orchestration), Swagger 4.0 (spec standard), and Claude 3.5 Sonnet (content generation) to automate accurate, up-to-date API docs with minimal manual overhead.

Prerequisites

  • Python 3.9+ or Node.js 18+ (we’ll use Python for this walkthrough)
  • Anthropic API key for Claude 3.5 access
  • LangChain 0.3.0+ installed: pip install langchain langchain-anthropic
  • Sample API to document (we’ll use a minimal FastAPI app for demonstration)
  • Basic familiarity with OpenAPI/Swagger 4.0 spec structure

How the Pipeline Works

The pipeline uses three core components working in tandem:

  • LangChain 0.3: Handles prompt engineering, LLM chaining, and output parsing to structure Claude’s responses into valid Swagger 4.0 specs.
  • Claude 3.5 Sonnet: Analyzes API endpoint logic, infers request/response schemas, and generates human-readable documentation copy.
  • Swagger 4.0: Provides the standardized spec format and UI rendering for the final documentation output.

Step 1: Set Up a Sample API

First, create a minimal FastAPI app with two endpoints to document. Install FastAPI and Uvicorn:

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

Create a file sample_api.py with the following code:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Sample E-Commerce API")

class OrderCreate(BaseModel):
    product_id: str
    quantity: int
    shipping_address: str

@app.post("/orders", tags=["Orders"])
async def create_order(order: OrderCreate):
    """Create a new order for a product"""
    return {"order_id": "ord_123", "status": "pending", **order.dict()}

@app.get("/orders/{order_id}", tags=["Orders"])
async def get_order(order_id: str):
    """Retrieve details for an existing order"""
    return {"order_id": order_id, "product_id": "prod_456", "quantity": 2, "status": "shipped"}

Enter fullscreen mode Exit fullscreen mode

Run the app with uvicorn sample_api:app --reload to confirm it works. By default, FastAPI generates basic Swagger 2.0 docs at /docs—we’ll replace this with AI-generated Swagger 4.0 docs.

Step 2: Configure LangChain 0.3 with Claude 3.5

Set your Anthropic API key as an environment variable:

export ANTHROPIC_API_KEY="your-api-key-here"
Enter fullscreen mode Exit fullscreen mode

Create a new file doc_generator.py and initialize the LangChain components:

from langchain_anthropic import ChatAnthropic
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
import json

# Initialize Claude 3.5 Sonnet via LangChain
llm = ChatAnthropic(
    model="claude-3-5-sonnet-20241022",
    temperature=0.1,  # Low temperature for deterministic spec generation
    max_tokens=4096
)

# Define the prompt template for Swagger 4.0 spec generation
prompt = ChatPromptTemplate.from_messages([
    ("system", """You are an API documentation expert. Generate a valid Swagger 4.0 (OpenAPI 4.0) compliant JSON spec for the provided API endpoint details. 
    Follow these rules:
    1. Use Swagger 4.0 schema (openapi: "4.0.0")
    2. Include info, servers, paths, components, and security sections as needed
    3. Infer request/response schemas from endpoint logic
    4. Write clear, concise summaries and descriptions for all endpoints
    5. Return ONLY valid JSON, no markdown or extra text"""),
    ("user", "{endpoint_details}")
])

# Create the LangChain chain
doc_chain = LLMChain(llm=llm, prompt=prompt)

Enter fullscreen mode Exit fullscreen mode

Step 3: Generate Swagger 4.0 Specs with AI

Pass your API endpoint details to the chain to generate a Swagger 4.0 spec. For the sample FastAPI app above, we’ll pass the endpoint logic and metadata:

endpoint_details = """
API Name: Sample E-Commerce API
Base URL: http://localhost:8000
Endpoints:
1. POST /orders
   - Request Body: OrderCreate model with product_id (string), quantity (integer), shipping_address (string)
   - Response: 200 OK with order_id (string), status (string), product_id, quantity, shipping_address
   - Summary: Create a new order for a product
   - Tags: Orders
2. GET /orders/{order_id}
   - Path Parameter: order_id (string)
   - Response: 200 OK with order_id, product_id, quantity, status
   - Summary: Retrieve details for an existing order
   - Tags: Orders
"""

# Generate the Swagger spec
swagger_spec = doc_chain.run(endpoint_details=endpoint_details)

# Parse and validate the output
try:
    spec_json = json.loads(swagger_spec)
    with open("swagger_4_spec.json", "w") as f:
        json.dump(spec_json, f, indent=2)
    print("Swagger 4.0 spec generated successfully!")
except json.JSONDecodeError:
    print("Error: Generated spec is not valid JSON. Retrying...")
    # Add retry logic here for production use

Enter fullscreen mode Exit fullscreen mode

Claude 3.5 will infer any missing schema details, generate consistent descriptions, and output a fully compliant Swagger 4.0 JSON file. LangChain 0.3 handles prompt formatting and output parsing to ensure the result matches the required structure.

Step 4: Render Documentation with Swagger 4.0 UI

To render the generated spec, use the Swagger UI 4.0 package. For Python, use fastapi with a custom Swagger UI setup, or use the Node.js swagger-ui-express package:

# Python FastAPI custom Swagger UI setup
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
import json

app = FastAPI()

# Load generated Swagger 4.0 spec
with open("swagger_4_spec.json") as f:
    swagger_spec = json.load(f)

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui():
    return get_swagger_ui_html(
        openapi_url="/openapi.json",
        title="AI-Generated API Docs",
        swagger_ui_version="4.0.0"
    )

@app.get("/openapi.json", include_in_schema=False)
async def get_openapi_spec():
    return swagger_spec

Enter fullscreen mode Exit fullscreen mode

Navigate to http://localhost:8000/docs to see your AI-generated Swagger 4.0 documentation, complete with accurate schemas, descriptions, and endpoint details.

Best Practices for Production Use

  • Add validation for generated specs using the openapi-spec-validator library to catch errors before deployment.
  • Use LangChain’s output parsers (e.g., JsonOutputParser) to enforce strict JSON structure instead of manual parsing.
  • Cache generated specs for unchanged endpoints to reduce API costs and latency.
  • Include example requests/responses in prompts to improve Claude’s output accuracy.
  • Set up CI/CD pipelines to regenerate docs automatically when API code changes.

Conclusion

Combining LangChain 0.3’s orchestration, Claude 3.5’s content generation, and Swagger 4.0’s standardized spec format eliminates the manual toil of API documentation. This pipeline produces accurate, up-to-date docs that stay in sync with your API, freeing engineers to focus on building features instead of writing docs.

Top comments (0)