PHP code example of webiny / rest

1. Go to this page and download the library: Download webiny/rest 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/ */

    

webiny / rest example snippets


// create REST instance for the given configuration and the API class
$rest = new \Webiny\Component\Rest\Rest('InternalApi', '\MyApp\Services\TestService');

// process the request and send the output to browser
$rest->processRequest()->sendOutput();

// simple as that...

/**
 * @rest.role ROLE_EDITOR
 */
class FooService
{
    /**
     * @rest.method get
     * @rest.default
     * @rest.ignore
     * @rest.cache.ttl 100
     * @rest.header.cache.expires 3600
     * @rest.header.status.success 200
     * @rest.header.status.errorMessage No Author for specified id.
     * @rest.rateControl.ignore
     * @rest.url some/custom/url/{param1}/param2/{param2}/other/{param3}
     *
     * @param integer $param1 Some param.
     * @param string $param2 Other param.
     * @param string $param3 Other param.
     */
    function fooMethod($param1, $param2 = "default", $param3 = "p3def")
    {
        ...
    }
}

/**
 * @rest.method get
 */

/**
 * @rest.default
 */

/**
 * @rest.ignore
 */

/**
 * @rest.cache.ttl 100
 */

/**
 * @rest.role ROLE_EDITOR
 */

/**
 * @rest.rateControl.ignore
 */

/**
 * @rest.url some/custom/url/{param1}/param2/{param2}/other/{param3}
 */

try{
    $rest = Rest::initRest('ExampleApi');
    if($rest){
        $rest->processRequest()->sendOutput();
    }    
}catch (RestException $e){
    // handle the exception
}

class FooService implements \Webiny\Component\Rest\Interfaces\VersionInterface
{

    static public function getLatestVersion(){
        return '2.0';
    }

    static public function getCurrentVersion(){
        return '1.0';
    }

    static public function getAllVersions(){
        return [
            '1.0' => 'FooService',
            '2.0' => 'FooServiceNew',
            '2.1' => 'FooServiceBetaInTesting'
        ];
    }
}

class FooService implements \Webiny\Component\Rest\Interfaces\AccessInterface
{

    public function hasAccess($role)
    {
        // do you processing here
    }
}

class FooService implements \Webiny\Component\Rest\Interfaces\CacheKeyInterface
{

    public function getCacheKey($role)
    {
        // return your generated key
    }
}

class FooService
{
    public function testError()
    {
        $error = new \Webiny\Component\Rest\RestErrorException("This is an error.", "Some custom error description.");
        $error->addError(['message'=>'This is an additional error message.', 'field'=>'This is a custom error field.']);
        $error->addError(['message'=>'Another error', 'code'=>'23a33']);

        throw $error;
    }
}