JSON-RPC Generator API Reference

Technical documentation for developers integrating JSON-RPC generation capabilities into their applications

On this page

Need to generate JSON-RPC?

Try our interactive generator tool for quick JSON-RPC creation.

Try Generator Tool

Overview

The JSON-RPC Generator API is a powerful library that allows developers to programmatically generate valid JSON-RPC 1.0 and 2.0 messages. It provides a simple, intuitive interface for creating requests, responses, notifications, and batch operations that conform to the official specification.

This API can be integrated into both client-side and server-side JavaScript applications, making it versatile for various use cases including testing, development, and production environments.

Installation

The Generator API can be installed via npm:

npm install @jsonrpc-tools/generator

Or included via CDN:

<script src="https://cdn.jsonrpc.dev/generator/v1/generator.min.js"></script>

API Reference

Core Methods

createRequest(method, params, id, options)

Creates a JSON-RPC request object.

Parameters:

  • method (String): The name of the method to be invoked
  • params (Array|Object, optional): Parameters to pass to the method
  • id (String|Number, optional): Request identifier
  • options (Object, optional): Generation options

Returns:

A valid JSON-RPC request object

createResponse(result, id, options)

Creates a JSON-RPC success response object.

Parameters:

  • result (Any): The result value
  • id (String|Number): Request identifier matching the original request
  • options (Object, optional): Generation options

Returns:

A valid JSON-RPC response object

createErrorResponse(error, id, options)

Creates a JSON-RPC error response object.

Parameters:

  • error (Object): Error object with code, message, and optional data
  • id (String|Number|null): Request identifier matching the original request
  • options (Object, optional): Generation options

Returns:

A valid JSON-RPC error response object

createNotification(method, params, options)

Creates a JSON-RPC notification (a request without an ID).

Parameters:

  • method (String): The name of the method to be invoked
  • params (Array|Object, optional): Parameters to pass to the method
  • options (Object, optional): Generation options

Returns:

A valid JSON-RPC notification object

createBatch(items, options)

Creates a JSON-RPC batch request or response.

Parameters:

  • items (Array): Array of request or response objects
  • options (Object, optional): Generation options

Returns:

A valid JSON-RPC batch array

Request Generator

The request generator allows you to create valid JSON-RPC request objects with various parameter types.

Example: Creating Requests

// Import the generator
import { createRequest } from '@jsonrpc-tools/generator';

// Create a request with positional parameters
const requestWithPositionalParams = createRequest(
  'subtract', 
  [42, 23], 
  1, 
  { version: '2.0' }
);
console.log(requestWithPositionalParams);
// Output: { jsonrpc: '2.0', method: 'subtract', params: [42, 23], id: 1 }

// Create a request with named parameters
const requestWithNamedParams = createRequest(
  'subtract', 
  { minuend: 42, subtrahend: 23 }, 
  2, 
  { version: '2.0' }
);
console.log(requestWithNamedParams);
// Output: { jsonrpc: '2.0', method: 'subtract', params: { minuend: 42, subtrahend: 23 }, id: 2 }

// Create a request with string ID
const requestWithStringId = createRequest(
  'getUser', 
  { userId: 123 }, 
  'user-req-1', 
  { version: '2.0' }
);
console.log(requestWithStringId);
// Output: { jsonrpc: '2.0', method: 'getUser', params: { userId: 123 }, id: 'user-req-1' }

Response Generator

The response generator enables you to create both success and error responses that comply with the JSON-RPC specification.

Example: Creating Responses

// Import the generator
import { createResponse, createErrorResponse } from '@jsonrpc-tools/generator';

// Create a success response
const successResponse = createResponse(
  19, // result
  1,  // id matching the original request
  { version: '2.0' }
);
console.log(successResponse);
// Output: { jsonrpc: '2.0', result: 19, id: 1 }

// Create an error response
const errorResponse = createErrorResponse(
  { 
    code: -32602, 
    message: 'Invalid params',
    data: { details: 'Parameter "userId" must be a number' }
  },
  2, // id matching the original request
  { version: '2.0' }
);
console.log(errorResponse);
/* Output: 
{
  jsonrpc: '2.0',
  error: {
    code: -32602,
    message: 'Invalid params',
    data: { details: 'Parameter "userId" must be a number' }
  },
  id: 2
}
*/

