What to use for HTTP requests in Laravel? - 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.

Related

Make a post request to a api that uses sanctum via Client (Laravel-6.2)

I have 5 applications that use the same sanctum API for authentication. What I really want to do is to make a POST request sanctum API from another application. I do GET requests like the below and it's working. But when I make a POST request it returns csrf token mismatch error.
So could someone please tell me is it possible to make a post request into a sanctum API via Client?
$response = $client->get('http://localhost:8000/api/user', [
'headers' => [
'accept' => 'application/json',
'cookie' => $request->header('cookie'),
'referer' => $request->header('referer'),
]
]);
Thanks
i use Bearer instead of cookie ,
in sanctum laravel reads access tokens from Authorization in header.
this is how i make request from laravel client to sanctum (an example of my code):
$response = Http::withHeaders([
"Accept"=> "application/json",
"Authorization" => "Bearer " . Cookie::get("Laravel")
])
->post("http://localhost:8088/api/v1/url/find", ["find" => $request->find]);
i send my headers with method withHeaders as an associative array
and send my post body with post method second argument.
read more here : https://laravel.com/docs/9.x/http-client
You're missing some headers on your requests. You need to first make a request to "/sanctum/csrf-cookie", what gives you a CSRF token. Then you pass that token as the value for the header "X-CSRF-TOKEN". Sanctum documentation explains it very well. https://laravel.com/docs/8.x/sanctum#spa-authenticating
Wish you luck!

Can't get auth user with laravel passport, keep getting "Unauthenticated" error

I can't get the information of the authenticated user in a Laravel passport app with JWT and vue.
I've installed laravel passport. Ive done everything in the documentation and added:
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
To consume it with js for a SPA app.
I've protected my routes with the auth:api middleware, but i keep getting:
{"Status":{"api_status":0,"Code":401,"Message":"Unauthenticated"}}
When i use postman to manually insert the CSRF-TOKEN in Authorization Bearer Token. It does give me the auth user.
Whatever i do, i keep getting null on Auth::user(); in my controllers and routes
Laravel V5.7
Node V10.15.3
Npm V.6.9.0
You need to send a POST request (using Postman/Insomnia) with the details of the user you want to log in as to /oauth/token in your app which will respond with an API token. You save this api token locally, and then add add it as a Header variable to your guzzle/axios/whatever function's http calls (every one of them!) to your API.
$http = new GuzzleHttp\Client;
$data = 'Whatever';
$response = $http->request('POST','api/user',[
'data' => $data,
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer xxxxxxxxxxxxThis is the long authentication string returned from the Postman requestxxxxxxxxxxxxxx'
]
]);
dd(json_decode((string) $response->getBody())); // To view the response
From: https://laravel.com/docs/5.5/passport#creating-a-password-grant-client

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.

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.

How to use Guzzle on 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.......

Resources