Skip to content

Instantly share code, notes, and snippets.

@peteheaney
Last active March 24, 2023 18:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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