2

I need to include some form of API call within my userfrosting site, however I am finding it difficult to find a way to do this. I have seen that one of the ways to add PHP to twig files is by creating an extension, but this does not seem to be what I'm looking for exactly.

I need to be able to pull data using a third party API which I have previously been using PHP to make calls with, however if any of you think I should use a different method to do this I am open to suggestions

TIA

alexw
  • 8,468
  • 6
  • 54
  • 86
O. Rowley
  • 31
  • 4
  • An extension seems like the solution. Perhaps explain the problem in a bit more detail. – Cerad Dec 22 '15 at 14:40
  • What sort of API is this? Generally speaking, you should be able to make your API call in the **controller**, and then pass any content retrieved from that API into your template via the call to `render`. – alexw Dec 22 '15 at 15:32

2 Answers2

2

For Userfrosting >4.1, in your sprinkle/composer.json file, add a requirement to include Guzzle: "require": {"guzzlehttp/guzzle": "~6.0"}

(remember to run composer update to install the new dependency.

Guzzle Docs

Then in your controller include guzzle:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;

then you can initiate guzzle with:

$client = new Client([
    'base_uri' => $config['api']['host'].'/',
    'timeout' => 5 // your timeout param
]);

(I set my api host in the sprinkle config, using an environment variable, so its not hardcoded.)

you can then make a POST request as follows, returning the response into a variable.

$api_response = $client->post('your_api_route', [
    'json' => [
        'api_param_1' => 'Hello',
        'api_param_2' => 'World!'
    ]
]);

Also reccomended the wrap the last bit in a try and catch an guzzle/http exceptions.

If your response is a JSON document, you can retrieve the contents into an array with:

$data = json_decode($api_response->getBody()->getContents(), true);
x00x70
  • 41
  • 4
1

I talk to an API in my userfrosting setup within the controller called by my route, then pass that data to my template. Check out the first tutorial on how to create a new template and pass data to it. Do whatever with PHP that you need to within the route (via a controller).

Web and Flow
  • 144
  • 8