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

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.

Related

Rapid API, Google Translate post request with laravel

I need to use the Google Translate API in my Laravel application, get requests are working fine, but post requests don't seem to, I tried with Postman and got the same error message.
Here's the test I made:
Route::get('/', function () {
return Http::withHeaders([
"content-type" => "application/x-www-form-urlencoded",
"accept-encoding"=> "application/gzip",
"x-rapidapi-key"=> "<rapid_api_key_here>",
"x-rapidapi-host"=> "google-translate1.p.rapidapi.com",
"useQueryString"=> true
])->post('https://google-translate1.p.rapidapi.com/language/translate/v2/detect', [
"q"=> "English is hard, but detectably so",
]);
});
Here's the test with Postman:
Here's the error I got in both tests:
I don't know what went wrong, any suggestions?
You can try using Route::post method instead of get as you're making a post request here.
Context: https://laravel.com/docs/5.0/routing#basic-routing

Laravel API request middleware unathenthicated

I need your help with my Laravel API HTTP Request. I am trying to get a response from my api. But it sends back "Error: "Request failed with status code 401" and the AuthenthicationException shows "Unauthenticated." . I have not found any solutions. I need your help... Thanks.
const response = (await rootApi.get(`/openSesame/targets/${id}`)).data;
My 'Api\TargetController
public function detail($id)
{
$spintaxInput = SpintaxInput::find($id);
if (!$spintaxInput) {
return response()->json(['error' => "Not found."], 404);
}
return response()->json($spintaxInput, 200);
}
My api routes
Route::group(['middleware' => ['auth:web']], function () {
Route::group(['prefix' => 'openSesame'], function () {
Route::get('/targets/{id}', 'Api\TargetController#detail');
});
});
you should use Sanctum to API authenticate
Passport would be the way to go here.
check Passport
Now, to help you with this:
To be able to authenticate when you're going to make a request to the api, make sure to use the header: Authentication and the token followed by Bearer
A token example should be like this one:
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiZThmNjZiMTU0Yjg4OGM2YmI2ODg0ZDM2ZDU3NGYxY2FiODFjODgyMmI0MDc5NDVkMTNjM2I2MDdiMDc0MGNkNTI1MzgxZDU2NWJkNWUwZTciLCJpYXQiOjE1ODY3MDY1MzgsIm5iZiI6MTU4NjcwNjUzOCwiZXhwIjoxNjE4MjQyNTM4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Brf48KrE3smifCIo61_8alvU8Yi5atsMtLz5t7-drQ7xnpG0Lga9q7Wh8RDJaYLtxHltdMLRVfp2HtstVQO6XY8qE0GNqS2pfjwFGDJTChWDSbINzjRyX9rO9FdTbE95TPlh84e_PRQ7iWMDO_DQkB67YvuYieXJjWAzF5UBGjK9ZMSjjzHahHV-iCE4Si_i0DHP6bLDTksZd51jiYV7ptGr41lZCwnL09fNjtWtLYTl79OoxIzcEPZMUQ_l7QcoJPJUYa0-lvHAta9hbkzZHdskIOB9C6afel4VxPFEVI0RmP5glJBJFKu0A_0N80iJf7yhXqofk5muF-bFWv9_092os2h3-zt0bDjTb7jeSAY8CkgxRQ3oLtRQN9MBgxRdUechycdimbKpU6hhpGfJfsofHtJiRGAbh5Eddlq5AGjdZkRW6zu9CjFUFiivZHOO_JI3HmU39jXUQx8218Czb9_Z-iG02K0Bvtk0eilvZl3k6FjvDka3beb0Zg99Da5MKeYSMKXqn4U-mndQPPtsidWCwh4foskzv6mRvWhsGh8xN0zByCTIhML-ogqrIGNcDUsrgpi2E4eue4PZ9DfYIa740kYKnJLzpNC6_ilQPesb3MjqLLx9DBcUkuWH7fwKKA_OaxhIv2WiELUECjWuIIDMpNGuK_Kes0RbqedPvlg
When using API's, you will need to use that header in each request. Otherwise you will get a 401. The 401 means that you're not logged in.
You should use passport, like said.
And for auth middleware, replace it to:
middleware('auth:api')

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 authenticate Vue.js / Axios request of an API route in Laravel

I'm in Laravel 5.6. I have all my API routes built out and properly responding to requests from my REST client (Paw). I'm trying to build a simple front end to access those routes.
I'm trying to use Laravel's out-of-the-box features as much as possible, so I'm using Axios to call those routes from a blade template using Vue.js. It works if I disable auth middleware on the test route, but I get 401 errors on the console when auth middleware is enabled for the route.
The problem seems obvious enough... The auth:api guard on my /api routes wants to see an oauth token in the header, but when I log in with the web page it does session authentication. I assume there's a simple way to resolve this without having to spoof an oauth token request in the web frontend, right? Do I need to somehow pass the session token in my request with Axios? And, if so, do I also need to change the auth:api guard in my api routes file?
I solved it! I'm a bit embarrassed because the answer was actually in the Laravel docs, but I will say I tried this before posting the question here and it wasn't working. Perhaps something else was broken at the time.
Per the Laravel docs:
All you need to do is add the CreateFreshApiToken middleware to your
web middleware group in your app/Http/Kernel.php file:
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
This Passport middleware will attach a laravel_token cookie to your
outgoing responses. This cookie contains an encrypted JWT that
Passport will use to authenticate API requests from your JavaScript
application. Now, you may make requests to your application's API
without explicitly passing an access token...
You will probably want to use Larvel Passport or a JWT auth mechanism for obtain the Authorization token.
Seeing as how you're using axios, add a request interceptor to attach the access token to every request once you successfully authenticate. A simple example:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// assume your access token is stored in local storage
// (it should really be somewhere more secure but I digress for simplicity)
let token = localStorage.getItem('access_token')
if (token) {
config.headers['Authorization'] = `Bearer ${token}`
}
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
to use the auth:api first you need api_token inside your users table
Schema::table('users', function ($table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
also you can create a user for testing as follows
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(60),
]);
in your layout use the following before #yield('content')
<script>
window.Laravel = <?php echo json_encode(['api_token' => (Auth::user())->api_token]); ?>
</script>
now you can use window.laravel.api_token inside your vue js to use it in headers
heres an example
var methods = new Vue({
el: '#tabs_lists',
data: {
config: {
headers: {
Authorization: 'Bearer ' + window.Laravel.api_token,
Accept: 'application/json'
}
},
data: []
},
methods: {
test: function (link) {
axios.get(link, this.config)
.then(response => (this.data = response.data)).catch(function (error) {
// handle error
console.log(error);
});
}
}
}
)

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.

Resources