How to connect APIs in Laravel

April 27, 2023

To connect APIs in Laravel, you can follow these steps:

  1. Define the API routes in your routes/api.php file. These routes should be prefixed with the /api URI prefix.
  2. Create a controller to handle the API requests. You can use the php artisan make:controller command to generate a new controller.
  3. In the controller, define methods for each API endpoint. These methods should return JSON responses using Laravel’s response()->json() method.
  4. Use Laravel’s built-in HTTP client or a third-party library like Guzzle to send requests to external APIs. You can create a new instance of the HTTP client in your controller method and use it to send requests.
  5. Parse the response from the external API and return it as a JSON response from your controller 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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments