[Symfony] Using the ipstack API

Published on 2020-01-04 • Modified on 2020-01-04

In this snippet we will see how to retrieve data from the ipstack API. We will use the Symfony HttpClient component. If you want to have a nice formatted output, please check out the tool page "What is my IP?".


<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

/**
 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet65Trait
{
    public function snippet65(Request $request): void
    {
        $ip = $request->getClientIp();
        if (empty($ip)) {
            echo 'No ip found.';

            return;
        }

        $routeParams = $request->attributes->get('_route_params');
        $endPoint = 'https://api.ipstack.com/'.$ip.'?'.http_build_query([
            'access_key' => $this->getParameter('ipstack_api_key'),
            'language' => $routeParams['_locale']
        ]);

        try {
            $response = HttpClient::create()->request('GET', $endPoint)->getContent();
        } catch (ClientExceptionInterface | RedirectionExceptionInterface | ServerExceptionInterface | TransportExceptionInterface $e) {
            echo 'Error when accessing the ipstack service.';

            return;
        }

        print_r(json_decode($response, true)); // That's it! 😁
    }
}