computer 311339
Articles » Using Guzzle and Silverstripe to get and render API data

Using Guzzle and Silverstripe to get and render API data

22 April, 2020

In this guide we will go through a basic example of using Guzzle to fetch data from an API and rendering that data onto a Silverstripe template.

The API we will be using is https://newsapi.org/. This API requires an API key which is free to obtain as part of the Developer Plan.

Installing Guzzle

Install Guzzle with the following command in your app’s root directory

composer require guzzlehttp/guzzle

 

Creating a Page type to fetch and render API data

Create a page type called NewsPage.

<?php

namespace MySite\Pages;

use Page;

class NewsPage extends Page {

}

 

And now create a NewsPageController where we will write our function to fetch API data.

<?php

namespace MySite\Pages;

use PageController;

class NewsPageController extends PageController {

}

 

Also create a NewsPage.ss template under the appropriate directory, and rebuild the database and flush the cache by appending ‘dev/build?flush=all’ to the end of your site URL.

Fetching API data

Before fetching data you must first have obtained an API key. To quickly test your API key works, try go to this URL and you should get a similar response.

URL: https://newsapi.org/v2/top-headlines?country=nz&apiKey=yourAPIkey

 

Now we can write our method to fetch data. Go to the NewsPageController and reference the GuzzleHttp namespace

<?php

namespace MySite\Pages;

use PageController;
use GuzzleHttp\Client;

class NewsPageController extends PageController {

}

 

Next, write the fetch method like the one below. I have called mine ‘NewsAPIData’.

public function NewsAPIData() {
    $articlesList = new ArrayList();

    $client = new Client([
        'base_uri' => 'https://newsapi.org/v2/'
    ]);

    $response = $client->request('GET', 'top-headlines?country=nz&apiKey=yourAPIkey');
                        
    if ($response->getStatusCode() == 200) {
        $body = json_decode($response->getBody(), true);
        $articles = $body['articles'];
                
        foreach ($articles as $article) {            
            $articlesList->push(new ArrayData([
                'Author' => $article['author'], 
                'Title' => $article['title'],
                'Description' => $article['description'],
                'URL' => $article['url'],
                'ImageURL' => $article['urlToImage'],
                'Published' => $article['publishedAt'],
                'Content' => $article['content'],
                'Source' => $article['source']['name']
            ]));
        }
    }
            
    return $articlesList;    
}

 

Let us step through the code:

  • $articlesList is an ArrayList, a list object that wraps around an array of objects or arrays.
  • $client is an instance of the Guzzle HTTP client and where we set our base_uri ('https://newsapi.org/v2).
  • $response posts a GET request to the API endpoint with additional parameters and API key.
  • Next, we check if we get a 200 response and decode the json response.
  • $articles contains the articles returned in the response.
  • Then we loop through the $articles and push them into the $articlesList array wrapped with ArrayData.
  • By wrapping our response in an ArrayList with ArrayData, this allows Silverstripe to interpret it and render it onto the template.

Rendering the fetched data onto a Silverstripe template

Now we are ready to render the data onto our NewsPage.ss template with the following markup

<% loop $NewsAPIData %>
    <div class="news-article">
        <div class="news-article__thumbnail-wrapper">
            <img src="$ImageURL" width="250px" alt="$Title">
        </div>
        <div class="news-article__main-body">
            <h3>
                <a href="$URL">$Title</a>
            </h3>
            <p>Author: $Author</p>
            <p>Published: $Published</p>
            <p>$Description</p>
        </div>        
    </div>
<% end_loop %>

 

If you would like to read more about rendering arrays onto Silverstripe templates, go to this article Silverstripe - how to render arrays in templates using ArrayList and ArrayData.

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments