How to use Guzzle on Codeigniter? - codeigniter

I am creating a web application on Codeigniter 3.2 which works with the Facebook Graph API. In order to make GET & POST HTTP requests, I need a curl library for Codeigniter. I have found Guzzle but I Don't know how to use Guzzle on Codeigniter.

Check this link:
https://github.com/rohitbh09/codeigniter-guzzle
$this->load->library('guzzle');
# guzzle client define
$client = new GuzzleHttp\Client();
#This url define speific Target for guzzle
$url = 'http://www.google.com';
#guzzle
try {
# guzzle post request example with form parameter
$response = $client->request( 'POST',
$url,
[ 'form_params'
=> [ 'processId' => '2' ]
]
);
#guzzle repose for future use
echo $response->getStatusCode(); // 200
echo $response->getReasonPhrase(); // OK
echo $response->getProtocolVersion(); // 1.1
echo $response->getBody();
} catch (GuzzleHttp\Exception\BadResponseException $e) {
#guzzle repose for future use
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
print_r($responseBodyAsString);
}

You can integrate Guzzle into Codeigniter 3.x by following the following steps:
NOTE: I was doing this on Windows, should work on other platforms too.
Open the command terminal on your computer
Change directory to your Codeigniter app installation (i.e. my app is called MyCodeigniterApp)
cd C:\wamp64\www\MyCodeigniterApp
Install Composer in that directory by running the following command on the terminal
curl -sS https://getcomposer.org/installer | php
After installing Composer, we can now install Guzzle by running the following command on the terminal
composer require guzzlehttp/guzzle
if you encounter the following error while executing the above command
follow the recommendation in the error message.
Open composer.json located in your App root folder i.e. C:\wamp64\www\MyCodeigniterApp
then change
"mikey179/vfsStream": "1.1.*"
to
"mikey179/vfsstream": "1.1.*"
You can now re-run the command in step 4 to install Guzzle
After successful installation of Guzzle, you now need to make the following changes to the config.php file under the application/config directory
make the following changes under Composer auto-loading section and let the configuration be:
$config['composer_autoload'] = 'vendor/autoload.php';
The integration is complete, now you can use Guzzle in your controllers or models as below or by following the guides from Guzzle documentation on https://docs.guzzlephp.org/en/stable/
//Create guzzle http client
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
DONE.......

Related

How to build Guzzle GET request for -d data in curl

I am trying to access an API using Guzzle in Laravel 5.5.
The command in curl looks like:
curl http://apiurl.com/getRequest -d "api_key=token_value"
Now using Guzzle, I started to code as below:
$client = new Client(['base_uri' => 'http://apiurl.com/']);
$response = $client->request('GET', 'getRequest', [
'headers' => [
'api_key' => ['token_value']
]
]);
var_dump($response->getStatusCode());
var_dump(json_decode($response->getBody(), true));
Now I am able to see statusCode as 200 and getBody as Null. But when I use the same request using curl then I am able to see the complete data.
Could someone resolve it please?
When comparing differences between curl and Guzzle, I highly recommend using -v (curl) and the debug request option (Guzzle). The verbose output allows for visual comparison of the requests that each software is transmitting.
The curl man page indicates that -d and --data send POST requests.
(HTTP) Sends the specified data in a POST request to the HTTP server,
in the same way that a browser does when a user has filled in an HTML
form and presses the submit button. This will cause curl to pass the
data to the server using the content-type
application/x-www-form-urlencoded.
A pair of changes are required in order to send the desired request with Guzzle:
$response = $client->request('POST', $uri, [
'form_params' => [
'api_key' => $key_value,
],
]);
The first change is the type of request that is being sent (GET => POST). The second, is the usage of form_params. The form_params request option is used to send application/x-www-form-urlencoded POST requests.

Downloading zip file results in .cpgz file after extraction

I am using the following code do download a zip file. I am sure the file is existing and working on the server. The result is .cpgz file after extraction.
return response()->download('/Applications/XAMPP/xamppfiles/htdocs/stoproject/source/storage/app/Copy of StoTherm Classic®.zip');
The code was working and without any change, it stopped.
I also tried adding headers:
$headers = array(
'Content-Type' => 'application/zip',
);
return response()->download('/Applications/XAMPP/xamppfiles/htdocs/stoproject/source/storage/app/Copy of StoTherm Classic®.zip', basename('/Applications/XAMPP/xamppfiles/htdocs/stoproject/source/storage/app/Copy of StoTherm Classic®.zip'), $headers);
Also tried with:
'Content-Type' => 'application/octet-stream'
Calling ob_end_clean() fixed the issue
$response = response()->download($pathToFile)->deleteFileAfterSend(true);
ob_end_clean();
return $response;
Laravel 4 Response download issue

How to retrieve JSON from a API endpoint using Laravel 5.4?

I have 2 projects made with Laravel 5.4:
Prj-1 it is an Restful API that returns JSON.
Prj-2 it is an website that consumes the above endpoints.
In this way, I have the follow endpoint from Prj-1 :
myAPI.com/city that returns a list of all cities in the database in a JSON format.
Inside Prj-2 I have the follow:
Route:
Route::get('/showCityAPItest','AddressController#getcity');
Controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
...
public function getcity()
{
$request =Request::create('http://myAPI.com/city', 'GET');
$response = Route::dispatch($request);
dd($response);
}
If I use directly the URL (http://myAPI.com/city) in the browser, it works. I can see the JSON as expected.
BUt when I try to retrieve it from the Prj-2 I can't see it in the browser.
Actually I see
404 Not Found
nginx/1.10.1 (Ubuntu)
I was following this post but I dont know what am I doing wrong.
Any help?
Yeah, #Joel Hinz is right. Request will work within same project api end.
You need to use GuzzleHttp.
Step 1. Install guzzle using composer. Windows base operating guzzle command for composer :
composer require guzzlehttp/guzzle
step 2 write following code
public function getcity()
{
$client = new \GuzzleHttp\Client;
$data =$client->request('GET', 'http://myAPI.com/city', [
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/json'
]
]);
$x = json_decode($data->getBody()->getContents());
return response()->json(['msg' => $x], 200);
}
The answer to which you are referring is talking about internal routes. You can't use the Request and Route facades for external addresses like that. Instead, use e.g. Guzzle (http://docs.guzzlephp.org/en/latest/) to send your requests from the second site.

What to use for HTTP requests in Laravel?

I need to do HTTP request in controller Laravel for getting data by URL.
The remote URL returns JSON data format.
What to use for HTTP requests in Laravel except standart PHP Curl?
Guzzle is a popular cross-framework for making HTTP calls to external services. Laravel already has this included as a dependency for its mail integration services (Sparkpost, Mailgun, Mandrill).
Edit composer.json and in the require section add "guzzlehttp/guzzle": "~6" after the laravel/framework line.
composer update
At the top of your controller add use GuzzleHttp\Client;
Then within a method you can use it like this:
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
There is also a a Laracast on using Guzzle with Laravel.

Getting different status code using Laravel PHPUnit

Laravel 5.0
PHPUnit 4.8.24
If I visit my homepage route('/') in browser chrome shows me status-code 200 OK
But when I check with PHPUNIT
$response = $this->call( 'GET', '/' );
var_dump( $response->getStatusCode() );
It returns int(500) why?
There might be multiple reasons for that for example incorrect database connection. You should run:
$response = $this->call( 'GET', '/' );
var_dump($response->getContent());
or verify error log to see what's the exact problem

Resources