Skip to main content

Call Guzzle from Twig

You dont need a plugin to access a ressource with guzzle - use Twig!
{% set request = craft.app.api.client
    .get('http://www.snazzy-api.com')
    .getBody()
    .__toString() 
%}

Macro

Alternativ gibt mit einem Macro eine nette Möglichkeit eines gecachten Zugriffs:

{% macro cachedApiCall(url, params) %}
    {% set cacheDuration = 60 * 60 * 12 %} {# 12 hours #}
    {% set cacheDurationOnError = 60 * 1 %} {# 1 min #}
    {% set cacheKey = [url, params] %}

    {% set response = craft.app.cache.get(cacheKey) %}
    {% if response is same as(false) %}

        {# Call API and fetch response #}
        {% set apiResponse = create('\\GuzzleHttp\\Client')
            .get(url, params)
        %}

        {# Validate response #}
        {% if apiResponse.getStatusCode() != 200 %}
            {% set cacheDuration = cacheDurationOnError %}
        {% else %}
            {% set response = apiResponse.getBody().getContents() %}
            {% if response|trim is empty %}
                {% set cacheDuration = cacheDurationOnError %}
            {% endif %}
        {% endif %}

        {# Cache response #}
        {% do craft.app.cache.set(cacheKey, response, cacheDuration) %}
    {% endif %}

    {{- response|raw -}}
{% endmacro %}

Call

Dieses Macro kann dann entweder importiert werden oder wenn es sich in demselben File befindet, direkt aufgerufen werden:

{% set wikipediaPage = _self.cachedApiCall('https://en.wikipedia.org/api/rest_v1/page/summary/' ~ person.title, {
    headers: {
        accept: 'application/json',
        charset: 'utf-8',
        profile: 'https://www.mediawiki.org/wiki/Specs/Summary/1.4.2',
        query: { redirect: 'false' },
    },
})|trim|json_decode 

%}

Quelle

Das Makro habe ich im Code in https://github.com/miranj/demystifying-craft-api gefunden.