Skip to content

Framework for REST API generation with support for reconciliation, authorization policies, and automatic schema control

Notifications You must be signed in to change notification settings

OpenCHAMI/fabrica

Fabrica πŸ—οΈ

Build production-ready REST APIs in Go with automatic code generation

REUSE statusgolangci-lint Build Release Go Reference Go Report Card OpenSSF Scorecard OpenSSF Best Practices

πŸ—οΈ Code Generator for Go REST APIs Transform Go structs into production-ready REST APIs with OpenAPI specs, storage backends, and middleware in minutes.

Fabrica is a powerful code generation tool that accelerates API development by transforming simple Go struct definitions into complete, production-ready REST APIs. Define your resources once, and Fabrica generates everything you need: handlers, storage layers, clients, validation, OpenAPI documentation, and more.

✨ Key Features

  • πŸš€ Zero-Config Generation - Define resources as Go structs, get complete APIs instantly
  • πŸ“Š Multiple Storage Backends - Choose between file-based storage or SQL databases (SQLite, PostgreSQL, MySQL)
  • πŸ”’ Security Ready - Flexible middleware system for custom authentication and authorization
  • πŸ“‹ OpenAPI Native - Auto-generated specs with Swagger UI out of the box
  • 🎯 Smart Validation - Request validation with detailed, structured error responses
  • ⚑ Developer Experience - CLI tools, hot-reload development, comprehensive testing
  • πŸ“‘ CloudEvents Integration - Automatic event publishing for resource lifecycle (CRUD) and condition changes
  • 🌐 Cloud-Native Ready - API versioning, conditional requests (ETags), event-driven patterns
  • πŸ—οΈ Production Patterns - Consistent API structure, error handling, and middleware

🎯 Perfect For

  • Microservices Architecture - Maintain consistent API patterns across services
  • Rapid Prototyping - From struct definition to running API in under 5 minutes
  • API Standardization - Enforce best practices and patterns across development teams
  • OpenAPI-First Development - Generate comprehensive documentation alongside your code

πŸ“¦ Installation

Latest Release (v0.3.1)

macOS/Linux:

# Direct download and install
curl -L https://github.com/openchami/fabrica/releases/download/v0.3.1/fabrica-$(uname -s)-$(uname -m) -o fabrica
chmod +x fabrica
sudo mv fabrica /usr/local/bin/

# Verify installation
fabrica version

Using Go:

go install github.com/openchami/fabrica/cmd/[email protected]

Development Version

git clone https://github.com/openchami/fabrica.git
cd fabrica
make install

πŸš€ Quick Start (5 Minutes)

1. Initialize your project:

fabrica init device-api
cd device-api

2. Add your first resource:

fabrica add resource Device

3. Update your Spec and Status fields in pkg/resources/device/device.go:

Add desired fields to generated DeviceSpec and DeviceStatus structs, retaining other code.

// DeviceSpec defines the desired state of a Device
type DeviceSpec struct {
    // copy contents to generated DeviceSpec
    Type         string            `json:"type" validate:"required,oneof=server switch router storage"`
    IPAddress    string            `json:"ipAddress" validate:"required,ip"`
    Status       string            `json:"status" validate:"required,oneof=active inactive maintenance"`
    Tags         map[string]string `json:"tags,omitempty"`
    LastSeen     *time.Time        `json:"lastSeen,omitempty"`
    Port         int               `json:"port,omitempty" validate:"min=1,max=65535"`
}

// DeviceStatus represents the observed state of a Device
type DeviceStatus struct {
    // copy contents to generated DeviceSpec
    Health       string    `json:"health" validate:"required,oneof=healthy degraded unhealthy unknown"`
    Uptime       int64     `json:"uptime" validate:"min=0"`
    LastChecked  time.Time `json:"lastChecked"`
    ErrorCount   int       `json:"errorCount" validate:"min=0"`
    Version      string    `json:"version,omitempty"`
}

4. Generate your API:

fabrica generate

5. Update dependencies:

go mod tidy

6. Run your server:

go run ./cmd/server

7. Test your API:

# Create a device
curl -X POST http://localhost:8080/devices \
  -H "Content-Type: application/json" \
  -d '{
    "name": "web-server-01",
    "type": "server",
    "ipAddress": "192.168.1.100",
    "status": "active",
    "port": 443,
    "tags": {"role": "web", "datacenter": "us-west-2"},
    "labels": {"environment": "production", "team": "platform"}
  }'

# List all devices
curl http://localhost:8080/devices

# Get specific device
curl http://localhost:8080/devices/web-server-01

# View OpenAPI documentation
open http://localhost:8080/swagger/

πŸŽ‰ That's it! You now have a fully functional REST API with validation, OpenAPI docs, and structured error handling.

πŸ“š Learn by Example

Explore hands-on examples in the examples/ directory:


πŸŽ“ Learning Path: Start with Example 1 to understand core concepts, try Example 5 for CloudEvents, then advance to Example 3 for production patterns and database integration.

πŸ—οΈ Architecture Overview

Fabrica follows clean architecture principles and generates well-structured projects:

πŸ“ Generated Project Structure
β”œβ”€β”€ πŸ“ cmd/
β”‚   β”œβ”€β”€ πŸ“ server/           # 🌐 REST API server with all endpoints
β”‚   └── πŸ“ cli/              # πŸ–₯️ Command-line client tools
β”œβ”€β”€ πŸ“ pkg/
β”‚   β”œβ”€β”€ πŸ“ resources/        # πŸ“ Your resource definitions (you write these)
β”‚   └── πŸ“ client/           # πŸ”Œ Generated HTTP client with proper error handling
β”œβ”€β”€ πŸ“ internal/
β”‚   β”œβ”€β”€ πŸ“ storage/          # πŸ’Ύ Generated storage layer (file or database)
β”‚   └── πŸ“ middleware/       # βš™οΈ Generated middleware (auth, validation, etc.)
β”œβ”€β”€ πŸ“ docs/                 # πŸ“š Generated OpenAPI specs and documentation
└── πŸ“„ .fabrica.yaml         # βš™οΈ Project configuration

