Files
restclient/README.md
2024-09-13 21:48:43 +00:00

4.3 KiB

RestClient

The RestClient is a versatile PHP class for making HTTP requests using cURL, with support for handling JSON responses, custom headers, file downloads, and cookies.

Features

  • Supports GET, POST, PUT, DELETE HTTP methods
  • Handles JSON requests and responses
  • Supports custom headers and user-agent strings
  • Maintains session using cookies (optional)
  • Can download files
  • Throws exceptions for HTTP errors (configurable)
  • Retrieves HTTP response codes

Installation

To use the RestClient class in your PHP project:

Setup this registry in your ~/.composer/config.json file:

{
	"repositories": [{
			"type": "composer",
			"url": "https://git.hpz.pw/api/packages/hpz937/composer"
		}
	]
}

To install the package using Composer, run the following command:

composer require hpz937/restclient

Usage

Basic Usage

You can start by creating an instance of RestClient and configuring options such as base URL, headers, or whether to use cookies.

use Hpz937\Restclient\RestClient;

$client = new RestClient();
$client->setBaseUrl('https://api.example.com');

HTTP GET Request

Perform a simple GET request to an API endpoint.

$response = $client->get('/endpoint')
                   ->getResponse();

echo $response;

HTTP POST Request

Send data to the API using a POST request.

$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com',
];

$response = $client->post('/endpoint', $data)
                   ->getResponse();

echo $response;

HTTP PUT Request

Update resources using a PUT request.

$data = [
    'name' => 'Jane Doe',
];

$response = $client->put('/endpoint/123', $data)
                   ->getResponse();

echo $response;

HTTP DELETE Request

Delete a resource using a DELETE request.

$response = $client->delete('/endpoint/123')
                   ->getResponse();

echo $response;

Handling JSON Responses

To handle JSON responses, you can use the decodeJson method to convert the response into an associative array.

$response = $client->get('/endpoint')
                   ->decodeJson();

print_r($response);

Custom Headers

You can set custom headers for your requests.

$headers = [
    'Authorization: Bearer YOUR_TOKEN',
    'Accept: application/json',
];

$client->setHeaders($headers);

Setting User-Agent

Set a custom User-Agent string for the requests.

$client->setUserAgent('MyCustomUserAgent/1.0');

File Downloads

You can download files using the download method. Make sure to specify the filename where the file will be saved.

$client->download('/path/to/file.jpg', '/local/path/to/save/file.jpg')
       ->get('/endpoint/download-file');

echo "File downloaded successfully!";

Using Cookies

Enable cookies to maintain session data between requests.

$client->setUseCookies(true);

Exception Handling for HTTP Errors

By default, the RestClient throws exceptions when HTTP errors (4xx, 5xx) occur. You can handle these exceptions as follows:

try {
    $client->get('/invalid-endpoint')
           ->getResponse();
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Getting the HTTP Response Code

Retrieve the HTTP response code from the most recent request.

$responseCode = $client->getResponseCode();

echo "HTTP Response Code: $responseCode";

Example Workflow

use Hpz937\Restclient\RestClient;

$client = new RestClient();
$client->setBaseUrl('https://api.example.com')
       ->setUserAgent('MyApp/1.0')
       ->setHeaders([
           'Authorization: Bearer YOUR_API_KEY',
           'Content-Type: application/json',
       ])
       ->setUseCookies(true);

try {
    // GET request example
    $response = $client->get('/users')
                       ->decodeJson();
    print_r($response);
    
    // POST request example
    $data = ['name' => 'New User'];
    $response = $client->post('/users', $data)
                       ->getResponse();
    echo $response;
    
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}

License

This project is licensed under the MIT License. See the LICENSE file for details.


This `README.md` provides an overview of the class, installation instructions, and usage examples for each of the key methods in your `RestClient` class.