How to make a request to an API in Laravel?

0 like 0 dislike
10 views
Good day!
Make an ajax request from js on back. Then you need to send a get request with the third-party api. Can you please tell me how to send request and get response. Watched a bunch of articles, videos and nothing comes out.

1) I Tried to do using Guzzle

use GuzzleHttp\\Client; public function getData() { $client = new Client([ 'headers' => [ 'content-type' => 'application/json', 'Accept' => 'application/json' ], ]); $response = $client->request('GET', ' link ']); $data = $response->getBody(); return response()->json( [ 'response' => [ 'test' => $data ] ], 200); }


2) Tried it this way

public function getData() { $url = " link "; $opts = [ 'http' => [ 'method' => "GET", ] ]; $context = stream_context_create($opts); $data = file_get_contents($url, false, $context); return response()->json( [ 'response' => [ 'test' => $data ] ], 200); }


Checked on 2 API. The first method does not work with either. The second only works with one. Just pasting link in the address bar in the browser get answers from two API. How to send request and receive response.

P. S. working With Laravel for a second week, hence the question. NID help!
by | 10 views

3 Answers

0 like 0 dislike
The first example about Guzzle, the second - about file_get_contents. What does Laravel do not understand.

Describe what "not working". The error in this issue?
by
0 like 0 dislike
And you from laravel csrf specified in the header of the request?
Most likely triggered banal protection lark
by
0 like 0 dislike
Perhaps the answer is useful to someone: don't look at the CSRF it's not for the Api!
From Laravel is in route/api.php who doesn't verify CSRF
Route::post('/post/{id}','IndexController@post');
In the controller check:
public function post(Request $request){ // example json $post = json_encode($request->all(), JSON_UNESCAPED_UNICODE); //... }

In /route/api.php you can do post requests without inspections and not only. Importantly, in the controller, handle them correctly.
And best of all read about the Laravel API.
by

Related questions

0 like 0 dislike
1 answer
asked Apr 12, 2019 by Alexxosipov
0 like 0 dislike
2 answers
asked Jun 7, 2019 by babyflowercry
0 like 0 dislike
3 answers
110,608 questions
257,186 answers
0 comments
33,708 users