Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Guzzle to HTTP GET to external API with Symfony

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?

like image 293
Liz Avatar asked Jan 23 '17 23:01

Liz


2 Answers

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.

like image 121
Chip Dean Avatar answered Nov 12 '22 06:11

Chip Dean


I set the IP address from localhost:8087 to my windows IP address 192.168.x.x:8087.

It worked so there was no need to do anything with linux ports/docker ports etc.

like image 27
Khandaker Toihidul Islam Avatar answered Nov 12 '22 07:11

Khandaker Toihidul Islam