Home > Software design >  Symfony Get from third party api
Symfony Get from third party api

Time:08-25

I'm very new to "Symfony" and I was wondering how u can use (Get) from a third-party API and then print it out in the controller.

and I did a httpclient like in https://symfony.com/doc/current/http_client.html

but how do I get that $Content over to an array I can use like my hardcoded in my product controller?

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;

class ProductsController extends AbstractController
{
    #[Route('/products', name: 'products')]
    public function index(): Response
    {       
        $products = ["Test", "Test2". "Test3"];

        return $this->render('/products/index.html.twig',array(
                'products' => $products
            ));
    }
}

CodePudding user response:

As already mentioned, you have to use the HTTPClient for this.

First, install it via composer

composer require symfony/http-client

In your controller you have to write the following:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class ProductsController extends AbstractController
{
    #[Route('/products', name: 'products')]
    public function index(HttpClientInterface $client): Response
    {       
        $response = $client->request('GET', 'API_URL');
        $products = $response->toArray();

        return $this->render('/products/index.html.twig',array(
            'products' => $products
        ));
    }
}

You can also dump the response beforehand for test purposes:

$response = $client->request('GET', 'API_URL');
$products = $response->toArray(); // or $response->getContent();

dump($products);

toArray parses directly the content of the API and tries to create an array from it. getContent gives you the response as a string.

See for more: https://symfony.com/doc/current/http_client.html

  • Related