How to make a api call in laravel?

by dalton_moen , in category: PHP CMS , 8 months ago

How to make a api call in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 8 months ago

@dalton_moen 

To make an API call in Laravel, you can follow these steps:

  1. First, you need to create a controller that will handle the API call. You can create a new controller by running the following command in your terminal:
1
php artisan make:controller ApiController


  1. In your ApiController, you can define a method that will make the API call. You can use the Guzzle HTTP client package to make the API call. First, you need to install the Guzzle package by running the following command:
1
composer require guzzlehttp/guzzle


  1. Once Guzzle is installed, you can use it in your controller method to make the API call. Here is an example of how you can make a GET request to a URL using Guzzle:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use GuzzleHttpClient;

public function makeApiCall()
{
    $client = new Client();

    $response = $client->request('GET', 'https://api.example.com');

    $statusCode = $response->getStatusCode();
    $body = $response->getBody();

    return Response::json(['status' => $statusCode, 'data' => $body]);
}


  1. Finally, you can define a route for your API call in your routes/api.php file:
1
Route::get('/api-call', 'ApiController@makeApiCall');


Now, when you visit /api-call on your Laravel application, it will make the API call and return the response.