CompactSchema: Complete AI-Ready Documentation for Swift APIs
In the age of AI-driven development, one of the biggest challenges is efficiently communicating your code structure to language models. Traditional API documentation is verbose and token-heavy, eating up valuable context window space. Enter CompactSchema - a comprehensive suite of Swift macros that generates token-optimized documentation for both your data structures and API methods.
The Problem
When working with AI tools like ChatGPT or Claude, you need to describe both your data structures and API methods. Traditional documentation is incredibly verbose:
/// A user profile containing authentication and preference data
public struct UserProfile: Codable, Sendable {
/// The user's unique username
public let username: String
/// Optional email address for the user
public let email: String?
/// Whether the user's email has been verified
public let isVerified: Bool
/// User-specific preferences as key-value pairs
public let preferences: [String: Any]
}
This verbose documentation consumes ~500 tokens just to describe a simple 4-field struct. And that’s before you even start documenting your API methods:
/// Fetches the user profile from the server
/// - Parameters:
/// - userId: The unique identifier of the user
/// - Returns: The user's profile data
/// - Throws: NetworkError if the request fails
public func getUserProfile(_ userId: String) async throws -> UserProfile {
// Implementation
}
Another ~200 tokens for a single method. When you’re working with complex APIs that have dozens of types and methods, you quickly hit context limits.
The Solution: A Complete Documentation Suite
CompactSchema provides a comprehensive set of macros that transform your entire API into minimal, AI-friendly documentation.
Data Structure Documentation
@CompactSchema
struct UserProfile: Codable {
let username: String
let email: String?
let isVerified: Bool
let preferences: [String: Any]
}
// Automatically generates:
// UserProfile { username: String, email: String?, isVerified: Bool, preferences: [String: Any] }
This compact representation uses only ~50 tokens - a 90% reduction while preserving all the essential type information.
API Method Documentation
Beyond data structures, CompactSchema now documents your API methods with the same efficiency:
// Document individual methods
@CompactMethod
public func getUserProfile(_ userId: String) async throws -> UserProfile {
// Implementation
}
// Generates: getUserProfileMethod = "getUserProfile(String) async throws -> UserProfile"
// Or document entire API classes
@CompactAPIMethods
public class UserAPI {
public func getUserProfile(_ userId: String) async throws -> UserProfile { ... }
public func updateProfile(_ request: UpdateRequest) async throws -> UserProfile { ... }
public func deleteUser(_ id: String) -> Void { ... }
}
// Generates: compactMethods = [
// "getUserProfile(String) async throws -> UserProfile",
// "updateProfile(UpdateRequest) async throws -> UserProfile",
// "deleteUser(String)"
// ]
Method signatures are compressed from ~200 tokens to just ~30 tokens - an 85% reduction.
How It Works
CompactSchema leverages Swift’s powerful macro system to analyze your code at compile time:
- Compile-time Analysis: Macros examine struct, enum, and method declarations
- Smart Filtering: Automatically excludes computed properties, protocol requirements, and private methods
- Zero Runtime Cost: All processing happens during compilation
- Perfect Synchronization: Can’t get out of sync with your actual code
- Intelligent Compression: Removes redundant information while preserving essential type signatures
Complete API Documentation
The real power comes when you combine everything using CompactDocumentation:
// 1. Document your data models
@CompactSchema
struct User { let id: String; let name: String }
@CompactSchema
struct CreateUserRequest { let name: String; let email: String }
// 2. Document your API methods
@CompactAPIMethods
public class UserAPI {
public func getUser(_ id: String) async throws -> User { ... }
public func createUser(_ request: CreateUserRequest) async throws -> User { ... }
}
// 3. Generate complete documentation
let documentation = CompactDocumentation.getCompleteDocumentation()
// Output:
// # API Documentation
//
// ## Methods
// getUser(String) async throws -> User
// createUser(CreateUserRequest) async throws -> User
//
// ## Data Models
// User { id: String, name: String }
// CreateUserRequest { name: String, email: String }
This complete API documentation uses 90% fewer tokens than traditional approaches while maintaining perfect accuracy.
Real-World Benefits
For API Documentation
Instead of maintaining separate documentation that gets outdated, your schemas are always current:
@CompactSchema
struct APIResponse: Codable {
let userId: String
let isActive: Bool
enum CodingKeys: String, CodingKey {
case userId = "user_id"
case isActive = "is_active"
}
}
// Generates: APIResponse { user_id: String, is_active: Bool }
Notice how it respects your CodingKeys
for accurate API field names.
For AI Conversations
When you need to describe your entire API to an AI assistant, you can provide complete documentation in a fraction of the tokens:
// Data structures
print(User.compactSchema) // User { name: String, age: Int }
print(Product.compactSchema) // Product { id: String, name: String, price: Double? }
print(Order.compactSchema) // Order { id: String, items: [Product], total: Double }
// Individual methods
print(getUserMethod) // getUser(String) async throws -> User
print(createOrderMethod) // createOrder(OrderRequest) async throws -> Order
// Or entire API classes
print(OrderAPI.compactMethods) // All public methods in OrderAPI
// Or everything at once
let completeDoc = CompactDocumentation.getCompleteDocumentation()
For Code Generation
Perfect for generating API clients, database schemas, or validation code where you need a machine-readable representation of your complete API surface:
// Use the registry for custom documentation needs
let allMethods = CompactMethodRegistry.getAllMethods()
let methodsByCategory = CompactMethodRegistry.getMethodsByCategory()
// Feed to code generators, AI tools, or documentation systems
generateAPIClient(from: CompactDocumentation.getCompleteDocumentation())
Token Efficiency Breakdown
Complete API Documentation Example
For a typical API with 20 methods and 15 data types:
Component | Traditional Docs | CompactSchema | Savings |
---|---|---|---|
Data Structures (15 types) | ~7,500 tokens | ~750 tokens | 90% |
API Methods (20 methods) | ~4,000 tokens | ~600 tokens | 85% |
Overhead & Formatting | ~3,500 tokens | ~150 tokens | 95% |
Total | ~15,000 tokens | ~1,500 tokens | 90% |
This means you can fit 10x more API documentation in the same context window!
Why This Matters
In modern development, we’re increasingly working alongside AI tools. The ability to efficiently communicate our complete API surface is becoming a critical skill. CompactSchema provides:
- Complete API Coverage: Document both data structures and methods
- Developer Productivity: Less time spent on documentation maintenance
- AI Efficiency: Fit entire APIs in limited context windows
- Code Quality: Documentation that’s impossible to get out of sync
- Zero Overhead: No runtime performance impact
- Unified Documentation: Single source of truth for your entire API
Getting Started
Installation is straightforward via Swift Package Manager:
dependencies: [
.package(url: "https://github.com/buza/CompactSchema.git", from: "1.0.0")
]
Then just add the annotations to your code:
@CompactSchema
for data structures@CompactMethod
for individual methods@CompactAPIMethods
for entire API classes
The macros will handle the rest, and you can access complete documentation via CompactDocumentation.getCompleteDocumentation()
.
The Future of AI-Native Development
CompactSchema represents a paradigm shift in how we document and communicate our APIs. It’s not just about saving tokens - it’s about creating a seamless bridge between your Swift code and AI tools.
The Complete Suite
The CompactSchema package now provides:
- @CompactSchema: Document your data structures
- @CompactMethod: Document individual API methods
- @CompactAPIMethods: Document entire API classes
- CompactMethodRegistry: Centralized method collection
- CompactDocumentation: Complete, integrated documentation
Together, these tools create a comprehensive documentation system that:
- Reduces token usage by 90%
- Stays perfectly synchronized with your code
- Provides complete API coverage
- Enables powerful AI-assisted development
Real Impact
Imagine feeding your entire API surface to an AI assistant in just 1,500 tokens instead of 15,000. That’s the difference between maxing out context windows and having room for actual problem-solving. This efficiency enables:
- AI Code Reviews: Analyze entire codebases for patterns and issues
- Automated Testing: Generate comprehensive test suites from API definitions
- Smart Refactoring: AI-guided architecture improvements
- Instant Documentation: Generate user guides, API references, and tutorials
Conclusion
As we enter the era of AI-augmented development, tools like CompactSchema become essential infrastructure. By providing a complete, token-optimized view of your API - both data structures and methods - it enables a new generation of AI-powered development workflows.
Whether you’re building microservices, mobile SDKs, or complex backend systems, CompactSchema ensures your documentation is always accurate, complete, and AI-ready.
CompactSchema is open source and available on GitHub. Perfect for complete API documentation, AI/LLM integration, microservices, SDK development, and any Swift project where comprehensive, token-efficient documentation matters.