πŸͺ Storage Backends:

  • πŸ“ File Backend - JSON files with atomic operations, perfect for development and small datasets
  • πŸ—ƒοΈ Ent Backend - Type-safe ORM supporting SQLite, PostgreSQL, MySQL for production workloads

⚑ Generated Features:

  • βœ… REST handlers with proper HTTP methods, status codes, and content negotiation
  • βœ… Comprehensive request/response validation with structured error messages
  • βœ… OpenAPI 3.0 specifications with interactive Swagger UI
  • βœ… Type-safe HTTP clients with automatic retries and error handling
  • βœ… CLI tools for testing, administration, and automation
  • βœ… Middleware for authentication, authorization, versioning, and caching

⚠️ IMPORTANT: Code Regeneration

Fabrica supports regenerating code when you modify your resources or configuration. This means:

βœ… SAFE TO EDIT:

  • pkg/resources/*/ - Your resource definitions (spec/status structs)
  • .fabrica.yaml - Project configuration
  • cmd/server/main.go - Server customizations (before first // Generated comment)

❌ NEVER EDIT:

  • Any file ending in _generated.go - These are completely regenerated on each fabrica generate
  • Files in generated directories after running fabrica generate

πŸ”„ Regeneration Command:

fabrica generate  # Safely regenerates all *_generated.go files

Your custom code in resource definitions and main.go will be preserved, but all generated files will be completely rewritten.

πŸ“¦ Resource Structure

Fabrica uses a Kubernetes-inspired envelope pattern that provides consistent structure across all resources. Every API resource follows this standardized format:

{
  "apiVersion": "v1",
  "kind": "Device",
  "metadata": {
    "name": "web-server-01",
    "uid": "550e8400-e29b-41d4-a716-446655440000",
    "labels": {
      "environment": "production",
      "team": "platform"
    },
    "annotations": {
      "description": "Primary web server for customer portal"
    },
    "createdAt": "2025-10-15T10:30:00Z",
    "updatedAt": "2025-10-15T14:22:15Z"
  },
  "spec": {
    "type": "server",
    "ipAddress": "192.168.1.100",
    "status": "active",
    "port": 443,
    "tags": {"role": "web", "datacenter": "us-west-2"}
  },
  "status": {
    "health": "healthy",
    "uptime": 2592000,
    "lastChecked": "2025-10-15T14:22:15Z",
    "errorCount": 0,
    "version": "1.2.3"
  }
}

🏷️ Envelope Components

Component Purpose Your Code Generated
apiVersion API compatibility versioning ❌ βœ… Auto-managed
kind Resource type identifier ❌ βœ… From struct name
metadata Resource identity & organization ❌ βœ… Standard fields
spec Desired state (your data) βœ… You define ❌
status Observed state (runtime info) βœ… You define ❌

πŸ“ What You Define

spec struct - The desired configuration/state of your resource:

type DeviceSpec struct {
    Type      string `json:"type" validate:"required,oneof=server switch router"`
    IPAddress string `json:"ipAddress" validate:"required,ip"`
    Status    string `json:"status" validate:"oneof=active inactive maintenance"`
    // ... your business logic fields
}

status struct - The observed/runtime state of your resource:

type DeviceStatus struct {
    Health      string    `json:"health" validate:"oneof=healthy degraded unhealthy"`
    Uptime      int64     `json:"uptime"`
    LastChecked time.Time `json:"lastChecked"`
    // ... your runtime/monitoring fields
}

🎯 Benefits of This Pattern

  • πŸ”„ Consistency - All resources follow the same structure regardless of domain
  • 🏷️ Rich Metadata - Built-in support for labels, annotations, and timestamps
  • πŸ“Š State Separation - Clear distinction between desired (spec) and observed (status) state
  • πŸ”§ Tooling Integration - Compatible with Kubernetes tooling and patterns
  • πŸ“ˆ Scalability - Proven pattern used by Kubernetes for managing complex systems

πŸ’‘ Pro Tip: Focus on designing your spec and status structs - Fabrica handles all the envelope complexity automatically!

πŸ“– Documentation

πŸš€ Getting Started:

πŸ—οΈ Architecture & Design:

πŸ’Ύ Storage & Data:

βš™οΈ Advanced Topics:

🀝 Contributing

We welcome contributions from the community! Here's how to get involved:

πŸ› Report Issues:

πŸ’» Code Contributions:

  • Fork the repository and create a feature branch
  • Write tests for your changes
  • Ensure all tests pass: make test integration
  • Submit a pull request with a clear description

πŸ’¬ Community:

🏷️ Releases & Roadmap

Current Version: v0.3.1

πŸ“… Recent Updates:

  • βœ… Enhanced template system with better error handling
  • βœ… Improved integration testing framework
  • βœ… Updated documentation and examples
  • βœ… Better CI/CD pipeline with comprehensive testing

πŸ“š Resources:

πŸ“„ License

This project is licensed under the MIT License - see the license file for details.

About

Framework for REST API generation with support for reconciliation, authorization policies, and automatic schema control

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors 4

  •  
  •  
  •  
  •