DEV Community

Cover image for How to Consume APIs in Laravel PHP
Michellebuchiokonicha
Michellebuchiokonicha

Posted on • Edited on

How to Consume APIs in Laravel PHP

Not many articles are available on this topic, the reason being that laravel is a serve-side framework and works with the database.

People rarely use third-party APIs in Laravel.
However, this is quite a simple process.

Consuming APIs in Laravel.

Here, I will discuss the GET API and the POST API.
Whether a laravel or livewire controller/component this works for both.

GET Requests

You create your method in your laravel controller, call the GET API, decode your JSON data, and return the result. Here is a sample.

$response = Http::get("your API");
$result = $response->getBody()->getContents();
$data = json_decode($result);
$resullt= $data->data;
return $result;
Enter fullscreen mode Exit fullscreen mode

Another way to do this is to add your API to your .env file as your root file and request it in your controller.

This is similar to your base URL in any other front-end framework.

The second way is to add your base URL to your .env file and then call it into your mount method.

public function mount()
{
$this->baseUrl = env('Your_BASE_URL');
}

Enter fullscreen mode Exit fullscreen mode

After this, call add your API to your component like this.

You can proceed to render it or add it to an event listener for use when needed.

$result = $this->makeRequest($this->baseUrl, 'GET', 'your api');
if ($result->success) {
$char = $result->data;
return $char;
}
return [];
Enter fullscreen mode Exit fullscreen mode

POST Requests.

To call a post request, here is what to do:

$response = Http::post(
"Your API",
[
'required_field' => $this->required_field,
]
);
$result = $response->getBody()->getContents();
$data = json_decode($result);
$result= $data->data;
return $result;
Enter fullscreen mode Exit fullscreen mode

Here, you would need some parameters to post and decode your json data. Add them as usual to your method.

Post your requests using the getBody and getContents.

You can also dd your result to see what your request returns.
This is as simple as it can get.

Top comments (0)