engeni / api-client
Engeni - API client
Requires
- php: ^8.2
- guzzlehttp/guzzle: ^7.5
Requires (Dev)
- rector/rector: ^1.0
- dev-master
- v7.2.0
- v7.1.3
- v7.1.2
- v7.1.1
- v7.1.0
- V7.0.8
- v7.0.7
- v7.0.6
- v7.0.5
- v7.0.4
- v7.0.3
- v7.0.2
- v7.0.1
- v7.0.0
- V6.5.11
- V6.5.10
- v6.5.9
- v6.5.8
- V6.5.7
- v6.5.6
- v6.5.5
- v6.5.4
- v6.5.3
- v6.5.2
- v6.5.1
- v6.5
- v6.4.11
- v6.4.10
- v6.4.9
- v6.4.8
- v6.4.7
- v6.4.6
- v6.4.5
- v6.4.4
- v6.4.3
- v6.4.2
- v6.4.1
- v6.4.0
- v6.3.23
- v6.3.22
- v6.3.21
- v6.3.20
- v6.3.19
- v6.3.18
- v6.3.17
- v6.3.16
- v6.3.15
- v6.3.14
- v6.3.13
- v6.3.12
- v6.3.11
- v6.3.10
- v6.3.9
- v6.3.8
- v6.3.7
- v6.3.6
- v6.3.5
- v6.3.4
- v6.3.3
- v6.3.2
- v6.3.1
- v6.3.0
- v6.2.5
- v6.2.4
- v6.2.3
- v6.2.2
- v6.2.1
- v6.2.0
- v6.1.0
- v6.0.3
- v6.0.2
- v6.0.1
- v6.0.0
- v5.13.0
- v5.12.0
- v5.11.9
- v5.11.8
- v5.11.7
- v5.11.6
- v5.11.5
- v5.11.4
- v5.11.3
- v5.11.2
- v5.11.1
- v5.11.0
- v5.10.18
- v5.10.17
- v5.10.16
- v5.10.15
- v5.10.14
- v5.10.13
- v5.10.12
- v5.10.11
- v5.10.10
- v5.10.9
- v5.10.8
- v5.10.7
- v5.10.6
- v5.10.5
- v5.10.4
- v5.10.3
- v5.10.2
- v5.10.0
- v5.9.6
- v5.8.9
- v5.7.5
- v5.7.0
- dev-feature/CXM-3112-clee.-activación-automática-de-
- dev-release/v5.10
- dev-release/v5.7
This package is auto-updated.
Last update: 2025-04-11 20:47:19 UTC
README
A PHP library providing Laravel Eloquent-style interface for interacting with Engeni RESTful APIs. This client is designed to bring the familiar syntax and patterns of Laravel's Eloquent ORM to RESTful API consumption.
Overview
The Engeni API Client allows developers to query and manipulate API resources using an Eloquent-like syntax, providing a fluid, intuitive interface for working with Engeni's RESTful API endpoints. Instead of crafting raw HTTP requests, you can use the same elegant query builder pattern that Laravel developers are familiar with.
Installation
composer require engeni/api-client
Configuration
use Engeni\ApiClient\Client;
// Initialize client with your API credentials
$client = new Client([
'base_uri' => 'https://api.test', // Your API base URL
'debug' => true, // Enable/disable debug mode
'auth_token' => 'YOUR_BEARER_TOKEN' // Authorization token
]);
// Set as global client instance
$client->setAsGlobal();
// Make a basic request to test connectivity
$query = (new Query)->setPath('/');
$response = $client->get($query);
Eloquent-Style API Querying
The client follows Laravel's Eloquent ORM patterns to provide a familiar experience:
// Find a resource by ID
$user = User::find($userId);
// Build complex queries with filtering
$activeAccounts = Account::select('id', 'name')
->where('active', '1')
->limit(2)
->get();
// Eager load relationships
$userWithProfile = User::with('profile')->find($userId);
RESTful Resource Operations
The client maps HTTP verbs to appropriate methods according to RESTful principles:
Retrieving Resources
// Get all resources (paginated by default)
$users = User::all();
// Find a specific resource
$user = User::find($userId);
// Get the first matching resource
$firstActiveAccount = Account::where('active', '1')->first();
// Use firstOrFail to throw an exception if no resource is found
try {
$user = User::where('email', 'nonexistent@example.com')->firstOrFail();
} catch (ResourceNotFoundException $e) {
// Handle the error
}
// Get an array of values from a specific column
$accountNames = Account::pluck('name', 'id'); // Returns ['id' => 'name', ...]
Creating Resources
// Create a new resource
$user = User::create([
'email' => 'user@example.com',
'first_name' => 'John',
'last_name' => 'Doe'
]);
Updating Resources
// Update via fill and save
$user = User::find($userId);
$user->fill([
'first_name' => 'Updated Name'
]);
$user->save();
// Or use the update method
$user->update([
'first_name' => 'Updated Name'
]);
Deleting Resources
// Delete a resource
$user->delete();
// Or use the destroy method
User::destroy($userId);
// Delete multiple resources
User::destroy([$userId1, $userId2, $userId3]);
Query Builder Features
The query builder supports all the API conventions for filtering, sorting, and field selection:
Field Selection
// Select specific fields
$users = User::select('id', 'email', 'first_name')->get();
// Alternative using fields parameter
$users = User::get(['fields' => 'id,email,first_name']);
Filtering
// Simple filtering
$activeAccounts = Account::where('active', '1')->get();
// Multiple filters
$users = User::where('status', 'active')
->where('role', 'admin')
->get();
// Using whereIn for multiple possible values
$products = Product::whereIn('category', ['electronics', 'computers'])
->get();
Sorting
// Sort by a field (ascending)
$users = User::orderBy('created_at')->get();
// Sort by a field (descending)
$users = User::orderBy('created_at', 'DESC')->get();
// Multiple sorting criteria
$users = User::orderBy('last_name', 'ASC')
->orderBy('first_name', 'ASC')
->get();
// Alternative using sort parameter
$users = User::get(['sort' => '-created_at']);
Pagination
// Get paginated results
$users = User::paginate();
// Specify page size
$users = User::paginate(15);
// Specify the page and page size
$users = User::forPage(2, 15)->get();
// Access pagination information
echo "Showing page {$users->current_page} of {$users->last_page}";
echo "Total items: {$users->total}";
// Iterate through results
foreach ($users as $user) {
// Process each user
}
// Access pagination metadata
$paginationInfo = [
'current_page' => $users->current_page,
'first_page_url' => $users->first_page_url,
'from' => $users->from,
'last_page' => $users->last_page,
'last_page_url' => $users->last_page_url,
'next_page_url' => $users->next_page_url,
'per_page' => $users->per_page,
'prev_page_url' => $users->prev_page_url,
'to' => $users->to,
'total' => $users->total
];
Relationships
// Eager load relationships
$user = User::with('profile')->find($userId);
// Multiple relationships
$user = User::with(['profile', 'accounts'])->find($userId);
// Nested relationships
$user = User::with('accounts.permissions')->find($userId);
// Alternative using embed parameter
$user = User::find($userId, ['embed' => 'profile,accounts']);
Available Resources
The client provides access to various Engeni API resources including:
User Resources
use Engeni\ApiClient\Resource\Core\User\User;
use Engeni\ApiClient\Resource\Core\User\Profile as UserProfile;
use Engeni\ApiClient\Resource\Core\Permission\UserLocation;
// Get authenticated user with relations
$user = User::getByToken($token, ['profile', 'language', 'accounts']);
// Get user profile data
$profile = UserProfile::fromUser($userId)->get();
// Update user settings
$user->saveSettings([
'language' => 'en',
'current_account_id' => 1,
'current_location_id' => 1,
]);
// Get user locations with filters
$locations = UserLocation::fromUser($userId)
->where('service_id', 'bdi')
->whereIn('resource_name', ['products', 'prices'])
->pluck('name', 'id');
Account Resources
use Engeni\ApiClient\Resource\Core\Account\Account;
// Find account by ID
$account = Account::find($accountId);
// Get active accounts
$accounts = Account::where('active', '1')->get();
Service Resources
use Engeni\ApiClient\Resource\Core\Service\Service;
// Get all services
$services = Service::all();
// Get service names and IDs
$serviceList = Service::pluck('name', 'id');
Location & Reference Data
use Engeni\ApiClient\Resource\Core\Country;
use Engeni\ApiClient\Resource\Core\Partner;
// Get all countries
$countries = Country::all();
// Get partners by country with relations
$partners = Partner::where('country_id', 'ar')
->with('language')
->get();
Messaging
use Engeni\ApiClient\Resource\Core\Message;
// Create and send a message
$message = new Message();
$message->subscription = 'core'; // Optional, has to exist as a subscription
$message->topic = 'api-client-test'; // Optional, up to 10 chars
$message->account_id = 0; // Optional, must be an existing Account
$message->payload = [
'from' => 'no-reply@notifications.engeni.com',
'fromName' => 'Engeni L.L.C.',
'to' => 'recipient@example.com',
'replyTo' => 'no-reply@notifications.engeni.com',
'replyToName' => 'Engeni S.A.',
'subject' => 'Test Subject',
'html_body' => '<p>Message content</p>',
];
$message->send();
// Check message ID after sending
if ($message->id) {
echo "Message sent successfully with ID: " . $message->id;
}
Working with Parent Resources
Many resources in the Engeni API have parent-child relationships. The client provides methods to work with these relationships:
// Get child resources from a parent
$childResources = ChildResource::fromParent($parentId)
->where('status', 'active')
->get();
// Example with credit cards from an account
$creditCards = CreditCard::fromAccount($accountId)
->where('default', '1')
->get();
// Get specific attributes from parent-related resources
$cardTypes = CreditCard::fromAccount($accountId)
->where('default', '1')
->pluck('type', 'id');
Data Formats
Date-Time Format
The API follows RFC3339 standards for date-time values and always uses UTC timezone. When working with dates:
- All date-time values must be in RFC3339 format:
YYYY-MM-DDThh:mm:ss.sssZ
- UTC timezone is represented by
Z
or+00:00
suffix - The client automatically handles date-time conversion between PHP and API formats
Valid date-time examples:
2020-01-01T10:00:00.00000Z
2020-01-01T10:00:00Z
2020-01-01T10:00:00+00:00
// When sending dates to the API
$resource->created_at = '2020-01-01T10:00:00Z';
// When receiving dates from the API
$date = new DateTime($resource->created_at);
JSON Format
All API responses follow a consistent JSON structure:
{
"code": 200,
"status": "success",
"data": {
// Resource data here
}
}
Error Handling
The client maps API error responses to appropriate exceptions. The Engeni API follows a standardized error response structure:
{
"status": "error",
"error": {
"code": 422,
"message": "The given data was invalid.",
"errors": {
"password": [
"The password field is required",
"The password field must have at least 8 characters",
"The password field must include one number"
]
}
}
}
In development environments, additional debug information is provided:
{
"status": "error",
"error": {
"code": 405,
"message": "Method PUT not allowed for this endpoint"
},
"debug": {
"file": "/vendor/laravel/lumen-framework/src/Concerns/RoutesRequests.php",
"line": 232,
"trace": "#0 [...] RoutesRequests.php(170) {main}"
}
}
Handling API Errors
try {
$user = User::findOrFail(999); // Non-existent user
} catch (ResourceNotFoundException $e) {
// Handle 404 Not Found
echo "User not found: " . $e->getMessage();
} catch (ValidationException $e) {
// Handle 422 Validation errors
$errors = $e->getErrors();
foreach ($errors as $field => $messages) {
echo "$field: " . implode(', ', $messages);
}
} catch (ApiException $e) {
// Handle other API errors
echo "API Error ({$e->getCode()}): " . $e->getMessage();
}
Advanced Usage
Custom Queries
// Create a custom query
$query = (new Query)
->setPath('/users')
->select('id', 'email')
->where('status', 'active')
->orderBy('created_at', 'DESC')
->limit(10);
// Execute the query
$response = $client->get($query);
Custom Actions
For non-CRUD operations, you can use the do
method to call custom endpoints:
// Perform a custom action on a resource
User::do('ban', $userId);
// Search products
$results = Product::do('search', ['query' => 'keyword']);
// Perform operations with form parameters
$result = Resource::do('setup', [
'verb' => 'POST',
'form_params' => [
'param1' => 'value1',
'param2' => 'value2'
]
]);
// Custom operations on specific resources
$resource = Resource::find($resourceId);
$result = $resource->do('activate', [
'verb' => 'POST'
]);
Application Context
You can set application context for a query, which is useful for multi-tenancy:
// Set context for a query
$users = User::withinContext([
'account_id' => 1,
'location_id' => 5
])->get();
RESTful API Conventions
The Engeni API follows RESTful conventions:
- Resources are named using plural nouns:
/users
,/accounts
,/countries
- HTTP methods map to operations:
- GET - Retrieve resources
- POST - Create new resources
- PUT - Update resources (full update)
- PATCH - Partial update
- DELETE - Remove resources
- Resource relations are accessed via nested paths or through embedding
- Custom actions use verb-based endpoints with POST method:
/users/{id}/ban
- Snake_case is used for all field names in request and response payloads
- Date-time values follow RFC3339 standards and use UTC timezone
License
GNU GPLv3
Support
For support, please contact Engeni LLC.