S
S
Slava2018-04-26 04:17:58
PHP
Slava, 2018-04-26 04:17:58

How to make an API request in Laravel?

Good day!
I make an ajax request from js to the backend. Next, you need to send a get request to a third-party api. Please tell me how to send a request and get a response. Reviewed a bunch of articles, videos and nothing comes out.
1) Tried doing it 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 for 2 APIs. The first method does not work with either. The second - works only with one. By inserting the link simply in the address bar in the browser, I get responses from two APIs. How to send a request and receive a response.
PS I'm working with Laravel for the second week, so this question. Need help!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
�
 Fauser, 2019-02-27
@slava_pv

Perhaps the answer will be useful to someone: Do not look towards CSRF - it is not for Api!
Laravel has in route/api.php which does not check CSRF In the controller check:

public function post(Request $request){
    // например json
         $post = json_encode($request->all(), JSON_UNESCAPED_UNICODE);
         //... 
 }

In /route/api.php you can make post requests without checks and more. The main thing is to handle them correctly in the controller.
And best of all, read about the Laravel API.

T
tvbird, 2018-12-23
@tvbird

Have you specified csrf from laravel in the request header?
Most likely, the banal protection of the lark works

S
Stalker_RED, 2018-04-26
@Stalker_RED

The first example is about Guzzle, the second is about file_get_contents. What does Laravel have to do with it - it's not at all clear.
Describe what "doesn't work" means. Does it give errors?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question