API
Description
API is Laravel Enso's reusable package for external service integrations and inbound API request logging.
It provides a small action-based client on top of Laravel's HTTP client, plus reusable contracts for authentication, retries, query parameters, file uploads, form payloads, and timeouts. On top of that, it standardizes inbound and outbound API logging, admin notifications for failed calls, and small payload-building helpers used across Enso integrations.
Installation
This package comes pre-installed in Laravel Enso distributions that integrate external services or expose protected internal API endpoints.
For standalone package installation inside an Enso-based application:
composer require laravel-enso/api
The package auto-registers its service provider, loads its migrations, and registers:
- the
api-action-loggermiddleware alias - the
core-apimiddleware group - the
enso.apiconfiguration namespace
Run the migrations after installation:
php artisan migrate
If you need to inspect raw request and response traffic during integration work, enable the debug flag in your environment:
API_DEBUG=true
Features
- Wraps outbound integrations in
Actionclasses that resolve and executeEndpointdefinitions. - Builds requests through Laravel's HTTP client with support for:
- bearer-token authentication
- basic authentication
- custom headers
- query parameters
- form submissions
- file attachments
- custom timeouts
- retry policies
- Refreshes an expiring auth token once automatically when an authenticated endpoint receives
401or403on the first try. - Logs outbound calls in
api_logs, including URL, route, HTTP method, status, attempt number, payload, type, and duration. - Logs inbound calls through the
ApiLoggermiddleware and reports non-200responses to administrators. - Queues
ApiCallErrornotifications to active Enso admins on thenotificationsqueue. - Provides
ResourceandFilterbase classes for payload shaping and input validation. - Includes a
Throttlehelper for debouncing repeated external API calls. - Ships the
api_logsmigration and anApi\Models\Logmodel with Enso caching traits.
Tip
If an endpoint implements UsesAuth and the first response is 401 or 403, Api::call() refreshes the token once through the token provider before continuing with the normal retry flow.
Usage
Outbound action
Define a small endpoint class that describes the request:
use LaravelEnso\Api\Contracts\Endpoint;
use LaravelEnso\Api\Enums\Methods;
class FetchOffers implements Endpoint
{
private array $filters = [];
public function method(): string
{
return Methods::get;
}
public function url(): string
{
return 'https://posf.ro/api/v1/comparator';
}
public function filters(array $filters): self
{
$this->filters = $filters;
return $this;
}
public function body(): array
{
return $this->filters;
}
}
Wrap it in an Action and call handle():
use LaravelEnso\Api\Action;
class FetchOffersAction extends Action
{
public function __construct(private array $filters)
{
}
protected function endpoint(): Endpoint
{
return (new FetchOffers())->filters($this->filters);
}
}
$response = (new FetchOffersAction([
'request' => 'comparator-electric',
'tip_client' => 'casnic',
]))->handle();
$payload = $response->json();
Inbound logging
Use the standalone middleware alias when you only want request logging:
Route::middleware(['auth', 'api-action-logger'])
->prefix('internal')
->group(function (): void {
Route::post('sync', SyncController::class)->name('internal.sync');
});
Or use Enso's core-api middleware group when the route also needs active-state checks, permission checks, and localisation handling:
Route::middleware(['auth', 'core-api'])
->prefix('api')
->group(function (): void {
Route::post('calendar/events', EventController::class)->name('calendar.events.store');
});
Resource and filter helpers
Use Resource when a payload needs nested resource resolution and mandatory attribute validation:
use LaravelEnso\Api\Resource;
class OfferResource extends Resource
{
public function __construct(private array $offer)
{
}
public function toArray(): array
{
return [
'id' => $this->offer['id'],
'supplier' => $this->offer['supplier'],
];
}
protected function mandatoryAttributes(): array
{
return ['id', 'supplier'];
}
}
Use Filter when you want to reject unsupported keys before sending them to the remote service:
use LaravelEnso\Api\Filter;
class OfferFilters extends Filter
{
public function allowed(): array
{
return ['request', 'tip_client', 'consum_lunar'];
}
}
$filters = (new OfferFilters($input))->toArray();
API
Core classes
LaravelEnso\Api\ApiBuilds and executes the HTTP request, applies optional contracts, tracks attempt count, refreshes bearer tokens once when needed, and retries failed calls when the endpoint allows it.LaravelEnso\Api\ActionOrchestrates one outbound call, measures duration, persists the outbound log entry, reports failures, and returns theIlluminate\Http\Client\Response.
Contracts
Required contract:
EndpointDefinesmethod(),url(), andbody().
Optional contracts:
UsesAuthAdds bearer token support through a token provider.UsesBasicAuthAdds HTTP basic authentication.CustomHeadersAdds arbitrary request headers.QueryParametersAppendsparameters()to the request URL.RetryEnables retries throughtries()anddelay().TimeoutSets a custom HTTP timeout.AsFormSends the payload as form data.AttachesFilesAttaches files to the pending request.TokenDefines the token provider contract used byUsesAuth.
Middleware
api-action-loggerAlias forLaravelEnso\Api\Http\Middleware\ApiLoggercore-apiMiddleware group registered by the service provider:LaravelEnso\Core\Http\Middleware\VerifyActiveStateLaravelEnso\Api\Http\Middleware\ApiLoggerLaravelEnso\Permissions\Http\Middleware\VerifyRouteAccessLaravelEnso\Localisation\Http\Middleware\SetLanguage
Log model and storage
LaravelEnso\Api\Models\Log
Stored attributes:
user_idrouteurlpayloadmethodstatustrytypedurationcreated_atupdated_at
Relationships and casts:
user()Belongs toLaravelEnso\Users\Models\UserpayloadCast to array
Logging types:
Calls::InboundCalls::Outbound
Resource, filter, and throttle helpers
Resource::resolve()Resolves nested resources and validates mandatory attributes.Resource::collection()Maps a collection into resolved resource arrays.Resource::toJson()Serializes the resource payload.Filter::toArray()Rejects unsupported keys before returning the filter array.Throttle::__invoke()Debounces repeated calls by sleeping until the configured interval has elapsed.
Note
Inbound logging reports any non-200 response through ApiCallError, while outbound actions report failed responses and thrown exceptions through the same notification pipeline.
The notification handler targets active Enso admins and queues the email on the notifications queue.
Depends On
Required Enso packages:
laravel-enso/core↗laravel-enso/enums↗laravel-enso/helpers↗laravel-enso/localisation↗laravel-enso/permissions↗laravel-enso/rememberable↗laravel-enso/tables↗laravel-enso/upgrade↗laravel-enso/users↗
Framework dependency:
Contributions
are welcome. Pull requests are great, but issues are good too.
Thank you to all the people who already contributed to Enso!