Skip to content

Instantly share code, notes, and snippets.

@peteheaney
Last active September 10, 2024 17:12
Show Gist options
  • Save peteheaney/231f488bac30e071ed74a2d747858834 to your computer and use it in GitHub Desktop.
Save peteheaney/231f488bac30e071ed74a2d747858834 to your computer and use it in GitHub Desktop.
Use Guzzle in a Craft CMS twig template. No need for a plugin!
{# Create Guzzle instance #}
{% set client = create({
'class': 'GuzzleHttp\\Client'
}) %}
{# Send API request #}
{% set response = client.request('GET', 'https://jsonplaceholder.typicode.com/posts') %}
{# Check the response status #}
{% set status = response.getStatusCode() %}
{# If the status is OK #}
{% if status == 200 %}
{# Decode the response contents #}
{% set posts = response.getBody().getContents() | json_decode %}
{# Loop through the content #}
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment