Home > OS >  How do I convert this cURL request to a Laravel 9.x Http client request?
How do I convert this cURL request to a Laravel 9.x Http client request?

Time:03-06

I am using Laravel 9.x and have the following cURL request which works fine however I'd like to use the proper Laravel way if possible. How do I convert this to the Laravel HTTP client.

    static public function doExternalApiCall($endpoint = null, $params = [])
    {
        try {
            $url = self::API_URL . $endpoint . http_build_query($params);
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                // CURLOPT_MAXREDIRS => 5,
                CURLOPT_TIMEOUT => 10,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0,
                // CURLOPT_CUSTOMREQUEST => 'GET',
                // CURLOPT_VERBOSE => false,
                CURLOPT_FAILONERROR => true,
                CURLOPT_HTTPHEADER => array(
                    "accept-language: en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7",
                    "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
                ),
            ));

            if(curl_exec($curl) === false)
            {
                echo 'Curl error: ' . curl_error($curl);
            }
            else
            {
                echo "Operation completed without any errors\n";
            }          

            if(curl_errno($curl))
            {
                echo 'Curl error: ' . curl_error($curl);
            }          
                
            $response = curl_exec($curl);
            curl_close($curl);
            return $response;

        } catch (\Exception $e) {
            // do some logging...
            return false;
        }        
    }

Laravel 9.x

    static private function viaGuzzle($endpoint = null, $params = null)
    {
        // unsure how I add the curlOptions
        $url = self::API_URL . $endpoint . http_build_query($params);
        return Http::withHeaders(['Referer' => self::REFERER])->get($url)->json();     
    } 

CodePudding user response:

There are plenty of examples ...

https://laravel.com/docs/9.x/http-client

$response = Http::withHeaders([
    'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
])->withOptions([
    'debug' => true,
])->get( self::API_URL . $endpoint, [
    'name' => 'Zabs',
]);
  • Related