Search code examples
phpguzzle

GuzzleHttp\Client ignores base path in base_url


I'm using Guzzle in a set of PHPUnit-powered tests for a REST API.

I create my client as follows:

use GuzzleHttp\Client;

$client = new Client(['base_url' => ['http://api.localhost/api/{version}', ['version' => '1.0']]]);

This works fine, and I can make requests using the following code:

$request = $client->createRequest('GET', '/auth');
$request->setBody(Stream::factory(json_encode(['test'=>'data'])));
$response = $client->send($request);
$decodedResponse = $response->json();

However, Guzzle is ignoring the /api/{version} part of the base URL and makes the request to here:

http://api.localhost/auth

However, I would have expected it to make the request here:

http://api.localhost/api/1.0/auth

Have I mis-read the documentation and my expected behaviour is thus wrong, or is there some other option I need to enable to get it to append the /auth url to the /api/1.0 base path when making the request?


Solution

  • Here are examples for Guzzle 7 (7.4.1) of what Michael Dowling wrote

    $client = new Client(['base_uri' => 'http://my-app.com/api/']);
    $response = $client->get('facets'); // no leading slash - append to base
    //    http://my-app.com/api/facets
    
    $client = new Client(['base_uri' => 'http://my-app.com/api/']);
    $response = $client->get('facets/'); // no leading slash - append to base // ending slash preserved
    //    http://my-app.com/api/facets/
    
    $client = new Client(['base_uri' => 'http://my-app.com/api/']);
    $response = $client->get('/facets'); // leading slash - absolute path - base path is lost
    //    http://my-app.com/facets
    
    $client = new Client(['base_uri' => 'http://my-app.com/api']); // no ending slash in base path - ignored
    $response = $client->get('facets');
    //    http://my-app.com/facets
    
    $client = new Client(['base_uri' => 'http://my-app.com/api']);
    $response = $client->get('/facets'); // leading slash - absolute path - base path is lost
    //    http://my-app.com/facets