I am new to Symfony development so excuse me if this is a dumb question. I am trying to GET JSON data from an external API. I have tried to run a GET request via Postman and got the correct data in JSON format back so I know my URL is correct.
I have the following code written to use Guzzle to HTTP GET a set of JSON data from my external API:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;
class ScheduleController {
/**
* @Route("/schedule")
*/
public function getJobs() {
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'http://my.api.url/']);
// Send a request to http://my.api.url/site/67/module/1449/item
$response = $client->request('GET', 'site/67/module/1449/item');
dump($response);
}
}
I am trying to follow along as closely as I can with the Guzzle quick start guide. I am getting a 500 error from this code:
Attempted to load class "Client" from namespace "AppBundle\Controller\GuzzleHttp".
Did you forget a "use" statement for e.g. "Symfony\Component\BrowserKit\Client", "Symfony\Component\HttpKernel\Client" or "Symfony\Bundle\FrameworkBundle\Client"?
I have a use statement for use GuzzleHttp\Client;
What am I doing wrong? Is there an easier way to do this?
This line:
$client = new GuzzleHttp\Client(['base_uri' => 'http://my.api.url/']);
Should be:
$client = new Client(['base_uri' => 'http://my.api.url/']);
or:
$client = new \GuzzleHttp\Client(['base_uri' => 'http://my.api.url/']);
Either one would work since you imported the namespace. You probably want the first option. When you put GuzzleHttp\Client PHP thinks it's a relative namespace that's why it's saying "AppBundle\Controller\GuzzleHttp\Client" cannot be found.