Bazlid Bazlid - 2 months ago 12
HTTP Question

400 Error on API endpoint in Guzzle that works fine in Browser & Postman

I am trying to access the following public API resource:

http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003

When I try it in the browser, it downloads as a JSON file. When I try it in Postman, it shows as text (JSON format).

When I try it in Guzzle, I get a 400 error.

$apiResource = "http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003";

try {
$client = new Client();
$res = $client->request('GET', $apiResource);
}
catch (\GuzzleHttp\Exception\BadResponseException $e) {
die($e->getMessage());
}


I suspect the problem is something to do with the API returning the

Content-Disposition attachment


In the header, but I don't know what the correct way for Guzzle to handle this is.

Just to be clear, I want to get the raw text output and not the file as an attachment.

Answer

All you need to do is get the body of the response (which is put into a Stream object) and then get the contents of that response:

$apiResource = "http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003";
try {
    $client = new Client();
    $res = $client->request('GET', $apiResource)->getBody()->getContents();
} 
catch (\GuzzleHttp\Exception\BadResponseException $e) {
    die($e->getMessage());
} 

Edit:

Exact code used for testing:

Route::get('/guzzletest', function() {
    $apiResource = "http://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json?geography=1946157081,943718401...943718512,2092957698&date=latest&variable=18&measures=20599,21001,21002,21003";

    try {
        // use GuzzleHttp\Client;
        $client = new Client();
        $res = $client->request('GET', $apiResource)->getBody()->getContents();
        dd($res);
    }
    catch (\GuzzleHttp\Exception\BadResponseException $e) {
        die($e->getMessage());
    }
});