Answer the question
In order to leave comments, you need to log in
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);
}
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);
}
Answer the question
In order to leave comments, you need to log in
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);
//...
}
Have you specified csrf from laravel in the request header?
Most likely, the banal protection of the lark works
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 questionAsk a Question
731 491 924 answers to any question