// Create a response for a request that produced a parsing error
const parseErrorResponse = createErrorResponse(
  { 
    code: -32700, 
    message: 'Parse error'
  },
  null, // null ID for parse errors
  { version: '2.0' }
);
console.log(parseErrorResponse);
// Output: { jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null }

Batch Generator

The JSON-RPC 2.0 specification allows for batching multiple requests or responses in a single message.

Example: Creating Batch Requests

// Import the generator
import { createRequest, createNotification, createBatch } from '@jsonrpc-tools/generator';

// Create individual requests
const request1 = createRequest('sum', [1, 2, 3], 1, { version: '2.0' });
const request2 = createRequest('subtract', [42, 23], 2, { version: '2.0' });
const notification = createNotification('log', { message: 'Processing batch' }, { version: '2.0' });

// Combine into a batch
const batchRequest = createBatch([request1, request2, notification], { version: '2.0' });
console.log(JSON.stringify(batchRequest, null, 2));
/* Output:
[
  {
    "jsonrpc": "2.0",
    "method": "sum",
    "params": [1, 2, 3],
    "id": 1
  },
  {
    "jsonrpc": "2.0",
    "method": "subtract",
    "params": [42, 23],
    "id": 2
  },
  {
    "jsonrpc": "2.0",
    "method": "log",
    "params": { "message": "Processing batch" }
  }
]
*/

Example: Creating Batch Responses

// Import the generator
import { createResponse, createErrorResponse, createBatch } from '@jsonrpc-tools/generator';

// Create individual responses
const response1 = createResponse(6, 1, { version: '2.0' }); // response to 'sum'
const response2 = createResponse(19, 2, { version: '2.0' }); // response to 'subtract'

// Combine into a batch response
const batchResponse = createBatch([response1, response2], { version: '2.0' });
console.log(JSON.stringify(batchResponse, null, 2));
/* Output:
[
  {
    "jsonrpc": "2.0",
    "result": 6,
    "id": 1
  },
  {
    "jsonrpc": "2.0",
    "result": 19,
    "id": 2
  }
]
*/

Templates

The Generator API includes built-in templates for common JSON-RPC message types.

Available Templates

Standard Error Templates

Predefined templates for standard JSON-RPC error responses:

  • Parse Error (-32700)
  • Invalid Request (-32600)
  • Method Not Found (-32601)
  • Invalid Params (-32602)
  • Internal Error (-32603)

Example Usage of Templates

import { templates } from '@jsonrpc-tools/generator';

// Create an Invalid Method error response
const errorResponse = templates.errors.methodNotFound(1);
console.log(errorResponse);
/* Output:
{
  jsonrpc: '2.0',
  error: {
    code: -32601,
    message: 'Method not found'
  },
  id: 1
}
*/

Complete Example

Building a JSON-RPC Client

import { createRequest, createBatch } from '@jsonrpc-tools/generator';

class JsonRpcClient {
  constructor(endpoint) {
    this.endpoint = endpoint;
    this.requestId = 1;
  }

  async callMethod(method, params) {
    const request = createRequest(
      method,
      params,
      this.requestId++,
      { version: '2.0' }
    );
    
    return this._sendRequest(request);
  }
  
  async callBatch(calls) {
    const requests = calls.map(call => {
      return createRequest(
        call.method,
        call.params,
        this.requestId++,
        { version: '2.0' }
      );
    });
    
    const batchRequest = createBatch(requests, { version: '2.0' });
    return this._sendRequest(batchRequest);
  }
  
  async _sendRequest(requestData) {
    try {
      const response = await fetch(this.endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });
      
      const data = await response.json();
      
      // Handle errors in response
      if (!Array.isArray(data) && data.error) {
        throw new Error(`${data.error.code}: ${data.error.message}`);
      }
      
      return data;
    } catch (error) {
      console.error('RPC call failed:', error);
      throw error;
    }
  }
}

// Example usage
const client = new JsonRpcClient('https://api.example.com/jsonrpc');

// Single method call
client.callMethod('getUserById', { id: 123 })
  .then(response => console.log('User:', response.result))
  .catch(error => console.error('Error:', error));

// Batch call
client.callBatch([
  { method: 'getUserById', params: { id: 123 } },
  { method: 'getPostsByUser', params: { userId: 123, limit: 5 } }
])
  .then(responses => {
    console.log('User:', responses[0].result);
    console.log('Posts:', responses[1].result);
  })
  .catch(error => console.error('Error:', error));