PHP code example of jivtesh / ci4-api-generator

1. Go to this page and download the library: Download jivtesh/ci4-api-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jivtesh / ci4-api-generator example snippets


public array $default = [
    'hostname' => 'localhost',
    'username' => 'your_username',
    'password' => 'your_password',
    'database' => 'your_database',
    'DBDriver' => 'MySQLi',
    // ... other settings
];



namespace Config;

use JivteshGhatora\Ci4ApiGenerator\Config\ApiGenerator as BaseApiGenerator;

class ApiGenerator extends BaseApiGenerator
{
    // Override any settings here
}

/**
 * API prefix - the base URL path for all API endpoints
 */
public string $apiPrefix = 'api/v1';

/**
 * Enable/disable API documentation
 */
public bool $apiDocumentationEnabled = true;

/**
 * API documentation URL path
 */
public string $apiDocumentationPath = 'api/v1/docs';

/**
 * Route cache TTL in seconds (default: 1 hour)
 */
public int $maxCacheAge = 3600;

/**
 * Generate APIs only for specific tables (empty = all tables)
 */
public array $tables = [];
// Example: public array $tables = ['users', 'posts', 'comments'];

/**
 * Exclude specific tables from API generation
 */
public array $excludeTables = ['migrations', 'ci_sessions'];

/**
 * Default endpoints for all tables
 * Options: 'index', 'show', 'create', 'update', 'delete'
 */
public array $defaultEndpoints = ['index', 'show', 'create', 'update', 'delete'];

/**
 * Customize endpoints for specific tables
 */
public array $enabledEndpoints = [
    'users' => ['index', 'show', 'update'],  // Read-only + update for users
    'logs' => ['index', 'show'],              // Read-only for logs
    'posts' => ['index', 'show', 'create', 'update', 'delete']  // Full CRUD for posts
];

/**
 * Control which columns are returned in API responses
 * Empty array = all columns (default)
 */
public array $enabledColumnsToShow = [
    'users' => ['id', 'name', 'email', 'created_at'],  // Hide password, etc.
    'posts' => ['id', 'title', 'content', 'author_id', 'created_at']
];

/**
 * Override auto-generated validation rules
 * Format: ['table_name' => ['column' => 'validation_rules']]
 */
public array $validationRules = [
    'users' => [
        'email' => 'equired|min_length[5]|max_length[200]',
        'content' => '

/**
 * Automatically filter queries by specific columns
 * Perfect for multi-tenant applications
 */
public array $multiTenantColumns = [
    'company_id' => '123',  // All queries will filter by company_id = 123
    'tenant_id' => '456'
];

/**
 * Exclude specific tables from multi-tenant filtering
 */
public array $multiTenantExcludeTables = ['settings', 'system_logs'];

// In your BaseController or filter
$config = config('ApiGenerator');
$config->multiTenantColumns = [
    'company_id' => session('user_company_id')  // Dynamically set from session
];

/**
 * Default number of records per page
 */
public int $perPage = 20;

/**
 * Maximum allowed records per page
 */
public int $maxPerPage = 100;



namespace Config;

use JivteshGhatora\Ci4ApiGenerator\Config\ApiGenerator as BaseApiGenerator;

class ApiGenerator extends BaseApiGenerator
{
    public string $apiPrefix = 'api/v2';
    
    public array $excludeTables = ['migrations', 'ci_sessions', 'password_resets'];
    
    public array $enabledEndpoints = [
        'users' => ['index', 'show', 'update'],
        'posts' => ['index', 'show', 'create', 'update', 'delete'],
        'comments' => ['index', 'show', 'create', 'delete']
    ];
    
    public array $enabledColumnsToShow = [
        'users' => ['id', 'username', 'email', 'created_at']
    ];
    
    public array $validationRules = [
        'users' => [
            'email' => '

public string $apiDocumentationPath = 'api/docs';  // Custom path

public bool $apiDocumentationEnabled = false;



namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class ApiAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $token = $request->getHeaderLine('Authorization');
        
        // Validate token
        if (!$this->isValidToken($token)) {
            return service('response')
                ->setJSON(['error' => 'Unauthorized'])
                ->setStatusCode(401);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do nothing
    }

    private function isValidToken($token): bool
    {
        // Your token validation logic
        return !empty($token);
    }
}

public array $aliases = [
    'api-auth' => \App\Filters\ApiAuthFilter::class,
];

public array $filters = [
    'api-auth' => ['before' => ['api/*']],
];

// In a controller or filter
$config = config('ApiGenerator');
$config->multiTenantColumns['company_id'] = session('user_company_id');



namespace App\Controllers\Api;

use JivteshGhatora\Ci4ApiGenerator\Controllers\ApiController as BaseApiController;

class CustomApiController extends BaseApiController
{
    protected function beforeCreate($data)
    {
        // Add custom logic before creating
        $data['created_by'] = session('user_id');
        return $data;
    }
}
bash
php spark api:list
bash
php spark api:generate --openapi
bash
GET /api/v1/payments/103/HQ336336
bash
PUT /api/v1/payments/103/HQ336336
Content-Type: application/json

{
  "paymentDate": "2004-10-20",
  "amount": "7000.00"
}
bash
DELETE /api/v1/payments/103/HQ336336
bash
php spark api:list
bash
php spark api:list users
bash
# Generate OpenAPI/Swagger specification
php spark api:generate --openapi

# Generate route cache
php spark api:generate --cache

# Generate everything
php spark api:generate --all
bash
php spark api:generate --openapi
bash
composer dump-autoload
bash
php spark db:table tablename
bash
php spark routes
bash
php spark api:refresh