PHP code example of laybot / request-sdk

1. Go to this page and download the library: Download laybot/request-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laybot / request-sdk example snippets


$http->request(...);
$http->streamSse(...);
$http->streamJsonLines(...);
$http->streamRaw(...);

$http->requestAsync(...);
$http->streamSseAsync(...);
$http->streamJsonLinesAsync(...);
$http->streamRawAsync(...);
$http->connectWebSocketAsync(...);



use LayBot\Request\Client;

$http = Client::make([
    'base_uri' => 'https://api.example.com',

    'retry' => false,

    'timeouts' => [
        'connect' => 10,
        'request' => 30,
        'idle' => 180,
    ],
]);

$result = $http->get('/users', [
    'page' => 1,
    'limit' => 20,
]);

var_dump($result);

$result = $http->getAny('/value');

$result = $http->postJson('/orders', [
    'product_id' => 1001,
    'quantity' => 2,
]);

$result = $http->postForm('/oauth/token', [
    'grant_type' => 'client_credentials',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
]);

$response = $http->request('POST', '/jobs', [
    'query' => [
        'source' => 'admin',
    ],
    'headers' => [
        'X-Request-Source' => 'console',
    ],
    'json' => [
        'name' => 'demo-job',
    ],
]);

LayBot\Request\DTO\Response

echo $response->status;
echo $response->body;
echo $response->durationMs;
echo $response->attempts;
echo $response->protocolVersion;

$requestId = $response->requestId();
$traceId = $response->traceId();

$array = $response->jsonArray();
$mixed = $response->jsonAny();



namespace app\service;

use LayBot\Request\Client;

final class PartnerApiService
{
    private Client $http;

    public function __construct()
    {
        $this->http = Client::make([
            'base_uri' => 'https://api.example.com',
            'token' => getenv('PARTNER_API_TOKEN'),
            'retry' => false,
            'timeouts' => [
                'connect' => 5,
                'request' => 30,
                'idle' => 120,
            ],
        ]);
    }

    public function users(int $page = 1): array
    {
        return $this->http->get('/users', [
            'page' => $page,
        ]);
    }
}

use LayBot\Request\Client;

$http = Client::make([
    'base_uri' => config('services.partner.base_uri'),
    'token' => config('services.partner.token'),
]);

$result = $http->get('/users');

use LayBot\Request\Client;

$http = Client::make([
    'base_uri' => $_ENV['PARTNER_BASE_URI'],
    'token' => $_ENV['PARTNER_API_TOKEN'],
]);

$result = $http->get('/users');

use LayBot\Request\Client;

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'token' => getenv('API_TOKEN'),
]);

$result = $http->get('/users');



ayBot\Request\Client;

$http = Client::make([
    'base_uri' => 'https://api.example.com',
]);

print_r($http->get('/status'));

$response = $http->request('POST', '/data', [
    'json' => [
        'name' => 'LayBot',
    ],
]);

$response = $http->request('POST', '/form', [
    'form_params' => [
        'name' => 'LayBot',
    ],
]);

$response = $http->request('POST', '/xml', [
    'headers' => [
        'Content-Type' => 'application/xml',
    ],
    'body' => '<root><name>LayBot</name></root>',
]);

$stream = fopen(__DIR__ . '/demo.txt', 'rb');

try {
    $response = $http->request('POST', '/upload', [
        'multipart' => [
            [
                'name' => 'file',
                'contents' => $stream,
                'filename' => 'demo.txt',
            ],
            [
                'name' => 'scene',
                'contents' => 'document',
            ],
        ],
        'retry' => false,
    ]);
} finally {
    if (is_resource($stream)) {
        fclose($stream);
    }
}

$http->send(...);
$http->requestJsonArray(...);
$http->get(...);
$http->postJson(...);
$http->postForm(...);
$http->post(...);
$http->put(...);
$http->patch(...);
$http->delete(...);

$http->sendAny(...);
$http->requestJsonAny(...);
$http->getAny(...);
$http->postJsonAny(...);
$http->postFormAny(...);
$http->postAny(...);
$http->putAny(...);
$http->patchAny(...);
$http->deleteAny(...);

$response = $http->request('GET', '/data');

$raw = $http->requestRaw('GET', '/data');

/*
[
    'status' => 200,
    'headers' => [...],
    'body' => '...',
]
*/

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'headers' => [
        'X-App-Name' => 'admin-service',
    ],
]);

'custom_headers' => [
    'X-App-Name' => 'admin-service',
],

$response = $http->request('GET', '/users', [
    'headers' => [
        'X-Tenant-Id' => 'tenant-1001',
    ],
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'token' => getenv('API_TOKEN'),
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'api_key' => getenv('API_KEY'),
    'header' => 'X-API-Key',
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'username' => 'username',
    'password' => 'password',
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'api_key' => getenv('API_KEY'),
    'api_secret' => getenv('API_SECRET'),
]);

$http = Client::make([
    'base_uri' => 'https://internal.example.com',
    'inner_token' => getenv('INNER_TOKEN'),
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',

    'token' => getenv('BEARER_TOKEN'),

    'custom_headers' => [
        'X-Export-Token' => getenv('EXPORT_TOKEN'),
        'X-Service-Name' => 'paper-export',
    ],
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'query_array_format' => 'repeat',
]);

