Download the PHP package programmatordev/php-api-sdk without Composer
On this page you can find all versions of the php package programmatordev/php-api-sdk. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-api-sdk
PHP API SDK
A library for creating SDKs in PHP with support for:
- PSR-18 HTTP clients;
- PSR-17 HTTP factories;
- PSR-6 caches;
- PSR-3 logs;
- Authentication;
- Event listeners;
- ...and more.
All methods are public for full hackability 🔥.
Requirements
- PHP 8.1 or higher.
Installation
Install the library via Composer:
Basic Usage
Just extend your API library with the Api
class and have fun coding:
Documentation
- Base URL
- Requests
- Query defaults
- Header defaults
- Authentication
- Event listeners
- HTTP client (PSR-18) and HTTP factories (PSR-17)
- Cache (PSR-6)
- Logger (PSR-3)
- Configure options
Base URL
Getter and setter for the base URL. Base URL is the common part of the API URL and will be used in all requests.
Requests
request
buildPath
request
This method is used to send a request to an API.
[!NOTE] A
ConfigException
will be thrown if a base URL is not set (this is, if it is empty). Check thesetBaseUrl
method for more information.[!NOTE] A
ClientException
will be thrown if there is an error while processing the request.
For example, if you wanted to get a list of users with pagination:
By default, this method will return a string
as it will be the response of the request as is.
If you want to change how the response is handled in all requests (for example, decode a JSON string into an array),
check the Event Listeners section.
buildPath
The purpose of this method is to have an easy way to build a properly formatted path depending on the inputs or parameters you might have.
For example, if you want to build a path that has a dynamic id:
Query Defaults
These methods are used for handling default query parameters. Default query parameters are applied to every API request.
For example, if you want to add a language query parameter in all requests:
[!NOTE] A
query
parameter with the same name, passed in therequest
method, will overwrite a query default. Check thegetCategories
method in the example above.
Header Defaults
These methods are used for handling default headers. Default headers are applied to every API request.
For example, if you want to add a language header value in all requests:
[!NOTE] A header with the same name, passed in the
request
method, will overwrite a header default. Check thegetCategories
method in the example above.
Authentication
Getter and setter for API authentication. Uses the authentication component from PHP HTTP.
Available authentication methods:
BasicAuth
Username and passwordBearer
TokenWsse
Username and passwordQueryParam
Array of query parameter valuesHeader
Header name and valueChain
Array of authentication instancesRequestConditional
A request matcher and authentication instances
You can also implement your own authentication method.
For example, if you have an API that is authenticated with a query parameter:
Event Listeners
addPreRequestListener
addPostRequestListener
addResponseContentsListener
- Event Priority
- Event Propagation
addPreRequestListener
The addPreRequestListener
method is used to add a function that is called before a request has been made.
This event listener will be applied to every API request.
For example:
Available event methods:
addPostRequestListener
The addPostRequestListener
method is used to add a function that is called after a request has been made.
This function can be used to inspect the request and response data that was sent to, and received from, the API.
This event listener will be applied to every API request.
For example, you can use this event listener to handle API errors:
Available event methods:
addResponseContentsListener
The addResponseContentsListener
method is used to manipulate the response that was received from the API.
This event listener will be applied to every API request.
For example, if the API responses are JSON strings, you can use this event listener to decode them into arrays:
Available event methods:
Event Priority
It is possible to add multiple listeners for the same event and set the order in which they will be executed.
By default, they will be executed in the same order as they are added, but you can set a priority
to control that order.
Event listeners are then executed from the highest priority to the lowest:
Event Propagation
In some cases, you may want to stop the event flow and prevent listeners from being called.
For that, you can use the stopPropagation()
method:
HTTP Client (PSR-18) and HTTP Factories (PSR-17)
- HTTP client and HTTP factory adapters
- Plugin system
HTTP Client and HTTP Factory Adapters
By default, this library makes use of the HTTPlug's Discovery library. This means that it will automatically find and install a well-known PSR-18 client and PSR-17 factory implementation for you (if they were not found on your project):
If you don't want to rely on the discovery of implementations, you can set the ones you want:
Plugin System
This library enables attaching plugins to the HTTP client. A plugin modifies the behavior of the client by intercepting the request and response flow.
Since plugin order matters, a plugin is added with a priority level, and are executed in descending order from highest to lowest.
Check all the available plugins or create your own.
[!NOTE] A
PluginException
will be thrown if there is a plugin with the samepriority
level.
It is important to know that this library already uses various plugins with different priorities. The following list has all the implemented plugins with the respective priority in descending order (remember that order matters):
Plugin | Priority | Note |
---|---|---|
ContentTypePlugin |
40 | |
ContentLengthPlugin |
32 | |
AuthenticationPlugin |
24 | only if authentication is enabled |
CachePlugin |
16 | only if cache is enabled |
LoggerPlugin |
8 | only if logger is enabled |
For example, if you wanted the client to automatically attempt to re-send a request that failed (due to unreliable connections and servers, for example) you can add the RetryPlugin:
Cache (PSR-6)
This library allows configuring the cache layer of the client for making API requests. It uses a standard PSR-6 implementation and provides methods to fine-tune how HTTP caching behaves:
For example, if you wanted to set a file-based cache adapter:
Logger (PSR-3)
This library allows configuring a logger to save data for making API requests. It uses a standard PSR-3 implementation and provides methods to fine-tune how logging behaves:
As an example, if you wanted to save logs into a file:
Configure Options
It is very common for APIs to offer different options (like language, timezone, etc.).
To simplify the process of configuring options, the OptionsResolver
is available.
It allows you to create a set of default options and their constraints such as required options, default values, allowed types, etc.
It then resolves the given options array
against these default options to ensure it meets all the constraints.
For example, if an API has a language and timezone options:
When using the API, it should look like this:
For all available methods, check the official page documentation.
Libraries using PHP API SDK
Contributing
Any form of contribution to improve this library (including requests) will be welcome and appreciated. Make sure to open a pull request or issue.
License
This project is licensed under the MIT license. Please see the LICENSE file distributed with this source code for further information regarding copyright and licensing.
All versions of php-api-sdk with dependencies
php-http/cache-plugin Version ^2.0
php-http/client-common Version ^2.7
php-http/discovery Version ^1.19
php-http/logger-plugin Version ^1.3
php-http/message Version ^1.16
psr/cache Version ^2.0 || ^3.0
psr/http-client Version ^1.0
psr/http-client-implementation Version *
psr/http-factory Version ^1.0
psr/http-factory-implementation Version *
psr/log Version ^2.0 || ^3.0
symfony/event-dispatcher Version ^6.4
symfony/options-resolver Version ^6.4