timostamm / json-client
A simple client for JSON APIs using Guzzle and the Symfony Serializer.
Installs: 227
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 3
Forks: 1
Open Issues: 1
pkg:composer/timostamm/json-client
Requires
- php: ^8.0
- guzzlehttp/guzzle: ^6.5 || ^7.4
- symfony/options-resolver: ^5.4 || ^6.4
- symfony/serializer: ^5.4 || ^6.4
Requires (Dev)
- phpunit/phpunit: ^9.6.20
- psr/log: ^3.0
Conflicts
- guzzlehttp/guzzle: <6.5.8
- guzzlehttp/promises: <1.4
- psr/http-message: <1.1
README
A simple client for JSON APIs using Guzzle and the Symfony Serializer.
To implement a API client, you can extend AbstractApiClient and write your methods, using the Guzzle Http Client to transmit.
class MyClient extends AbstractApiClient { /** * @throws TransferException */ public function send(Model $model):void { // The data will automatically be // serialized to JSON. $this->http->post('model', [ 'data' => $model ]); } /** * @param int $id * @throws TransferException * @returns Model */ public function get(int $id):Model { $response = $this->http->get('model/'.$id, [ 'deserialize_to' => Model::class ]); if (!$response instanceof DeserializedResponse) { throw new \RuntimeException('Expected a DeserializedResponse, got: '.get_class($response)); } return $response->getDeserializedData(); } }
All functionality is implemented as middleware, the
AbstractApiClient just configures the Guzzle HandlerStack for you.
Provided middleware
Serialization
See DeserializeResponseMiddleware and SerializeRequestBodyMiddleware.
Server error messages
ServerMessageMiddleware provides support for JSON error messages.
Response expectations
If you want to make sure that a response has a specific header, content
type or other feature, use ResponseExpectationMiddleware.
Logging
There is also middleware to log all HTTP requests (and corresponding
response or exception), see HttpLoggingMiddleware
An adapter for Psr\Log\LoggerInterface is available.
This middleware is not added by default because the order is
important: The HttpLoggingMiddleware must be added last.