Search code examples
phphttplaravelbuzz

How to add form data on Post requests for Buzz HTTP Client on Laravel?


I'm using Buzz HTTP Client for Laravel.

I have a problem adding form data to my POST requests, since it wasn't specified in it's wiki/documentation.

Listed below are the two ways of sending requests.

Example 1:

$response = Buzz::post('http://api.website.com/login');
//how do I add a "username", and "password" field in my POST request?
echo $response;
echo $response->getContent;

Example 2:

$request = new Buzz\Message\Request('POST', '/', 'http://google.com');
$response = new Buzz\Message\Response();
//how do I add a "username", and "password" field in my POST request?    
$client = new Buzz\Client\FileGetContents();  
$client->send($request, $response);

echo $request;  
echo $response;

Solution

  • The answer here is going to really depend on what the API expects. Lets assume, the API expects the password and username sent as JSON in the content of the request. The example http request would look something like:

    POST /login HTTP/1.1
    Content-Type: application/json
    
    {
        "username": "bugsBunny",
        "password": "wh4tsUpD0c"
    }
    

    To do this with Buzz, this should work:

    $jsonPayload = json_encode([
        ‘username’ => ‘bugsBunny’,
        ‘password’ => ‘wh4tsUpD0c
    ]);
    
    $headers = ['Content-Type', 'application/json'];
    
    $response = Buzz::post('http://api.website.com/login', $headers, $jsonPayload);
    

    If you're attempting to submit a form on a given website, you shouldn't use the above method. Instead use Buzz's built in form method which will attach the correct headers.

    use Buzz\Message\Form;
    $request = new Form(Form::METHOD_POST, ‘login’, ‘api.website.com’);
    $request->setFields([
        ‘username’ => ‘bugsBunny’,
        ‘password’ => ‘wh4tsUpD0c’
    ]);
    
    $response = new Buzz\Message\Response();
    
    $client = new Buzz\Client\Curl();
    $client->send($request, $response);
    

    On a side note, I'd suggest not using this library. The library is, as you stated, Laravel integration for Buzz. The issue here is, the author should have made buzz a dependency listed in composer, rather than include the Buzz source directly. This prevents updates to Buzz from making their way into this project. You can see on the actual Buzz repo, the last commit was 29 days ago. Also if another package is using Buzz and including it correctly by composer, composer would install both packages. But when an instance of Buzz was created, you couldn't be certain which version was being loaded. You should just use Buzz, which can be found on packagist.

    // assuming $headers and $jsonPayload are the same as in previous example.
    $browser = new Buzz\Browser();
    $response = $browser->post('http://api.website.com/login', $headers, $jsonPayload);