Search code examples
phpapicurlget

PHP - GET request works in Postman, but not with cUrl


There's a free weather API in my country that I want to use to get rain data. The request is simple https://apitempo.inmet.gov.br/estacao/2021-05-03/2021-05-06/A826 and there's no authentication. If I try the request using Postman, my browser or AJAX, it works fine and I get the results I need. However, using cURL, I get nothing.

Here's the PHP code that I tried:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://apitempo.inmet.gov.br/estacao/2021-05-03/2021-05-06/A826',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

I have the cURL.dll installed and tested in another server, but it didn't work.

Is there a problem with the code or is it the API that blocks PHP requests?


Solution

  • its look like this website looking for user-agent header. try this:

    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://apitempo.inmet.gov.br/estacao/2021-05-03/2021-05-06/A826',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'User-Agent: something'
      ),
    ));
    
    $response = curl_exec($curl);
    
    curl_close($curl);
    echo $response;