cms-frontend/app/Services/Api/ApiService.php

92 lines
2.6 KiB
PHP

<?php
namespace App\Services\Api;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
use Exception;
class ApiService
{
protected string $baseUrl;
public function __construct()
{
// Get the external API URL from environment variable
$this->baseUrl = env('EXTERNAL_API_URL', 'http://localhost:8000/api');
}
/**
* Make a GET request to the API
*/
public function fetch($endpoint, array $params = [])
{
try {
$response = Http::withHeaders($this->getHeaders())
->get($this->baseUrl . $endpoint, $params);
if ($response->successful()) {
return [
'success' => true,
'data' => $response->json()['data'] ?? $response->json(),
'message' => 'Data fetched successfully'
];
}
return [
'success' => false,
'message' => $response->json()['message'] ?? 'Failed to fetch data',
'errors' => $response->json()['errors'] ?? []
];
} catch (Exception $e) {
return [
'success' => false,
'message' => 'API service is unavailable',
'errors' => [$e->getMessage()]
];
}
}
/**
* Make a POST request to the API
*/
public function submit($endpoint, array $data = [])
{
try {
$response = Http::withHeaders($this->getHeaders())
->post($this->baseUrl . $endpoint, $data);
if ($response->successful()) {
return [
'success' => true,
'data' => $response->json()['data'] ?? $response->json(),
'message' => 'Data submitted successfully'
];
}
return [
'success' => false,
'message' => $response->json()['message'] ?? 'Failed to submit data',
'errors' => $response->json()['errors'] ?? []
];
} catch (Exception $e) {
return [
'success' => false,
'message' => 'API service is unavailable',
'errors' => [$e->getMessage()]
];
}
}
/**
* Get the headers for API requests
*/
protected function getHeaders(): array
{
return [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . session('api_token'),
];
}
}