[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?".



namespace App\Controller\Snippet;

use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Request;
use function Symfony\Component\String\u;
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 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 = u($request->getClientIp())->trim();
        if ($ip->isEmpty()) {
            echo 'No ip found.';


        /** @var array<string,mixed> $routeParams */
        $routeParams = $request->attributes->get('_route_params');
        $endPoint = 'http://api.ipstack.com/'.$ip->toString().'?'.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) {
            echo 'Error when accessing the Ipstack service.';


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

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet