How to connect APIs in Laravel
April 27, 2023

To connect APIs in Laravel, you can follow these steps:
routes/api.php
file. These routes should be prefixed with the /api
URI prefix.php artisan make:controller
command to generate a new controller.response()->json()
method.Here’s an example of a controller method that connects to an external API:
public function getWeather(Request $request)
{
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.openweathermap.org/data/2.5/weather?q='.$request->city.'&appid='.env('OPENWEATHER_API_KEY'));
$weather = json_decode($response->getBody(), true);
return response()->json($weather);
}
In this example, the controller method gets the current weather for a city by sending a request to the OpenWeatherMap API using the Guzzle HTTP client. The response is then parsed and returned as a JSON response from the controller method.
Note: Make sure to properly handle exceptions and errors that may occur when connecting to external APIs.