How to get JSON API to TYPO3 Fluid ViewHelper?

Kategorie : Extbase , Fluid , By : Tanvi Patel

Now a days, Headless CMS approach is trending. People love to create APIs based website and webapps. Imaging a situation, where you will need to read JSON API data to your TYPO3 Fluid.

Here is the TYPO3 code snippet to get JSON API data to your TYPO3 CMS using custom TYPO3 Fluid ViewHelper.

Call Custom TYPO3 JSON to Fluid ViewHelper

 


{namespace n=Vendor\Package\ViewHelpers}
<n:JsonToFluid api="https://yoursite/path.json"  />

 

Prepare Custom TYPO3 JsonToFluidViewHelper

 


namespace Vendor\Package\ViewHelpers;

use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;


/**
 * renders the header of the results page
 * @internal
 */
class JsonToFluidViewHelper extends AbstractViewHelper
{
    use CompileWithRenderStatic;

    /**
     * As this ViewHelper renders HTML, the output must not be escaped.
     *
     * @var bool
     */
    protected $escapeOutput = false;

    /**
     * Initialize arguments
     */
    public function initializeArguments()
    {
        $this->registerArgument('api', 'string', '', true);
    }

    /**
     * @param array $arguments
     * @param callable|\Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     * @return array
     */
    public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
    {
        $api = $arguments['api'];
        $req = GeneralUtility::makeInstance(RequestFactory::class);
        $response = $req->request($api,'GET',[]);
        $rawResponse = $response->getBody()->getContents();
        return json_decode($rawResponse, true);
    }
}

To keep improving, Do you have feedback and suggestions? Or, Are you facing any issues to implement above TYPO3 tutorial? Feel free to write your comment at below comment box; I'll happy to help you :)

Post Comment

Your email address will not be published. Required fields are marked *

×

Name ist erforderlich!

Geben Sie einen gültigen Namen ein

Gültige E-Mail ist erforderlich!

Gib eine gültige E-Mail Adresse ein

Kommentar ist erforderlich!

Google Captcha ist erforderlich!

Sei der erste der kommentiert

Stay up to date with our recent TYPO3 Blogs, news, & updates