$response = $http->request('GET', '/users', [
    'query' => [
        'ids' => [1, 2],
    ],
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',

    'timeouts' => [
        'connect' => 10,
        'request' => 30,
        'idle' => 180,
    ],
]);

$response = $http->request('GET', '/slow', [
    'connect_timeout' => 5,
    'request_timeout' => 60,
    'idle_timeout' => 30,
]);

[
    'connect_timeout' => 10,
    'request_timeout' => 0,
    'idle_timeout' => 120,
]

'retry' => false

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'retry' => 2,
]);

$http = Client::make([
    'base_uri' => 'https://api.example.com',

    'retry' => [
        'max_attempts' => 3,
        'base_delay_ms' => 200,
        'max_delay_ms' => 5000,
        'jitter_ms' => 100,
        'retry_statuses' => [
            429,
            502,
            503,
            504,
        ],
        'safe_methods_only' => true,
    ],
]);

$response = $http->request('POST', '/jobs', [
    'idempotent' => true,
    'retry' => [
        'max_attempts' => 3,
    ],
    'json' => [
        'request_id' => 'unique-business-id',
    ],
]);

use LayBot\Request\DTO\SseEvent;

$result = $http->streamSse(
    'POST',
    '/v1/events',
    [
        'headers' => [
            'Accept' => 'text/event-stream',
        ],
        'json' => [
            'stream' => true,
        ],
        'request_timeout' => 0,
        'idle_timeout' => 120,
    ],
    static function (SseEvent $event): void {
        if ($event->comment) {
            return;
        }

        echo $event->data;
    },
    '[DONE]'
);

$handle = $http->streamSseAsync(
    'POST',
    '/v1/events',
    [
        'json' => [
            'stream' => true,
        ],
        'request_timeout' => 0,
        'idle_timeout' => 120,
    ],
    static function ($head): void {
        echo 'HTTP status: ', $head->status, PHP_EOL;
    },
    static function ($event): void {
        if (!$event->comment) {
            echo $event->data;
        }
    },
    static function ($result): void {
        echo $result->termination->value;
    },
    static function (\Throwable $error): void {
        echo $error->getMessage();
    },
    '[DONE]'
);

use LayBot\Request\DTO\JsonLine;

$result = $http->streamJsonLines(
    'GET',
    '/v1/logs',
    [
        'request_timeout' => 0,
        'idle_timeout' => 60,
    ],
    static function (JsonLine $line): void {
        var_dump($line->value);
    }
);

$result = $http->streamRaw(
    'GET',
    '/audio',
    [
        'request_timeout' => 0,
        'idle_timeout' => 60,
    ],
    static function (string $chunk): bool {
        echo strlen($chunk), PHP_EOL;

        return true;
    }
);

$http->stream(
    '/v1/stream',
    [
        'input' => 'hello',
        'stream' => true,
    ],
    static function (
        string $data,
        bool $done
    ): void {
        if ($done) {
            echo '[DONE]';
            return;
        }

        echo $data;
    }
);

streamSse()
streamJsonLines()
streamRaw()

use LayBot\Request\Client;
use LayBot\Request\DTO\Response;
use Workerman\Worker;

$worker = new Worker();

$worker->onWorkerStart = static function (): void {
    $http = Client::make([
        'base_uri' => 'https://api.example.com',
        'retry' => false,
    ]);

    $http->requestAsync(
        'GET',
        '/users',
        [],
        static function (Response $response): void {
            var_dump($response->jsonArray());
        },
        static function (\Throwable $error): void {
            echo $error->getMessage();
        }
    );
};

Worker::runAll();

Worker::runAll();

$handle = $http->requestAsync(
    'GET',
    '/slow',
    [],
    $onComplete,
    $onError
);

$handle->cancel('user cancelled');

use LayBot\Request\Stream\CancellationSource;

$source = new CancellationSource();

$handle = $http->requestAsync(
    'GET',
    '/slow',
    [
        'cancellation' => $source->token(),
    ],
    $onComplete,
    $onError
);

$source->cancel('user stopped');

use LayBot\Request\Contract\WebSocketConnectionInterface;
use LayBot\Request\DTO\WebSocketCloseInfo;
use LayBot\Request\DTO\WebSocketOpenInfo;
use LayBot\Request\DTO\WebSocketRequest;
use LayBot\Request\Stream\WebSocketListener;

$listener = new class extends WebSocketListener {
    public function onOpen(
        WebSocketConnectionInterface $connection,
        WebSocketOpenInfo $info
    ): void {
        $connection->sendText('hello');
    }

    public function onText(
        WebSocketConnectionInterface $connection,
        string $payload
    ): void {
        echo $payload;
    }

    public function onBinary(
        WebSocketConnectionInterface $connection,
        string $payload
    ): void {
        echo 'Binary bytes: ', strlen($payload);
    }

    public function onClose(
        WebSocketConnectionInterface $connection,
        WebSocketCloseInfo $info
    ): void {
        printf(
            "Closed: %d %s\n",
            $info->code,
            $info->reason
        );
    }

    public function onError(
        WebSocketConnectionInterface $connection,
        \Throwable $error
    ): void {
        echo $error->getMessage();
    }
};

