Goodbye cURL! Practical GuzzleHttp Encapsulation: One-Click API Requests in GET/POST Dual Mode

Introduction

use GuzzleHttp\Client;

GET Request

$response = (new Client())->get('https://xxx.com/api/ping');$status = $response->getStatusCode();$content = $response->getBody()->getContents();dd($status,$content);

Encapsulation

use GuzzleHttp\Client;use GuzzleHttp\Exception\GuzzleException;
class HttpHelper{    /**     * Initiate a GET request     *     * @param string $url Request URL     * @param array|null $query GET parameters (automatically appended to URL)     * @param array $headers Custom request headers     * @return array ['status' => int, 'content' => string] or ['error' => string]     */    public static function getRequest(string $url, ?array $query = null, array $headers = []): array    {        try {            $client = new Client();            $response = $client->get($url, [                'headers' => $headers,                'query' => $query, // GET parameters (e.g., ?key1=value1&key2=value2)                'verify' => false, // Should be removed or set to true in production            ]);
            return [                'status' => $response->getStatusCode(),                'content' => $response->getBody()->getContents(),            ];        } catch (GuzzleException $e) {            return ['error' => $e->getMessage()];        }    }
    /**     * Initiate a POST request     *     * @param string $url Request URL     * @param array $data POST data     * @param array $headers Custom request headers     * @param bool $isJson Whether to send JSON data (default is form format)     * @return array ['status' => int, 'content' => string] or ['error' => string]     */    public static function postRequest(string $url, array $data, array $headers = [], bool $isJson = false): array    {        try {            $client = new Client();            $options = [                'headers' => $headers,                $isJson ? 'json' : 'form_params' => $data, // Automatically select data type based on $isJson                'verify' => false, // Should be removed or set to true in production            ];
            $response = $client->post($url, $options);
            return [                'status' => $response->getStatusCode(),                'content' => $response->getBody()->getContents(),            ];        } catch (GuzzleException $e) {            return ['error' => $e->getMessage()];        }    }}

In the HttpHelper class, a GET request method is added, and the code structure is optimized to support the reuse of GET/POST requests. Below is the complete implementation:

Final Version of HttpHelper Class (GET + POST)

use GuzzleHttp\Client;use GuzzleHttp\Exception\GuzzleException;
class HttpHelper{    /**     * Initiate a GET request     *     * @param string $url Request URL     * @param array|null $query GET parameters (automatically appended to URL)     * @param array $headers Custom request headers     * @return array ['status' => int, 'content' => string] or ['error' => string]     */    public static function getRequest(string $url, ?array $query = null, array $headers = []): array    {        try {            $client = new Client();            $response = $client->get($url, [                'headers' => $headers,                'query' => $query, // GET parameters (e.g., ?key1=value1&key2=value2)                'verify' => false, // Should be removed or set to true in production            ]);
            return [                'status' => $response->getStatusCode(),                'content' => $response->getBody()->getContents(),            ];        } catch (GuzzleException $e) {            return ['error' => $e->getMessage()];        }    }
    /**     * Initiate a POST request     *     * @param string $url Request URL     * @param array $data POST data     * @param array $headers Custom request headers     * @param bool $isJson Whether to send JSON data (default is form format)     * @return array ['status' => int, 'content' => string] or ['error' => string]     */    public static function postRequest(string $url, array $data, array $headers = [], bool $isJson = false): array    {        try {            $client = new Client();            $options = [                'headers' => $headers,                $isJson ? 'json' : 'form_params' => $data, // Automatically select data type based on $isJson                'verify' => false, // Should be removed or set to true in production            ];
            $response = $client->post($url, $options);
            return [                'status' => $response->getStatusCode(),                'content' => $response->getBody()->getContents(),            ];        } catch (GuzzleException $e) {            return ['error' => $e->getMessage()];        }    }}

Usage Examples

1. GET Request (with parameters)

$result = HttpHelper::getRequest('https://xxx.com/api/user', [    'id' => 123,    'type' => 'vip',], [    'Authorization' => 'Bearer token123',]);
dd($result);

Equivalent cURL:

GET https://xxx.com/api/user?id=123&type=vip

2. POST Request (form format)

$result = HttpHelper::postRequest('https://xxx.com/api/user', [    'username' => 'zhangsan',    'age' => 12,], [    'X-Request-From' => 'Laravel',]);
dd($result);

Equivalent cURL:

curl -X POST \  -H "Content-Type: application/x-www-form-urlencoded" \  -d "username=zhangsan&age=12" \https://xxx.com/api/user

3. POST Request (JSON format)

$result = HttpHelper::postRequest('https://xxx.com/api/user', [    'username' => 'zhangsan',    'age' => 12,], [    'Accept' => 'application/json',], true); // Key: set the last parameter to true
dd($result);

Equivalent cURL:

curl -X POST \  -H "Content-Type: application/json" \  -d '{"username":"zhangsan","age":12}' \  https://xxx.com/api/user

Alternative

Prefer using GuzzleHttp, if not available, use the cURL below

    public static function cUrlRequest($url,$data = null,$header_datas=null){        $curl = curl_init();        curl_setopt($curl, CURLOPT_URL, $url);        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);        curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);        if (!empty($data)){            curl_setopt($curl, CURLOPT_POST, 1);            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);        }        if(!empty($header_datas)){            // Set request headers            $headers = [];            foreach ($header_datas as $key => $value) {                $headers[] = $key . ': ' . $value;            }            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);        }        $output = curl_exec($curl);        curl_close($curl);        return $output;    }

「Previous Highlights」

  • The first domestic free one-core one-G cloud server?
  • The secrets Linux veterans never reveal: Why does tar.gz crush zip and 7z?
  • Highly recommended, 5 must-have productivity software for computers
  • Tested, an incredibly useful Linux connection tool, no less than xshell
  • Truly amazing, an open-source lightweight centralized scheduling and management system gocron
  • Python’s cross-platform package management and environment configuration tool
  • Passwordless SSH login: Simplifying Linux connections, enhancing security (verified)
  • The magical tool for operating servers, Tmux

Leave a Comment