laravel-enso/api
最新稳定版本:1.14.1
Composer 安装命令:
composer require laravel-enso/api
包简介
External service integrations and API logging for Laravel Enso
关键字:
README 文档
README
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, direction, and duration. - Logs inbound calls through the
ApiLoggermiddleware and reports non-200responses to administrators. - Provides a read-only
System > API Logstable, with filters for user, permission, method, direction, and creation datetime. - 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 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\Method; class FetchOffers implements Endpoint { private array $filters = []; public function method(): Method { return Method::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_idrouteurlpayloadmethodstatustrydirectiondurationcreated_atupdated_at
Relationships and casts:
user()Belongs toLaravelEnso\Users\Models\UserpayloadCast to arraymethodCast toLaravelEnso\Api\Enums\MethoddirectionCast toLaravelEnso\Api\Enums\Direction
Logging directions:
Direction::InboundDirection::Outbound
API Logs table
The package provides the System > API Logs table through:
GET /api/system/apiLogs/initTableGET /api/system/apiLogs/tableDataGET /api/system/apiLogs/exportExcel
Permissions:
system.apiLogs.indexsystem.apiLogs.initTablesystem.apiLogs.tableDatasystem.apiLogs.exportExcel
The table defaults to api_logs.created_at desc, exposes created_at as a datetime column, displays resolved users and permissions, and supports filters for user, permission, method, direction, and creation datetime.
Upgrade notes
This release changes the public logging enum contract:
- replace
LaravelEnso\Api\Enums\CallswithLaravelEnso\Api\Enums\Direction - replace
Calls::Inbound/Calls::OutboundwithDirection::Inbound/Direction::Outbound - replace
LaravelEnso\Api\Enums\MethodswithLaravelEnso\Api\Enums\Method - replace
Method::get,Method::post,Method::put, andMethod::deletewithMethod::GET,Method::POST,Method::PUT, andMethod::DELETE - update endpoint signatures from
method(): stringtomethod(): Method - update application code or reporting queries that reference
api_logs.typeto useapi_logs.direction - update frontend API log filters from
apiLogMethodstoapiLogMethod
After updating the package, run:
composer update laravel-enso/api php artisan enso:upgrade
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.
::: warning 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/menus↗laravel-enso/migrator↗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!
统计信息
- 总下载量: 22.78k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 2
- 依赖项目数: 4
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-06-23