JSON-RPC Code Generator API Reference
Technical documentation for integrating code generation capabilities for JSON-RPC into your applications
On this page
Need to generate code?
Try our interactive code generator tool for quick implementation.
Try Code GeneratorOverview
The JSON-RPC Code Generator API provides programmatic access to generate client and server code for JSON-RPC implementations in various programming languages. This powerful library translates JSON-RPC interface definitions into idiomatic, production-ready code that adheres to best practices for each supported language.
The API is language-agnostic at its core, with dedicated language modules that handle the specifics of code generation for each target language.
Installation
The Code Generator API can be installed via npm:
npm install @jsonrpc-tools/code-generator
For specific language support, install the corresponding plugin:
npm install @jsonrpc-tools/code-generator-typescript npm install @jsonrpc-tools/code-generator-python # Additional language plugins as needed
Core Functions
generateCode(schema, options)
The primary function for generating code from a JSON-RPC interface schema.
Parameters:
schema
(Object): JSON-RPC interface definitionoptions
(Object): Configuration options for code generation
Returns:
An object containing generated code files, with file paths as keys and file content as values
parseSchema(schema)
Parses and validates a JSON-RPC interface schema.
Parameters:
schema
(Object|String): JSON-RPC interface definition
Returns:
A parsed and normalized schema object ready for code generation
getSupportedLanguages()
Returns an array of supported programming languages.
Returns:
Array of language identifiers that are currently supported
Language Generation
The API provides language-specific generators for creating idiomatic code in various programming languages.
Supported Languages
Language-Specific Generation
// Import the generator import { generateCode } from '@jsonrpc-tools/code-generator'; // Generate TypeScript client code const tsCode = generateCode(schema, { language: 'typescript', target: 'client', options: { framework: 'axios', outputStyle: 'es6', generateTypes: true } }); // Generate Python server code const pythonCode = generateCode(schema, { language: 'python', target: 'server', options: { framework: 'flask', asyncMode: true, docstringFormat: 'google' } });
Code Templates
The API uses customizable templates for generating code in different languages.
You can use default templates, customize them, or provide your own:
// Using default templates const code = generateCode(schema, { language: 'typescript' }); // Customizing templates const code = generateCode(schema, { language: 'typescript', templates: { // Override specific templates client: '{{customTemplate}}', method: '{{customMethodTemplate}}' } }); // Getting built-in templates for customization import { getTemplates } from '@jsonrpc-tools/code-generator'; const tsTemplates = getTemplates('typescript'); // Modify templates... const code = generateCode(schema, { language: 'typescript', templates: modifiedTemplates });
Configuration
Configure the code generator to suit your specific needs.
Common Options
language
: Target programming languagetarget
: 'client', 'server', or 'both'outputStyle
: Code style/formatnamingConvention
: Case style for generated code
Structure Options
moduleType
: Module system to use (e.g., 'commonjs', 'esm')packageName
: Package/namespace namefileStructure
: How to organize generated files
Framework Options
framework
: Framework to target (e.g., 'axios', 'fetch', 'flask')dependencies
: External dependencies to use
Complete Example
Generating a TypeScript Client
import { generateCode } from '@jsonrpc-tools/code-generator'; // Define your JSON-RPC API schema const schema = { methods: [ { name: 'getUserById', description: 'Retrieves a user by their ID', params: { id: { type: 'number', description: 'User ID' } }, returns: { type: 'object', properties: { id: { type: 'number' }, name: { type: 'string' }, email: { type: 'string' } } } }, { name: 'createUser', description: 'Creates a new user', params: { user: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' } } } }, returns: { type: 'object', properties: { id: { type: 'number' }, name: { type: 'string' }, email: { type: 'string' } } } } ] }; // Generate TypeScript client code const generatedCode = generateCode(schema, { language: 'typescript', target: 'client', options: { framework: 'axios', outputStyle: 'es6', generateTypes: true, packageName: 'user-api-client', errorHandling: 'throw', includeDocComments: true } }); // Output the generated code for (const [filename, content] of Object.entries(generatedCode)) { console.log(`\n--- ${filename} ---\n`); console.log(content); } // Example output for userApiClient.ts: /* import axios from 'axios'; /** * User data structure */ export interface User { id: number; name: string; email: string; } /** * Input for creating a new user */ export interface CreateUserInput { name: string; email: string; } /** * Client for the User API */ export class UserApiClient { private endpoint: string; private requestId: number; constructor(endpoint: string) { this.endpoint = endpoint; this.requestId = 1; } /** * Retrieves a user by their ID * @param id User ID * @returns The user data */ async getUserById(id: number): Promise<User> { const response = await this.sendRequest('getUserById', { id }); return response.result; } /** * Creates a new user * @param user User data to create * @returns The created user */ async createUser(user: CreateUserInput): Promise<User> { const response = await this.sendRequest('createUser', { user }); return response.result; } private async sendRequest(method: string, params: any) { try { const response = await axios.post(this.endpoint, { jsonrpc: '2.0', method, params, id: this.requestId++ }); const data = response.data; if (data.error) { throw new Error(`${data.error.code}: ${data.error.message}`); } return data; } catch (error) { throw error; } } } */