$connection = $http->connectWebSocketAsync(
    new WebSocketRequest(
        url: 'wss://api.example.com/realtime',
        connectTimeout: 10,
        idleTimeout: 120,
        pingInterval: 30,
        closeTimeout: 5,
        maxMessageBytes: 16 * 1024 * 1024
    ),
    $listener
);

$connection->sendText('hello');
$connection->sendBinary($binary);
$connection->ping('heartbeat');
$connection->close(1000, 'finished');
$connection->cancel('cancelled');

$request = new WebSocketRequest(
    url: 'wss://api.example.com/realtime',
    lowWaterMark: 1 * 1024 * 1024,
    highWaterMark: 4 * 1024 * 1024,
    hardBufferLimit: 16 * 1024 * 1024
);

public function onBufferFull(
    WebSocketConnectionInterface $connection
): void {
    // 暂停上游数据生产。
}

public function onBufferDrain(
    WebSocketConnectionInterface $connection
): void {
    // 恢复上游数据生产。
}

BackpressureException

$result = $http->upload(
    '/files',
    'file',
    __DIR__ . '/demo.pdf',
    [
        'scene' => 'document',
    ],
    [
        'X-Tenant-Id' => 'tenant-1001',
    ]
);

$path = $http->download(
    '/files/demo.pdf',
    __DIR__ . '/runtime/demo.pdf',
    query: [],
    headers: [],
    maxBytes: 512 * 1024 * 1024
);

$handle = $http->downloadAsync(
    path: '/files/demo.pdf',
    saveTo: __DIR__ . '/runtime/demo.pdf',
    query: [],
    headers: [],
    onComplete: static function (string $path): void {
        echo $path;
    },
    onError: static function (\Throwable $error): void {
        echo $error->getMessage();
    },
    maxBytes: 512 * 1024 * 1024
);

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'proxy' => 'http://127.0.0.1:8080',
]);

$response = $http->request('GET', '/data', [
    'proxy' => 'http://127.0.0.1:8081',
]);

'verify' => true

$http = Client::make([
    'base_uri' => 'https://localhost:8443',
    'verify' => false,
]);

$response = $http->request(
    'GET',
    'https://other.example.com/data',
    [
        'allow_cross_origin' => true,
    ]
);

[
    'allow_cross_origin' => true,
    'forward_cross_origin_credentials' => true,
]

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'logger' => $logger,
]);

$http = $http->withSensitiveHeaders([
    'X-Gateway-Credential',
    'X-Proxy-*',
]);

'log_bodies' => false

use LayBot\Request\Middleware\RetryPolicy;
use LayBot\Request\Timeout\TimeoutConfig;

$configured = $http
    ->withHeaders([
        'X-App-Name' => 'admin-service',
    ])
    ->withTimeouts(new TimeoutConfig(
        connect: 5,
        request: 30,
        idle: 120
    ))
    ->withRetryPolicy(new RetryPolicy(
        maxAttempts: 2
    ))
    ->withVerify(true)
    ->withUserAgent('LayBot-Admin/2.0')
    ->withQueryArrayFormat('repeat')
    ->withSensitiveHeaders([
        'X-Private-*',
    ])
    ->withProxy(null);

use LayBot\Request\Exception\HttpException;
use LayBot\Request\Exception\RequestException;

try {
    $response = $http->request('GET', '/data');
} catch (HttpException $error) {
    echo $error->getStatusCode();
    echo $error->getRequestId();
} catch (RequestException $error) {
    echo $error->getMethod();
    echo $error->getUrl();
    echo $error->getMessage();
}

$http = Client::make([
    'base_uri' => 'https://api.example.com',
    'max_response_bytes' => 32 * 1024 * 1024,
]);

[
    'max_event_bytes' => 8 * 1024 * 1024,
    'max_line_bytes' => 8 * 1024 * 1024,
]

request()
send()
sendAny()
requestJsonArray()
requestJsonAny()
requestRaw()

get()
getAny()
postJson()
postJsonAny()
postForm()
postFormAny()
post()
postAny()
put()
putAny()
patch()
patchAny()
delete()
deleteAny()
head()
options()

requestAsync()

streamRaw()
streamSse()
streamJsonLines()
stream()

streamRawAsync()
streamSseAsync()
streamJsonLinesAsync()

upload()
download()
downloadAsync()

connectWebSocketAsync()

withSigner()
withLogger()
withHeaders()
withTimeout()
withTimeouts()
withVerify()
withRetry()
withRetryPolicy()
withProxy()
withUserAgent()
withQueryArrayFormat()
withSensitiveHeaders()

$response = $http->request(...);

Worker::runAll();
text
PHP 8.4
当前稳定版Webman
Workerman 5.2+
text
request_timeout=0:不限制流的总持续时间
idle_timeout=120:连续120秒无数据时中断
text
PHP 8.1
PHP 8.2
PHP 8.3
PHP 8.4