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.
Install Guzzle with the following command in your app’s root directory
composer require guzzlehttp/guzzle
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.
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:
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