jsonrpcserver

repository·main·Indexed 42 days ago

https://github.com/explodinglabs/jsonrpcserver

A Python library for processing incoming JSON-RPC 2.0 requests. It provides tools to define RPC methods using the @method decorator and dispatch requests via functions like dispatch, dispatch_to_json, dispatch_to_serializable, and dispatch_to_response. It also includes a serve() function to launch a development server that listens for JSON-RPC requests via HTTP POST.

Tokens
1.4K
Snippets
7
Records
7
Agent score
53%

What's inside jsonrpcserver

  1. Basic usage of jsonrpcserver

    main

    To use jsonrpcserver, define your RPC methods using the @method decorator. You can return a Success object to wrap your result. Use the dispatch function to process a raw JSON-RPC request string and receive the corresponding JSON-RPC response string.

    from jsonrpcserver import dispatch, method, Success
    
    @method
    def ping():
        return Success("pong")
    
    response = dispatch('{"jsonrpc": "2.0", "method": "ping", "id": 1}')
    # => '{"jsonrpc": "2.0", "result": "pong", "id": 1}'
  2. Dispatch JSON-RPC requests using dispatch_to_json

    main

    The dispatch_to_json function (aliased as dispatch) is the primary entry point for the library. It handles the complete JSON-RPC lifecycle: taking a raw JSON-RPC request string and returning a serialized JSON-RPC response string. For notifications (requests without an id), it returns an empty string instead of null to ensure compliance with JSON-RPC standards.

    Arguments:

    • serializer: A function used to serialize the resulting Python object to a JSON string. Defaults to json.dumps.
    • **kwargs: All other arguments are passed through to dispatch_to_serializable (see below).
    from jsonrpcserver import dispatch
    
    # Example: A standard request
    response = dispatch('{"jsonrpc": "2.0", "method": "ping", "id": 1}')
    # Output: '{"jsonrpc": "2.0", "result": "pong", "id": 1}'
    
    # Example: A notification (no id)
    notification_response = dispatch('{"jsonrpc": "2.0", "method": "ping"}')
    # Output: ''
  3. Dispatch JSON-RPC requests using dispatch_to_serializable

    main

    The dispatch_to_serializable function dispatches a JSON-RPC request and returns the response as a Python dictionary or a list of dictionaries (or None for notifications). This is useful when you want to manipulate the response data in Python before serializing it yourself.

    Arguments:

    • request: The JSON-RPC request string.
    • methods: A dictionary mapping method names to functions. If omitted, it uses the internal global_methods (populated via the @method decorator).
    • context: An object passed as the first argument to all called methods.
    • deserializer: A function to deserialize the request string. Defaults to json.loads.
    • validator: A function to validate the request. It should raise an exception if invalid. To disable validation, pass lambda _: None.
    • post_process: A function applied to the Response object before returning. dispatch_to_serializable uses to_dict by default.
    from jsonrpcserver import dispatch_to_serializable
    
    # Returns a dict instead of a JSON string
    response_dict = dispatch_to_serializable('{"jsonrpc": "2.0", "method": "ping", "id": 1}')
    # Output: {'jsonrpc': '2.0', 'result': 'pong', 'id': 1}
  4. Use serve() to bind to a specific host

    main

    The serve function accepts a name parameter (representing the hostname/IP) and a port parameter. This allows you to restrict the server to localhost or bind it to a specific network interface.

    from jsonrpcserver import serve
    
    # Listen only on localhost at port 8000
    serve(name="localhost", port=8000)
  5. Start a development server with serve()

    main

    Use the serve function to launch a simple development server that listens for JSON-RPC requests via HTTP POST. By default, it listens on all available interfaces at port 5000. It uses Python's built-in http.server module to handle requests and dispatches them using the internal dispatch logic.

    from jsonrpcserver import serve
    
    # Start the server on default port 5000
    serve()
    
    # Or specify a custom port
    serve(port=8080)
  6. Dispatch JSON-RPC requests using dispatch_to_response

    main

    The dispatch_to_response function dispatches a JSON-RPC request and returns Response namedtuples (or None for notifications). This provides the most granular access to the response structure.

    Arguments:

    • request: The JSON-RPC request string.
    • methods: A dictionary mapping method names to functions. If omitted, it uses the internal global_methods.
    • context: An object passed as the first argument to all called methods.
    • deserializer: A function to deserialize the request string. Defaults to json.loads.
    • validator: A function to validate the request. To disable validation, pass lambda _: None.
    • post_process: A function applied to the Response object. Defaults to identity.
    from jsonrpcserver import dispatch_to_response
    
    # Returns Response namedtuples
    responses = dispatch_to_response('{"jsonrpc": "2.0", "method": "ping", "id": 1}')
    # Output: [Response(result='pong', id=1, ...)]