Skip to content

Latest commit

 

History

History
329 lines (266 loc) · 7.44 KB

File metadata and controls

329 lines (266 loc) · 7.44 KB

Backant CLI JSON API Schema Documentation

Overview

The backant CLI now supports generating complete APIs from JSON specifications using the --json option with the ant generate api command. This allows you to define entire API structures with routes, subroutes, and mock data in a single JSON file.

Command Usage

ant generate api <project_name> --json <json_string_or_file> [--verbose] [--dry-run]

Options

  • --json: JSON string or path to JSON file containing API specification
  • --verbose, -v: Show detailed generation progress
  • --dry-run: Validate JSON and show what would be generated without creating files

JSON Schema Structure

Basic Structure

{
  "project": {
    "name": "my-api",
    "description": "API description (optional)"
  },
  "routes": {
    "route_name": {
      "type": "HTTP_METHOD",
      "mock": "mock_data (optional)",
      "subroutes": {
        "subroute_name": {
          "type": "HTTP_METHOD",
          "mock": "mock_data (optional)"
        }
      }
    }
  }
}

Required Fields

  • routes: Object containing route definitions (required)
  • route_name: Valid Python identifier for route names (required)
  • type: HTTP method for routes/subroutes (optional, defaults to "GET")

Optional Fields

  • project: Project metadata
  • mock: Mock data for routes/subroutes (JSON object, array, or primitive)
  • subroutes: Nested route definitions

Supported HTTP Methods

  • GET
  • POST
  • PUT
  • DELETE

Examples

1. Simple API

{
  "routes": {
    "users": {
      "type": "GET",
      "mock": {"users": [], "total": 0}
    },
    "products": {
      "type": "GET",
      "mock": {"products": []}
    }
  }
}

Generated:

  • GET /users - Returns users list
  • GET /products - Returns products list

2. API with Subroutes

{
  "routes": {
    "users": {
      "type": "GET",
      "mock": {"users": []},
      "subroutes": {
        "register": {
          "type": "POST",
          "mock": {"success": true, "user_id": 123}
        },
        "profile": {
          "type": "GET",
          "mock": {"id": 1, "name": "John", "email": "john@example.com"}
        }
      }
    }
  }
}

Generated:

  • GET /users - Returns users list
  • POST /users/register - User registration endpoint
  • GET /users/profile - User profile endpoint

3. E-commerce API Example

{
  "project": {
    "name": "shop-api",
    "description": "E-commerce backend API"
  },
  "routes": {
    "products": {
      "type": "GET",
      "mock": {
        "products": [
          {"id": 1, "name": "Laptop", "price": 999.99},
          {"id": 2, "name": "Mouse", "price": 29.99}
        ],
        "total": 2
      },
      "subroutes": {
        "create": {
          "type": "POST",
          "mock": {"id": 3, "status": "created"}
        },
        "categories": {
          "type": "GET",
          "mock": {"categories": ["Electronics", "Accessories"]}
        }
      }
    },
    "orders": {
      "type": "GET",
      "mock": {"orders": []},
      "subroutes": {
        "create": {
          "type": "POST",
          "mock": {"order_id": "ord_123", "total": 1029.98}
        },
        "tracking": {
          "type": "GET",
          "mock": {"status": "shipped", "tracking": "TRK123"}
        }
      }
    }
  }
}

Usage Examples

1. Generate from JSON String

ant generate api my-shop --json '{"routes": {"products": {"type": "GET", "subroutes": {"create": {"type": "POST"}}}}}'

2. Generate from JSON File

ant generate api e-commerce --json api-spec.json --verbose

3. Dry Run Validation

ant generate api test-api --json api.json --dry-run

4. Verbose Generation

ant generate api shop --json example-api.json --verbose

Generated Project Structure

The JSON-based generation creates the same layered architecture as individual route generation:

project-name/
├── api/
│   ├── routes/
│   │   ├── users_route.py
│   │   └── products_route.py
│   ├── services/
│   │   ├── users_service.py
│   │   └── products_service.py
│   ├── repositories/
│   │   ├── users_repository.py
│   │   └── products_repository.py
│   ├── models/
│   │   ├── Users_model.py
│   │   └── Products_model.py
│   ├── startup/
│   │   └── Alchemy.py (updated with imports)
│   └── app.py (updated with blueprints)

Generated Code Features

Route Files

  • Flask blueprints with proper HTTP methods
  • Request body handling for POST/PUT/DELETE
  • JSON response formatting
  • Automatic service integration

Service Files

  • Business logic layer
  • Mock data embedding (if provided)
  • Repository integration
  • Error handling structure

Repository Files

  • SQLAlchemy-based data access
  • CRUD operation templates
  • Database session management
  • Integrity error handling

Model Files

  • SQLAlchemy ORM models
  • Dataclass decorators
  • Primary key definitions
  • Table name mapping

Validation Rules

Route Names

  • Must be valid Python identifiers
  • Cannot contain spaces or special characters
  • Examples: users, products, user_profiles ✅
  • Examples: user-profiles, 123users, users profiles ❌

HTTP Methods

  • Must be one of: GET, POST, PUT, DELETE
  • Case-sensitive
  • Examples: "GET", "POST" ✅
  • Examples: "get", "patch" ❌

Mock Data

  • Must be valid JSON
  • Can be objects, arrays, or primitives
  • Automatically converted to Python syntax
  • Examples: {"key": "value"}, [1, 2, 3], "string", 123, true ✅

Error Handling

The CLI provides comprehensive error reporting:

JSON Validation Errors

  • Missing required fields
  • Invalid route names
  • Unsupported HTTP methods
  • Malformed JSON syntax

Generation Errors

  • File system permissions
  • Directory conflicts
  • Template file issues

Best Practices

1. Route Organization

  • Use logical groupings (users, products, orders)
  • Keep route names consistent and descriptive
  • Group related functionality under subroutes

2. Mock Data Design

  • Provide realistic sample data
  • Include all expected response fields
  • Use consistent data types
  • Consider edge cases (empty arrays, null values)

3. HTTP Method Selection

  • GET: Data retrieval operations
  • POST: Create new resources
  • PUT: Update existing resources
  • DELETE: Remove resources

4. Project Structure

  • Include project metadata for documentation
  • Use descriptive project names
  • Document API purpose and scope

Integration with Existing Workflows

The JSON-based generation is fully compatible with:

  • Individual route/subroute generation
  • Docker containerization
  • Database migrations
  • Testing frameworks
  • CI/CD pipelines

Troubleshooting

Common Issues

  1. Invalid JSON Format

    • Validate JSON syntax using online validators
    • Check for trailing commas
    • Ensure proper quote escaping
  2. Route Name Conflicts

    • Use unique, descriptive route names
    • Avoid Python reserved keywords
    • Follow snake_case convention
  3. File Permission Errors

    • Ensure write permissions in target directory
    • Check for existing project directories
    • Run with appropriate user permissions
  4. Mock Data Issues

    • Validate JSON structure of mock data
    • Avoid circular references
    • Use simple data types for complex objects

For additional support, refer to the main backant CLI documentation or submit issues to the project repository.