CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Programming PHP HTTP Request With Guzzle

PHP HTTP Request With Guzzle

Rana Ahsan June 11, 2014 3 Comments


 PHP HTTP Request With Guzzle    

If you are consuming some kind of API with complex PHP HTTP requests which doesn’t provide a clean wrapper library, I can feel the nightmare you might be having. Same could be happen if you are yourself writing such kind of API wrapper as well. Here, I will try to introduce you with guzzle library and getting a quick start. This article is targeted for complete beginners, so if you are already somewhat experienced, you either might 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 causes for an excellent and stable library, Guzzle to be released. It’s a lot helpful to create, customize, 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 utilizes this library as the PHP http request processing layer.

What Can Be Done With Guzzle?

You will might be interested to know why we are talking about this and what we actually 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 kind of data content,you can get a free serp api or 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 nice 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

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

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

Alternative Of Guzzle For PHP HTTP Request:

I guess, symfony httpfoundation along with httpkernel components together can act in similar way, which might good alternative of this library. Codeception, The popular code coverage/acceptance testing framework, is built on these symfony components and works in similar way to fill-up web forms, post data, match response.

Download/Installation Guzzle:

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

{
    "require": {
        "guzzlehttp/guzzle": "~4.0"
    }
}

Creating Your First Guzzle Based Request:

To create your very first request with guzzle, a code snippet as simple as 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());

So, after executing the script, you should be able to see some output like 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",
  .....................
}

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

Performing POST Request:

POST request is quite similar to the previous one, just additionally 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());

Also, to test your implementation whether its sending data properly, you can create an request bin to collect and show what you just sent.

There are of course all other kind 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 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 plugin with guzzle to match to your needs such as implement caching/logging etc. However, if you have any questions about basic understanding of this library or related to PHP HTTP request, you are welcome to leave a comment. Happy coding!

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • How To Work With CodeIgniter Pagination
  • Get Facebook C# Api Access Token
  • LinQ To SQL Database Update Operations In C#
  • How To Work With Multithreaded Programming In C#.NET Application
  • Getting Started With HTML5 Web Speech API

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in