• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / PHP HTTP Request With Guzzle

PHP HTTP Request With Guzzle

June 11, 2014 by Rana Ahsan 3 Comments

HTTP PHP Guzzle

If you are consuming some kind of API with complex PHP HTTP requests which don’t provide a clean wrapper library, I can feel the nightmare you might be having. The same could happen if you are writing such kind of API wrapper as well. Here, I will try to introduce you to Guzzle library and get a quick start. This article is targeted at complete beginners, so if you are already somewhat experienced, you might either skip this or review it and help me improve it to fit as a robust getting-started tutorial.

What Is Guzzle?

Being there a lot of complexity in cURL support in PHP, there is a great community of PHP developers and their valuable contributions, which caused an excellent and stable library, Guzzle, to be released. It’s a lot helpful to create, customize, and process complex HTTP requests/responses(such as token-based authentication etc) easily and efficiently. As a result, even many complex API providers, such as AWS PHP SDK, utilize this library as the PHP HTTP request processing layer.

What Can Be Done With Guzzle?

You will be interested to know why we are talking about this and what we can do with it. Well, there are several use cases for this, and one or more could be yours:

  • Consume Third-Party API/Authentication: Whether you are implementing a Facebook-based authentication or showing some data which are fed from third-party web services, this is the tool you will want as your primary client to do such kind of jobs.
  • Scraping Website Data: If you are about to work on any web scraping-related tasks, either create a crawler or collect and parse various kinds of data content, you can have this library do wonders for you.
  • Easier: If you are trying to do this with raw support from PHP, in case of a little complex API consumption, you will fall into a sea of code, which will be harder to maintain/debug. This library can act as a lovely layer over PHP cURL so that you can concentrate on the main parts.
  • Performance: For simple data retrieval, its possible to do with file_get_contents

a function that might seem easier for you. But, in terms of performance, cURL still should be your primary choice. So, instead of digging into the complexity of the cURL library, this library will give you easy to understand of API interface. Also, with Guzzle, you will able to take the full power of curl to perform multiple parallel requests simultaneously, as I described in another article about retrieving multiple objects from AWS S3 in parallel.

It is known as one of the best HTTP clients available in the PHP language as of now, which also acts as a complete framework to build custom web service clients.

Alternative Of Guzzle For PHP HTTP Request:

I guess Symfony HTTP foundation, along with HTTP kernel components together, can act in a similar way, which might be a good alternative to this library. Codeception, The popular code coverage/acceptance testing framework, is built on these Symfony components and works in a similar way to fill up web forms, post data, and match responses.

Download/Installation Guzzle:

You can easily download the complete source and integrate it into your project manually from Guzzle github repo. On the other hand, if you are using composer in your application, then you can use the simple entry as a dependency as below:


{
    "require": {
        "guzzlehttp/guzzle": "~4.0"
    }
}
Code language: JSON / JSON with Comments (json)

Creating Your First Guzzle-Based Request:

To create your very first request with guzzle, a code snippet as simple as the one below will work:


use GuzzleHttp\Client;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;

$client = new Client();
$response = $client->get("https://api.github.com/");
var_dump($response->json());
Code language: PHP (php)

So, after executing the script, you should be able to see some output like the below:


{
  "current_user_url": "https://api.github.com/user",
  "authorizations_url": "https://api.github.com/authorizations",
  "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",
  "emails_url": "https://api.github.com/user/emails",
  .....................
}
Code language: JavaScript (javascript)

Hola! You have just written the smallest tinny client to consume Github API! well, it’s not much, but as long as it’s working, it’s a sign to the great path of the API consumption road. Congratulation!

Performing POST Request:

The POST request is quite similar to the previous one. Just add you will have to feed data with it. An example is given below:


$client = new Client();
$response = $client->post("http://requestb.in/tg4brftg", [
    'headers' => ['X-Foo' => 'Bar'],
    'body'    => ['field_name' => 'value']
]);
var_dump($response->getStatusCode());
Code language: PHP (php)

Also, to test your implementation to see whether it’s sending data properly, you can create a request bin to collect and show what you just sent.

There are, of course, all other kinds of request types available put for PUT, delete for DELETE etc.

oAuth Based Authentication With Guzzle:

Well, guzzle decoupled the OAuth mechanism into a separate subscriber plugin with a nice simple usage example. You can see how easy it is to create a Twitter API client!

Anything Else?

You can see the list of currently available plugins with Guzzle to match your needs, such as implementing caching/logging etc. However, if you have any questions about the basic understanding of this library or related to PHP HTTP requests, you are welcome to leave a comment. Happy coding!

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: guzzle, http, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Matt Robinson says

    June 12, 2014 at 3:40 pm

    Http-foundation is not an alternative to Guzzle, it’s an OO interface to fake or incoming requests. Alternatives to Guzzle include Requests and Buzz

    Reply
    • Md Ali Ahsan Rana says

      June 12, 2014 at 4:00 pm

      Not alone, but with use of http-kernel component(which provides a client) it seems to perform similar functionality, I guess(Though I haven’t use them in such way).

      Reply
  2. Budi Arsana says

    November 10, 2014 at 10:02 am

    HttpFoundation + HttpKernel is not designed to create request, it’s for catch request. I’ll clearly not recommend it.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023