eugenejenkins/json-rpc-server

A lightweight JSON-RPC server implementation in PHP.

v1.0.0 2024-10-05 23:27 UTC

This package is auto-updated.

Last update: 2025-01-06 00:09:40 UTC


README

This project is a JSON-RPC server implemented in PHP 8.1. It adheres to the JSON-RPC 2.0 specification (RFC 7049). The server is built in a canonical way, following best practices for handling JSON-RPC requests.

Features

  • Complies with the JSON-RPC 2.0 standard.
  • Supports method registration and execution.
  • Structured exception handling for request processing.

Requirements

  • PHP 8.1 or higher
  • Composer

Installation

  1. Clone the repository:

    git clone git@github.com:EugeneJenkins/json-rpc-server.git
    cd json-rpc-server
  2. Install dependencies::

    composer install

Example Usage

$server = new Server;

$server->register('subtract', fn($minuend, $subtrahend) => $minuend - $subtrahend);
$server->register('add', fn($a, $b) => $a + $b);

$server->registerClass(Calculator::class);

$response = $server->execute();
$response->show();

To run the server locally, you can use the built-in PHP server:

php -S localhost:8008 index.php

How to Make Requests

You can send JSON-RPC requests to the server using any HTTP client (e.g., curl, Postman, etc.).

Example request:

curl -X POST http://localhost:8008 \
    -H "Content-Type: application/json" \
    -d '{
        "jsonrpc": "2.0",
        "method": "subtract",
        "params": {"minuend": 10, "subtrahend": 3},
        "id": 1
    }'

Example response:

{
    "jsonrpc": "2.0",
    "result": {
        "minuend": 10,
        "subtrahend": 3
    },
    "id": 1
}

Error Handling

If an error occurs during the execution of a request, the server will respond with a JSON-RPC error object, as specified in the JSON-RPC 2.0 specification.