PHP code example of xpat / xpat-http

1. Go to this page and download the library: Download xpat/xpat-http 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/ */

    

xpat / xpat-http example snippets


use Xpat\Http\Request\Get;
use Xpat\Http\Request\Headers;
use Xpat\Http\Request\Url;


$response = (
    new Get(
        new Url(
            'localhost',
            8080,
            '/expense-categories'
        ),
        new Headers([
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])
    )
)->execute();

echo $response->content() . PHP_EOL;
echo $response->statusCode() . PHP_EOL;


use Xpat\Http\Request\Headers;
use Xpat\Http\Request\JsonBody;
use Xpat\Http\Request\Post;
use Xpat\Http\Request\Url;


$response = (
    new Post(
        new Url(
            'localhost',
            8080,
            '/expense-categories'
        ),
        new Headers([
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ]),
        new JsonBody([
            'name' => 'New Category',
        ])
    )
)->execute();

echo $response->content() . PHP_EOL;
echo $response->statusCode() . PHP_EOL;

use Xpat\Http\Request\Headers;
use Xpat\Http\Request\JsonBody;
use Xpat\Http\Request\Put;
use Xpat\Http\Request\Url;


$response = (
    new Put(
        new Url(
            'localhost',
            8080,
            '/expense-categories/4'
        ),
        new Headers([
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ]),
        new JsonBody([
            'id' => 4,
            'name' => 'Grocery',
        ])
    )
)->execute();

echo $response->content() . PHP_EOL;
echo $response->statusCode() . PHP_EOL;

use Xpat\Http\Request\Delete;
use Xpat\Http\Request\Headers;
use Xpat\Http\Request\Url;


$response = (
    new Delete(
        new Url(
            'localhost',
            8080,
            '/expense-categories/4'
        ),
        new Headers([
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])
    )
)->execute();

echo $response->content() . PHP_EOL;
echo $response->statusCode() . PHP_EOL;

use Xpat\Http\Json\JsonObject;


$json = new JsonObject(
    '{
        "id": 3,
        "amount": 300,
        "description": "Plain ticket",
        "date": "2024-11-27 22:47:21",
        "category": {
            "id": 2,
            "name": "Travel"
        }
    }'
);

if ($json->has('category.name')) {
    echo $json->get('category.name');
} else {
    echo 'No category name found';
}