Uses of Http Guzzle PHP

Sraban Pahadasingh    April 24, 2020 02:42 PM

About PHP Guzzle for API

  1. Initialize th instance

    $this->client = new \GuzzleHttp\Client();
  2. Get Method

    $params = Array(
            'key1' => $id, 
            'key2' => $value,
           );
    $promise = $this->client->request('GET',  route('statement'), [
        'query' => $params,
        'debug' => false
    ]);
    
    $promise->getBody()->rewind();
    $output = $promise->getBody()->getContents();
    $httpStatusCode = $promise->getStatusCode();
    
  3. Post Method: Raw data posting like posting json in payload

    $rawInput = json_encode($array); // string
    
    -OR-
    
    $rawInput = <<client->request('POST',  route('statement'), [
        'body' => $rawInput,
        'debug' => false
    ]);
    
    $promise->getBody()->rewind();
    $output = $promise->getBody()->getContents();
    $httpStatusCode = $promise->getStatusCode();
    
  4. Post using Form Fields

    $filedInputs = Array(
        'email' => 'test@gmail.com',
        'name' => 'Test user',
        'password' => 'testpassword',
    );
    
    $promise = $this->client->request('POST',  route('statement'), [
        'form_params' => $rawInput,
        'debug' => false
    ]);
    
    $promise->getBody()->rewind();
    $output = $promise->getBody()->getContents();
    $httpStatusCode = $promise->getStatusCode();
    
  5. POST File Upload from Directory

    $promise = $this->client->request('POST', 'http://www.example.com/files/post', [
        'multipart' => [
            [
                'name'     => 'file_name',
                'contents' => fopen('/path/to/file', 'r')
            ],
            [
                'name'     => 'csv_header',
                'contents' => 'First Name, Last Name, Username',
                'filename' => 'csv_header.csv'
            ]
        ]
    ]);
    
    $promise->getBody()->rewind();
    $output = $promise->getBody()->getContents();
    $httpStatusCode = $promise->getStatusCode();
    





Comments powered by Disqus