Declarative HTTP Clients using Guzzle HTTP Library and PHP 8 Attributes

Overview

Build License Total Downloads

Waffler


How to install?

$ composer require waffler/waffler
  • This package requires PHP 8 or above.

How to test?

$ composer phpunit

Quick start

For our example, lets imagine that we want to consume an ordinary API: https://foo-bar.baz/api

Our objectives are:

  • Perform the login to retrieve the authorization token.
  • Retrieve all posts from the database.

Step 1: Create the basic interface for your client.

<?php // FooClient.php

namespace App\Clients;

interface FooClient
{
    /**
     * Retrieve authorization token.
     *
     * @param array $credentials Just pass the login and password.
     * @return array             The json response.
     */
    public function login(array $credentials): array;

    /**
     * Retrieve all posts.
     *
     * @param string $authToken The authorization token.
     * @param array $query      Some optional query string Filters.
     * @return array            The list of posts.
     */
    public function getPosts(string $authToken, array $query = []): array:
}

Step 2: Annotate the methods with Waffler Attributes.

The magic is almost done. Now we need to annotate the methods and parameters to "teach" Waffler how to make the requests. There are dozens of Attributes, but for this example we just need 5 of them.

Import the Attributes from the Waffler\Waffler\Attributes namespace.

<?php // FooClient.php

namespace App\Clients;

use Waffler\Waffler\Attributes\Auth\Bearer;
use Waffler\Waffler\Attributes\Request\Json;
use Waffler\Waffler\Attributes\Request\Post;
use Waffler\Waffler\Attributes\Request\Query;
use Waffler\Waffler\Attributes\Verbs\Get;

interface FooClient
{
    /**
     * Retrieve authorization token.
     *
     * @param array $credentials Just pass the login and password.
     * @return array             The json response.
     */
    #[Post('/auth/login')]
    public function login(#[Json] array $credentials): array;

    /**
     * Retrieve all posts.
     *
     * @param string $authToken The authorization token.
     * @param array $query      Some optional query string Filters.
     * @return array            The list of posts.
     */
    #[Get('/posts')]
    public function getPosts(#[Bearer] string $authToken, #[Query] array $query = []): array:
}

Step 3: Generate the implementation for your interface and use it.

Import the class Waffler\Waffler\Client\Factory and call the static method make passing the fully qualified name of the interface we just created as first argument and an associative array of GuzzleHttp client options as second argument.

<?php

namespace App;

use App\Clients\FooClient;
use Waffler\Waffler\Client\Factory;

// Instantiate the client passing the interface as first argument.
$fooClient = Factory::make(FooClient::class, ['base_uri' => '<api-base-uri>']);

// Retrieve the credentials
$credentials = $this->fooClient->login([
    'email' => '[email protected]',
    'password' => '<secret>'
]);

// Retrieve the posts.
$posts = $this->fooClient->getPosts($credentials['token'], ['created_at' => '2020-01-01'])

Usage examples

See the Examples folder.

Attributes docs

See the wiki for more information about the Attributes.

You might also like...
Unirest in PHP: Simplified, lightweight HTTP client library.

Unirest for PHP Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the

Requests - a HTTP library written in PHP, for human beings

Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python library. Requests is ISC Licensed (similar to the new BSD license) and has no dependencies, except for PHP 5.6+.

LittleProxy is a high performance HTTP proxy written in Java atop Trustin Lee's excellent Netty event-based networking library

LittleProxy is a high performance HTTP proxy written in Java atop Trustin Lee's excellent Netty event-based networking library

PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs
PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs

PHP Curl Class: HTTP requests made easy PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs. Installation Requirements Quic

A simple PHP Toolkit to parallel generate combinations, save and use the generated terms to brute force attack via the http protocol.
A simple PHP Toolkit to parallel generate combinations, save and use the generated terms to brute force attack via the http protocol.

Brutal A simple PHP Toolkit to parallel generate combinations, save and use the generated terms to apply brute force attack via the http protocol. Bru

Composer package providing HTTP Methods, Status Codes and Reason Phrases for PHP

HTTP Enums For PHP 8.1 and above This package provides HTTP Methods, Status Codes and Reason Phrases as PHP 8.1+ enums All IANA registered HTTP Status

HTTP header kit for PHP 7.1+ (incl. PHP 8) based on PSR-7

HTTP header kit for PHP 7.1+ (incl. PHP 8) based on PSR-7 Installation composer require sunrise/http-header-kit How to use? HTTP Header Collection Mor

Express.php is a new HTTP - Server especially made for RESTful APIs written in PHP.

express.php Express.php is a new HTTP - Server especially made for RESTful APIs written in PHP. Features Fast The Library is handles requests fast and

Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.
Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.

This is a port of the VCR Ruby library to PHP. Record your test suite's HTTP interactions and replay them during future test runs for fast, determinis

Releases(1.1.1)
Owner
Waffler
Waffler
Guzzle, an extensible PHP HTTP client

Guzzle, PHP HTTP client Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interf

Guzzle 22.3k Jan 2, 2023
A HTTP Cache for Guzzle 6. It's a simple Middleware to be added in the HandlerStack.

A HTTP Cache for Guzzle 6. It's a simple Middleware to be added in the HandlerStack.

Kevin Robatel 371 Dec 17, 2022
Supercharge your app or SDK with a testing library specifically for Guzzle

Full Documentation at guzzler.dev Supercharge your app or SDK with a testing library specifically for Guzzle. Guzzler covers the process of setting up

null 275 Oct 30, 2022
Server emulator for the Hasbro Em@il Games clients

HasbroPBEMProxy Greg Kennedy, 2021 Server emulator for the Hasbro Em@il Games clients About In 1999 Hasbro launched a series of games under the "Em@il

Greg Kennedy 4 Dec 20, 2022
🐼 Framework agnostic package using asynchronous HTTP requests and PHP generators to load paginated items of JSON APIs into Laravel lazy collections.

Framework agnostic package using asynchronous HTTP requests and generators to load paginated items of JSON APIs into Laravel lazy collections.

Andrea Marco Sartori 61 Dec 3, 2022
A simple yet powerful HTTP metadata and assets provider for NFT collections using Symfony

Safe NFT Metadata Provider A simple yet powerful HTTP metadata and assets provider for NFT collections using Symfony.

HashLips Lab 66 Oct 7, 2022
PHP Curl - This package can send HTTP requests to a given site using Curl.

PHP Curl This package can send HTTP requests to a given site using Curl. It provides functions that can take several types of parameters to configure

Mehmet Can 1 Oct 27, 2022
Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

null 3.5k Dec 31, 2022
Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

null 3.5k Dec 31, 2022
The Library for HTTP Status Codes, Messages and Exception

This is a PHP library for HTTP status codes, messages and error exception. Within the library, HTTP status codes are available in classes based on the section they belong to. Click this link for more information.

Sabuhi Alizada 5 Sep 14, 2022