flask_jsonrpc package

Subpackages

Submodules

flask_jsonrpc.app module

class JSONRPC(app=None, path='/api', version='1.0.0', jsonrpc_site=default_jsonrpc_site, jsonrpc_site_api=default_jsonrpc_site_api, enable_web_browsable_api=None)[source]

Bases: JSONRPCDecoratorMixin

Flask JSON-RPC application wrapper.

Manages the integration of JSON-RPC functionality into a Flask application.

Parameters:
  • app (flask.Flask | None) – The Flask application instance. If provided, the JSON-RPC application will be initialized with this Flask app.

  • path (str) – The URL path where the JSON-RPC application will be accessible. Defaults to ‘/api’.

  • version (str) – The version of the JSON-RPC application. Defaults to ‘1.0.0’.

  • jsonrpc_site (type[flask_jsonrpc.site.JSONRPCSite]) – The JSON-RPC site class to use. Defaults to the default JSON-RPC site.

  • jsonrpc_site_api (type[flask_jsonrpc.views.JSONRPCView]) – The JSON-RPC site API class to use. Defaults to the default JSON-RPC site API.

  • enable_web_browsable_api (bool | None) – Whether to enable the web browsable API. If None, it will be enabled in debug mode. Defaults to None.

path

The URL path where the JSON-RPC application is accessible.

Type:

str

base_url

The base URL of the JSON-RPC application.

Type:

str | None

version

The version of the JSON-RPC application.

Type:

str

jsonrpc_site

The JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

jsonrpc_site_api

The JSON-RPC site API class.

Type:

type[flask_jsonrpc.views.JSONRPCView]

jsonrpc_apps

The set of registered JSON-RPC applications.

Type:

set[flask_jsonrpc.app.JSONRPC | flask_jsonrpc.blueprints.JSONRPCBlueprint]

jsonrpc_browse

The JSON-RPC browse application instance.

Type:

flask_jsonrpc.contrib.browse.JSONRPCBrowse | None

enable_web_browsable_api

Whether to enable the web browsable API. If None, it will be enabled in debug mode. Defaults to None.

Type:

bool | None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @jsonrpc.method('my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> if __name__ == '__main__':
...     app.run()
get_jsonrpc_site()[source]

Get the JSON-RPC site.

Returns:

The JSON-RPC site instance.

Return type:

flask_jsonrpc.site.JSONRPCSite

Parameters:

self (Self)

get_jsonrpc_site_api()[source]

Get the JSON-RPC site API.

Returns:

The JSON-RPC site API type.

Return type:

flask_jsonrpc.views.JSONRPCView

Parameters:

self (Self)

init_app(app)[source]

Initialize the JSON-RPC application with the given Flask app.

Initializes the JSON-RPC application by configuring it with the provided Flask application instance. This includes setting up the URL rules, logging, and web browsable API if enabled.

If the web browsable API is enabled, it will also initialize the browse interface.

Parameters:
Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(path='/api', version='1.0.0')
>>> jsonrpc.init_app(app)
register(view_func, name=None, **options)[source]

Register a view function as a JSON-RPC method.

Parameters:
  • view_func (Callable[..., Any]) – The view function to register.

  • name (str | None) – The name of the JSON-RPC method. If None, the function’s __name__ attribute will be used.

  • **options (Any) – Additional options for the JSON-RPC method.

  • self (Self)

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> jsonrpc.register(my_method, name='my_method', validate=False)
register_blueprint(app, jsonrpc_app, url_prefix=None, enable_web_browsable_api=None)[source]

Register a JSON-RPC blueprint with the given Flask app.

If the web browsable API is enabled, it will also register the browse interface for the blueprint.

Parameters:
  • app (flask.Flask) – The Flask application instance.

  • jsonrpc_app (flask_jsonrpc.blueprints.JSONRPCBlueprint) – The JSON-RPC blueprint to register.

  • url_prefix (str | None) – The URL prefix for the JSON-RPC blueprint. If None, the blueprint’s path will be used.

  • enable_web_browsable_api (bool | None) – Whether to enable the web browsable API. If None, it will be enabled in debug mode. Defaults to None.

  • self (Self)

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC, JSONRPCBlueprint
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> my_blueprint = JSONRPCBlueprint('my_blueprint', __name__)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @my_blueprint.method('my_blueprint.my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> jsonrpc.register_blueprint(app, my_blueprint, url_prefix='/my-blueprint')
init_browse_app(app, path=None, base_url=None)[source]

Initialize the JSON-RPC browse application.

Parameters:
  • app (flask.Flask) – The Flask application instance.

  • path (str | None) – The URL path for the JSON-RPC browse application. If None, the browse URL will be generated based on the JSON-RPC application’s path.

  • base_url (str | None) – The base URL for the JSON-RPC browse application. If None, the base URL will be generated based on the JSON-RPC application’s base URL.

  • self (Self)

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>> jsonrpc.init_browse_app(
...     app, path='/api/browse', base_url='http://localhost/api'
... )
register_browse(jsonrpc_app)[source]

Register the JSON-RPC browse application for a given JSON-RPC app.

Parameters:
Raises:

RuntimeError – If the JSON-RPC browse application has not been initialized.

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC, JSONRPCBlueprint
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>> my_blueprint = JSONRPCBlueprint('my_blueprint', __name__)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @my_blueprint.method('my_blueprint.my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> jsonrpc.register_blueprint(app, my_blueprint, url_prefix='/my-blueprint')
>>> jsonrpc.init_browse_app(app)
>>> jsonrpc.register_browse(my_blueprint)

flask_jsonrpc.blueprints module

class JSONRPCBlueprint(name, import_name, version='1.0.0', jsonrpc_site=default_jsonrpc_site, jsonrpc_site_api=default_jsonrpc_site_api)[source]

Bases: JSONRPCDecoratorMixin

JSON-RPC blueprint for Flask applications.

Parameters:
  • name (str) – The name of the blueprint.

  • import_name (str) – The import name of the blueprint.

  • version (str) – The version of the JSON-RPC API. Default is ‘1.0.0’.

  • jsonrpc_site (type[flask_jsonrpc.site.JSONRPCSite]) – The JSON-RPC site class to use. Default is flask_jsonrpc.globals.default_jsonrpc_site.

  • jsonrpc_site_api (type[flask_jsonrpc.views.JSONRPCView]) – The JSON-RPC site API class to use. Default is flask_jsonrpc.globals.default_jsonrpc_site_api.

name

The name of the blueprint.

Type:

str

import_name

The import name of the blueprint.

Type:

str

version

The version of the JSON-RPC API.

Type:

str

jsonrpc_site

The JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

jsonrpc_site_api

The JSON-RPC site API class.

Type:

type[flask_jsonrpc.views.JSONRPCView]

Examples

>>> from flask_jsonrpc import JSONRPCBlueprint
>>>
>>> jsonrpc_bp = JSONRPCBlueprint('api', __name__, version='1.0.0')
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @jsonrpc_bp.method('my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
get_jsonrpc_site()[source]

Get the JSON-RPC site instance.

Returns:

The JSON-RPC site instance.

Return type:

flask_jsonrpc.site.JSONRPCSite

Parameters:

self (Self)

get_jsonrpc_site_api()[source]

Get the JSON-RPC site API class.

Returns:

The JSON-RPC site API class.

Return type:

type[flask_jsonrpc.views.JSONRPCView]

Parameters:

self (Self)

register(view_func, name=None, **options)[source]

Register a view function with the JSON-RPC blueprint.

Parameters:
  • view_func (Callable[..., Any]) – The view function to register.

  • name (str | None) – The name of the method. If None, the function’s __name__ is used.

  • **options (Any) – Additional options for the method registration.

  • self (Self)

Return type:

None

Examples

>>> from flask_jsonrpc import JSONRPCBlueprint
>>>
>>> jsonrpc_bp = JSONRPCBlueprint('api', __name__, version='1.0.0')
>>>
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> jsonrpc_bp.register(my_method, name='my_method', validate=False)

flask_jsonrpc.descriptor module

class JSONRPCServiceDescriptor(jsonrpc_site)[source]

Bases: object

JSON-RPC Service Descriptor for JSON-RPC 2.0.

It provides a detailed description of the JSON-RPC service, including its methods, parameters, return types, and other metadata.

Parameters:

jsonrpc_site (flask_jsonrpc.site.JSONRPCSite) – JSON-RPC site instance.

jsonrpc_site

JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

service_describe()[source]

Get the service description.

Returns:

Service description.

Return type:

flask_jsonrpc.typing.ServiceDescribe

Parameters:

self (Self)

register(jsonrpc_site)[source]

Register the service description method.

The ‘rpc.describe’ is automatically registered to provide service description.

Parameters:
Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>> assert 'rpc.describe' in jsonrpc.get_jsonrpc_site().view_funcs

flask_jsonrpc.encoders module

serializable(obj)[source]

Serialize an object to a JSON-serializable format.

Parameters:

obj (Any) – The object to serialize.

Returns:

The JSON-serializable representation of the object.

Return type:

Any

Examples

>>> serializable(b'hello')
'hello'
>>>
>>> serializable(bytearray(b'world'))
'world'
>>>
>>> from enum import Enum
>>> class Color(Enum):
...     RED = 'red'
...     GREEN = 'green'
>>> serializable(Color.RED)
'red'
>>>
>>> serializable({'key': b'value', 'number': 42})
{'key': 'value', 'number': 42}
>>>
>>> serializable([b'item1', b'item2'])
['item1', 'item2']
>>>
>>> from dataclasses import dataclass
>>> @dataclass
... class Person:
...     name: str
...     age: int
>>> person = Person(name='Alice', age=30)
>>> serializable(person)
{'name': 'Alice', 'age': 30}
>>>
>>> from pydantic import BaseModel
>>> class User(BaseModel):
...     id: int
...     username: str
>>> user = User(id=1, username='bob')
>>> serializable(user)
{'id': 1, 'username': 'bob'}
jsonify(obj)[source]

Convert an object to a JSON response.

Parameters:

obj (Any) – The object to convert.

Returns:

The JSON response.

Return type:

flask.typing.ResponseValue

flask_jsonrpc.exceptions module

exception JSONRPCError(message=None, code=None, data=None, status_code=None)[source]

Bases: Exception

Error class based on the JSON-RPC 2.0 specs.

Parameters:
  • message (str | None, optional) – Error message. Defaults to None.

  • code (int | None, optional) – Error code. Defaults to 0.

  • data (Any | None, optional) – Additional error data. Defaults to None.

  • status_code (int | None, optional) – HTTP status code. Defaults to 400.

Return type:

None

Examples

>>> error = JSONRPCError(
...     message='An error occurred', code=1234, data={'info': 'details'}
... )
>>> assert error.jsonrpc_format == {
...     'name': 'JSONRPCError',
...     'code': 1234,
...     'message': 'An error occurred',
...     'data': {'info': 'details'},
... }
message: str | None = None
code: int = 0
data: Any | None = None
status_code: int = 400
property jsonrpc_format: dict[str, Any]

Return the Exception data in a format for JSON-RPC

Returns:

The error data formatted for JSON-RPC

Return type:

dict[str, Any]

Examples

>>> error = JSONRPCError(
...     message='An error occurred', code=1234, data={'info': 'details'}
... )
>>> assert error.jsonrpc_format == {
...     'name': 'JSONRPCError',
...     'code': 1234,
...     'message': 'An error occurred',
...     'data': {'info': 'details'},
... }
exception ParseError(message=_('Parse error'), code=-32700, data=None, status_code=400)[source]

Bases: JSONRPCError

Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.

Parameters:
  • message (str | None)

  • code (int)

  • data (Any | None)

  • status_code (int)

Return type:

None

exception InvalidRequestError(message=_('Invalid Request'), code=-32600, data=None, status_code=400)[source]

Bases: JSONRPCError

The JSON sent is not a valid Request object.

Parameters:
  • message (str | None)

  • code (int)

  • data (Any | None)

  • status_code (int)

Return type:

None

exception MethodNotFoundError(message=_('Method not found'), code=-32601, data=None, status_code=400)[source]

Bases: JSONRPCError

The method does not exist / is not available.

Parameters:
  • message (str | None)

  • code (int)

  • data (Any | None)

  • status_code (int)

Return type:

None

exception InvalidParamsError(message=_('Invalid params'), code=-32602, data=None, status_code=400)[source]

Bases: JSONRPCError

Invalid method parameter(s).

Parameters:
  • message (str | None)

  • code (int)

  • data (Any | None)

  • status_code (int)

Return type:

None

exception InternalError(message=_('Internal error'), code=-32603, data=None, status_code=400)[source]

Bases: JSONRPCError

Internal JSON-RPC error.

Parameters:
  • message (str | None)

  • code (int)

  • data (Any | None)

  • status_code (int)

Return type:

None

exception ServerError(message=_('Server error'), code=-32000, data=None, status_code=500, original_exception=None)[source]

Bases: JSONRPCError

Reserved for implementation-defined server-errors.

Parameters:
  • message (str | None, optional) – Error message. Defaults to ‘Server error’.

  • code (int | None, optional) – Error code. Defaults to -32000.

  • data (Any | None, optional) – Additional error data. Defaults to None.

  • status_code (int | None, optional) – HTTP status code. Defaults to 500.

  • original_exception (BaseException | None, optional) – The original exception that caused this error. Defaults to None.

Return type:

None

Notes

code: -32000 to -32099 Server error.

Examples

>>> try:
...     1 / 0
... except ZeroDivisionError as e:
...     error = ServerError(original_exception=e)
>>> assert error.jsonrpc_format == {
...     'name': 'ServerError',
...     'code': -32000,
...     'message': 'Server error',
...     'data': None,
... }
>>> assert isinstance(error.original_exception, ZeroDivisionError)

flask_jsonrpc.funcutils module

loads(param_type, param_value)[source]

Deserialize a JSON-RPC parameter value to the specified type.

Parameters:
  • param_type (Any) – The type to deserialize to.

  • param_value (Any) – The parameter value to deserialize.

Returns:

The deserialized parameter value.

Return type:

Any

Raises:
  • TypeError – If the parameter value cannot be deserialized to the specified type.

  • TypeError – If an unsupported union type is provided.

Examples

>>> loads(int, 42)
42
>>> loads(list[int], [1, 2, 3])
[1, 2, 3]
>>> from enum import Enum
>>> class Color(Enum):
...     RED = 'red'
...     GREEN = 'green'
>>> loads(Color, 'red')
<Color.RED: 'red'>
>>> from pydantic import BaseModel
>>> class User(BaseModel):
...     id: int
...     name: str
>>> loads(User, {'id': 1, 'name': 'Alice'})
User(id=1, name='Alice')
bindfy(view_func, params)[source]

Bind JSON-RPC parameters to a view function’s parameters with type deserialization.

Parameters:
  • view_func (Callable[..., Any]) – The view function to bind parameters to.

  • params (dict[str, Any]) – The JSON-RPC parameters to bind.

Returns:

The bound parameters with deserialized values.

Return type:

dict[str, Any]

flask_jsonrpc.globals module

default_jsonrpc_site

type[flask_jsonrpc.site.JSONRPCSite]: Default JSON-RPC site class.

default_jsonrpc_site_api

type[flask_jsonrpc.views.JSONRPCView]: Default JSON-RPC site API class.

flask_jsonrpc.helpers module

class Node(name, items=<factory>, children=<factory>)[source]

Bases: object

A node in a tree structure.

Parameters:
  • name (str | None) – Name of the node.

  • items (list[dict[str, Any]]) – List of items in the node.

  • children (list[Node]) – List of child nodes.

name

Name of the node.

Type:

str | None

items

List of items in the node.

Type:

list[dict[str, Any]]

children

List of child nodes.

Type:

list[Node]

Examples

>>> root = Node(name='root')
>>> child1 = Node(name='child1')
>>> child2 = Node(name='child2')
>>> root.add_child(child1)
>>> root.add_child(child2)
>>> child1.insert_item({'name': 'item1'})
>>> child2.insert_item({'name': 'item2'})
>>> assert root.to_dict() == {
...     'name': 'root',
...     'items': [],
...     'children': [
...         {'name': 'child1', 'items': [{'name': 'item1'}], 'children': []},
...         {'name': 'child2', 'items': [{'name': 'item2'}], 'children': []},
...     ],
... }
>>> root.find_child('child1').to_dict()
{'name': 'child1', 'items': [{'name': 'item1'}], 'children': []}
>>>
>>> root.find_child('child3') is None
True
>>> root.clean()
>>> root.sort()
>>> assert root.to_dict() == {
...     'name': 'root',
...     'items': [],
...     'children': [
...         {'name': 'child1', 'items': [{'name': 'item1'}], 'children': []},
...         {'name': 'child2', 'items': [{'name': 'item2'}], 'children': []},
...     ],
... }
name: str | None
items: list[dict[str, Any]]
children: list[Node]
find_child(name)[source]

Find a child node by name.

Parameters:
  • name (str) – Name of the child node to find.

  • self (Self)

Returns:

The child node if found, otherwise None.

Return type:

Node | None

add_child(node)[source]

Add a child node.

Parameters:
  • node (Node) – Child node to add.

  • self (Self)

Return type:

None

insert_item(val)[source]

Insert an item into the node.

Parameters:
Return type:

None

clean()[source]

Clean the node by removing empty children.

Parameters:

self (Self)

Return type:

None

sort()[source]

Sort the node’s children and items by name.

Parameters:

self (Self)

Return type:

None

to_dict()[source]

Convert the node to a dictionary.

Returns:

Dictionary representation of the node.

Return type:

dict[str, Any]

Parameters:

self (Self)

urn(name, *args)[source]

Return the URN name.

Parameters:
  • name (str) – Name.

  • *args (Any) – Additional name parts.

Returns:

URN name.

Return type:

str

Examples

>>> urn('python')
'urn:python'
>>> urn('python.flask')
'urn:python:flask'
>>> urn('python', 'Flask', 'JsonRPC')
'urn:python:flask:jsonrpc'
>>> urn('python', '/api/browse')
'urn:python:api:browse'
>>> urn(None)
Traceback (most recent call last):
    ...
ValueError: name is required
>>> urn('')
Traceback (most recent call last):
    ...
ValueError: name is required
from_python_type(tp, default=Object)[source]

Convert Python type to JSONRPCNewType.

Parameters:
Returns:

Corresponding JSONRPCNewType or default.

Return type:

flask_jsonrpc.types.types.JSONRPCNewType | None

Examples

>>> str(from_python_type(str))
'String'
>>> str(from_python_type(int))
'Number'
>>> str(from_python_type(dict))
'Object'
>>> str(from_python_type(list))
'Array'
>>> str(from_python_type(bool))
'Boolean'
>>> str(from_python_type(None))
'Null'
>>> str(from_python_type(t.NoReturn))
'Null'
get(obj, path, default=None)[source]

Get the value at any depth of a nested object based on the path described by path. If path doesn’t exist, default is returned.

Parameters:
  • obj (dict) – Object to process.

  • path (str) – List or . delimited string of path describing path.

  • default (Any)

Keyword Arguments:
  • default (Any) – Default value to return if path doesn’t exist.

  • None. (Defaults to)

Returns:

Value of obj at path.

Return type:

Any

Examples

>>> get(None, 'a')
>>> get(None, 'a', 'default')
'default'
>>> get('a', 'a.b.c', 'default')
'default'
>>> get({'a': 1}, 'a')
1
>>> get({'a': 1}, 'b')
>>> get({'a': 1}, 'b', 'default')
'default'
>>> get({'a': {'b': {'c': 1}}}, 'a.b.c')
1
>>> get({}, 'a.b.c')
>>> get([], 'a.b.c')
>>> get([], 'a.b.c', None)

flask_jsonrpc.site module

class JSONRPCSite(version, path=None, base_url=None)[source]

Bases: object

JSON-RPC site to handle JSON-RPC requests.

Parameters:
  • version (str) – The version of the JSON-RPC API.

  • path (str | None) – The URL path for the JSON-RPC site. If None, it will be set later.

  • base_url (str | None) – The base URL for the JSON-RPC site. If None, it will be set later.

path

The URL path for the JSON-RPC site.

Type:

str | None

base_url

The base URL for the JSON-RPC site.

Type:

str | None

error_handlers

A mapping of exception types to their handlers.

Type:

dict[type[Exception], Callable[[Any], Any]]

view_funcs

A mapping of method names to their view functions.

Type:

collections.OrderedDict[str, Callable[…, Any]]

uuid

A unique identifier for the JSON-RPC site.

Type:

uuid.UUID

name

The name of the JSON-RPC site.

Type:

str

version

The version of the JSON-RPC API.

Type:

str

describe

A callable that returns the service description.

Type:

Callable[[], dict[str, Any]]

Examples

>>> jsonrpc_site = JSONRPCSite(
...     version='2.0', path='/api', base_url='http://localhost/api'
... )
property is_json: bool

Check if the mimetype indicates JSON data, either application/json or application/*+json.

Returns:

True if the mimetype indicates JSON data, False otherwise.

Return type:

bool

property logger: Logger[source]

Get the logger for the JSON-RPC site.

If the logger does not have any level handlers, a NullHandler is added.

Returns:

The logger instance.

Return type:

logging.Logger

set_path(path)[source]

Set the URL path for the JSON-RPC site.

Parameters:
  • path (str) – The URL path to set.

  • self (Self)

Return type:

None

set_base_url(base_url)[source]

Set the base URL for the JSON-RPC site.

Parameters:
  • base_url (str | None) – The base URL to set.

  • self (Self)

Return type:

None

register_error_handler(exception, fn)[source]

Register an error handler for a specific exception type.

Parameters:
Return type:

None

Examples

>>> class MyException(Exception):
...     pass
>>>
>>>
>>> def my_error_handler(exc: MyException) -> dict[str, Any]:
...     return {'message': str(exc), 'code': 1234}
>>>
>>> jsonrpc_site = JSONRPCSite(version='2.0', path='/api')
>>> jsonrpc_site.register_error_handler(MyException, my_error_handler)
register(name, view_func)[source]

Register a view function with the JSON-RPC site.

Parameters:
  • name (str) – The name of the method.

  • view_func (Callable[..., Any]) – The view function to register.

  • self (Self)

Return type:

None

Examples

>>> def my_method(param1: int) -> str:
...     return str(param1)
>>> jsonrpc_site = JSONRPCSite(version='2.0', path='/api')
>>> jsonrpc_site.register('my_method', my_method)
dispatch_request()[source]

Dispatch the JSON-RPC request.

Returns:

The response data, status code, and headers.

Return type:

tuple[Any, int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

Raises:

flask_jsonrpc.exceptions.ParseError – If the request is not valid JSON.

Parameters:

self (Self)

validate_request()[source]

Validate the JSON-RPC request.

Returns:

True if the request is valid, False otherwise.

Return type:

bool

Parameters:

self (Self)

to_json(request_data)[source]

Convert the request data to JSON.

Parameters:
  • request_data (bytes) – The request data.

  • self (Self)

Returns:

The JSON-decoded data.

Return type:

Any

Raises:

flask_jsonrpc.exceptions.ParseError – If the request data is not valid JSON.

handle_view_func(view_func, params)[source]

Handle the view function with the given parameters.

Parameters:
  • view_func (Callable[..., Any]) – The view function to handle.

  • params (Any) – The parameters to pass to the view function.

  • self (Self)

Returns:

The result of the view function.

Return type:

Any

Raises:
dispatch(req_json)[source]

Dispatch the JSON-RPC request.

Parameters:
  • req_json (dict[str, Any]) – The JSON-RPC request data.

  • self (Self)

Returns:

The response data, status code, and headers.

Return type:

tuple[Any, int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

Raises:
handle_exception(req_json, exc)[source]

Handle exceptions that occur during request dispatch.

If no specific error handler is found for the exception, a generic ServerError is used.

Parameters:
  • req_json (dict[str, Any]) – The JSON-RPC request data.

  • exc (Exception) – The exception that occurred.

  • self (Self)

Returns:

The response data, status code, and headers.

Return type:

tuple[Any, int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

handle_dispatch_except(req_json)[source]

Handle the dispatch of the request and catch exceptions.

If an exception occurs during dispatch, it is handled appropriately.

Parameters:
  • req_json (dict[str, Any]) – The JSON-RPC request data.

  • self (Self)

Returns:

The response data, status code, and headers.

Return type:

tuple[Any, int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

batch_dispatch(reqs_json)[source]

Dispatch a batch of JSON-RPC requests.

Parameters:
Returns:

tuple[

list[typing.Any], int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]

]:

The list of response data, status code, and headers.

Raises:

flask_jsonrpc.exceptions.InvalidRequestError – If the batch request is empty.

Return type:

tuple[list[Any], int, Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

validate(req_json)[source]

Validate the JSON-RPC request structure.

Parameters:
  • req_json (dict[str, Any]) – The JSON-RPC request data.

  • self (Self)

Returns:

True if the request is valid, False otherwise.

Return type:

bool

unpack_tuple_returns(resp_view, default_status_code=JSONRPC_DEFAULT_HTTP_STATUS_CODE, default_headers=JSONRPC_DEFAULT_HTTP_HEADERS)[source]

Unpack the response tuple returned by a view function.

Parameters:
  • resp_view (Any) – The response returned by the view function.

  • default_status_code (int) – The default HTTP status code to use if not specified.

  • default_headers (werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]) – The default HTTP headers to use if not specified.

  • self (Self)

Returns:

The unpacked response body, status code, and headers.

Return type:

tuple[Any, int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

make_response(req_json, resp_view)[source]

Make a JSON-RPC response.

Parameters:
  • req_json (dict[str, Any]) – The JSON-RPC request data.

  • resp_view (Any) – The response returned by the view function.

  • self (Self)

Returns:

The response data, status code, and headers.

Return type:

tuple[Any, int, werkzeug.datastructures.Headers | dict[str, str] | tuple[str] | list[tuple[str]]]

flask_jsonrpc.typing module

class BaseModel[source]

Bases: BaseModel

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Field(*, name, type, summary=None, description=None, properties=None, examples=None, required=None, deprecated=None, nullable=None, minimum=None, maximum=None, multiple_of=None, min_length=None, max_length=None, pattern=None, allow_inf_nan=None, max_digits=None, decimal_places=None)[source]

Bases: BaseModel

Parameters:
name: str
type: str
summary: str | None
description: str | None
properties: t.Mapping[str, Field] | None
examples: list[t.Any] | None
required: bool | None
deprecated: bool | None
nullable: bool | None
minimum: float | None
maximum: float | None
multiple_of: float | None
min_length: int | None
max_length: int | None
pattern: str | t.Pattern[str] | None
allow_inf_nan: bool | None
max_digits: int | None
decimal_places: int | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ExampleField(*, name, value, summary=None, description=None)[source]

Bases: BaseModel

Parameters:
  • name (str)

  • value (Any)

  • summary (str | None)

  • description (str | None)

name: str
value: t.Any
summary: str | None
description: str | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Example(*, name=None, summary=None, description=None, params=None, returns=None)[source]

Bases: BaseModel

Parameters:
name: str | None
summary: str | None
description: str | None
params: list[ExampleField] | None
returns: ExampleField | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Error(*, code, message, data=None, status_code)[source]

Bases: BaseModel

Parameters:
  • code (int)

  • message (str)

  • data (Any | None)

  • status_code (int)

code: int
message: str
data: t.Any | None
status_code: int
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Method(*, name, type, summary=None, description=None, validation=True, notification=True, deprecated=None, params=[], returns, tags=None, errors=None, examples=None)[source]

Bases: BaseModel

Parameters:
name: str
type: str
summary: str | None
description: str | None
validation: bool
notification: bool
deprecated: bool | None
params: list[Field]
returns: Field
tags: list[str] | None
errors: list[Error] | None
examples: list[Example] | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Server(*, url, description=None)[source]

Bases: BaseModel

Parameters:
  • url (str)

  • description (str | None)

url: str
description: str | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class ServiceDescribe(*, id, name, version, title=None, description=None, servers, methods)[source]

Bases: BaseModel

Parameters:
id: str
name: str
version: str
title: str | None
description: str | None
servers: list[Server]
methods: OrderedDict[str, Method]
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

flask_jsonrpc.utils module

trait(cls)[source]
mypyc_attr(*attrs, **kwattrs)[source]

flask_jsonrpc.views module

class JSONRPCView(jsonrpc_site)[source]

Bases: MethodView

JSON-RPC view to handle JSON-RPC requests.

Parameters:

jsonrpc_site (flask_jsonrpc.site.JSONRPCSite) – The JSON-RPC site instance.

jsonrpc_site

The JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

post()[source]

Handle POST requests for JSON-RPC.

If the request is successful, returns a JSON response with the result. If there is a JSON-RPC error, returns a JSON response with the error details.

Returns:

The Flask response object.

Return type:

flask.typing.ResponseReturnValue

Parameters:

self (Self)

methods: ClassVar[Collection[str] | None] = {'POST'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

flask_jsonrpc.wrappers module

class JSONRPCDecoratorMixin[source]

Bases: object

Mixin class to add JSON-RPC method and error handler decorators.

property logger: Logger[source]

Get the logger for the Flask JSON-RPC wrapper.

Returns:

The logger instance.

Return type:

logging.Logger

get_jsonrpc_site()[source]

Get the JSON-RPC site.

Returns:

The JSON-RPC site instance.

Return type:

flask_jsonrpc.site.JSONRPCSite

Parameters:

self (Self)

get_jsonrpc_site_api()[source]

Get the JSON-RPC site API.

Returns:

The JSON-RPC site API type.

Return type:

type[flask_jsonrpc.views.JSONRPCView]

Parameters:

self (Self)

register_view_function(view_func, name=None, annotation=None, **options)[source]

Register a view function as a JSON-RPC method.

Parameters:
  • view_func (Callable[..., Any]) – The view function to register.

  • name (str | None) – The name of the JSON-RPC method. If None, the function name is used.

  • annotation (flask_jsonrpc.types.methods.MethodAnnotatedType | None) – The method annotation.

  • **options (dict[str, Any]) – Additional options for the method.

  • self (Self)

Returns:

The registered view function.

Return type:

Callable[…, Any]

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> jsonrpc.register_view_function(my_method, name='my_method', validate=False)
<function my_method at 0x...>
method(name=None, annotation=None, **options)[source]

Decorator to register a view function as a JSON-RPC method.

Parameters:
  • name (str | None) – The name of the JSON-RPC method. If None, the function name is used.

  • annotation (flask_jsonrpc.types.methods.MethodAnnotatedType | None) – The method annotation.

  • **options (dict[str, Any]) – Additional options for the method.

  • self (Self)

Returns:

The decorator function.

Return type:

Callable[…, Any]

Raises:

ValueError – If validation is enabled and the method lacks type annotations.

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @jsonrpc.method('my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
register_error_handler(exception, fn)[source]

Register an error handler for a specific exception type.

Parameters:
Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> class MyException(Exception):
...     pass
>>>
>>> @jsonrpc.errorhandler(MyException)
... def handle_my_exception(exc: MyException) -> dict[str, str]:
...     return {'message': str(exc)}
>>>
>>> jsonrpc.register_error_handler(MyException, handle_my_exception)
errorhandler(exception)[source]

Decorator to register an error handler for a specific exception type.

Parameters:
Returns:

The decorator function.

Return type:

Callable[[Callable[[Any], Any]], Callable[[Any], Any]]

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> class MyException(Exception):
...     pass
>>>
>>> @jsonrpc.errorhandler(MyException)
... def handle_my_exception(exc: MyException) -> dict[str, str]:
...     return {'message': str(exc)}
>>>
>>> jsonrpc.errorhandler(MyException)(handle_my_exception)
<function handle_my_exception at 0x...>

Module contents

class JSONRPC(app=None, path='/api', version='1.0.0', jsonrpc_site=default_jsonrpc_site, jsonrpc_site_api=default_jsonrpc_site_api, enable_web_browsable_api=None)[source]

Bases: JSONRPCDecoratorMixin

Flask JSON-RPC application wrapper.

Manages the integration of JSON-RPC functionality into a Flask application.

Parameters:
  • app (flask.Flask | None) – The Flask application instance. If provided, the JSON-RPC application will be initialized with this Flask app.

  • path (str) – The URL path where the JSON-RPC application will be accessible. Defaults to ‘/api’.

  • version (str) – The version of the JSON-RPC application. Defaults to ‘1.0.0’.

  • jsonrpc_site (type[flask_jsonrpc.site.JSONRPCSite]) – The JSON-RPC site class to use. Defaults to the default JSON-RPC site.

  • jsonrpc_site_api (type[flask_jsonrpc.views.JSONRPCView]) – The JSON-RPC site API class to use. Defaults to the default JSON-RPC site API.

  • enable_web_browsable_api (bool | None) – Whether to enable the web browsable API. If None, it will be enabled in debug mode. Defaults to None.

path

The URL path where the JSON-RPC application is accessible.

Type:

str

base_url

The base URL of the JSON-RPC application.

Type:

str | None

version

The version of the JSON-RPC application.

Type:

str

jsonrpc_site

The JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

jsonrpc_site_api

The JSON-RPC site API class.

Type:

type[flask_jsonrpc.views.JSONRPCView]

jsonrpc_apps

The set of registered JSON-RPC applications.

Type:

set[flask_jsonrpc.app.JSONRPC | flask_jsonrpc.blueprints.JSONRPCBlueprint]

jsonrpc_browse

The JSON-RPC browse application instance.

Type:

flask_jsonrpc.contrib.browse.JSONRPCBrowse | None

enable_web_browsable_api

Whether to enable the web browsable API. If None, it will be enabled in debug mode. Defaults to None.

Type:

bool | None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @jsonrpc.method('my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> if __name__ == '__main__':
...     app.run()
get_jsonrpc_site()[source]

Get the JSON-RPC site.

Returns:

The JSON-RPC site instance.

Return type:

flask_jsonrpc.site.JSONRPCSite

Parameters:

self (Self)

get_jsonrpc_site_api()[source]

Get the JSON-RPC site API.

Returns:

The JSON-RPC site API type.

Return type:

flask_jsonrpc.views.JSONRPCView

Parameters:

self (Self)

init_app(app)[source]

Initialize the JSON-RPC application with the given Flask app.

Initializes the JSON-RPC application by configuring it with the provided Flask application instance. This includes setting up the URL rules, logging, and web browsable API if enabled.

If the web browsable API is enabled, it will also initialize the browse interface.

Parameters:
Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(path='/api', version='1.0.0')
>>> jsonrpc.init_app(app)
register(view_func, name=None, **options)[source]

Register a view function as a JSON-RPC method.

Parameters:
  • view_func (Callable[..., Any]) – The view function to register.

  • name (str | None) – The name of the JSON-RPC method. If None, the function’s __name__ attribute will be used.

  • **options (Any) – Additional options for the JSON-RPC method.

  • self (Self)

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> jsonrpc.register(my_method, name='my_method', validate=False)
register_blueprint(app, jsonrpc_app, url_prefix=None, enable_web_browsable_api=None)[source]

Register a JSON-RPC blueprint with the given Flask app.

If the web browsable API is enabled, it will also register the browse interface for the blueprint.

Parameters:
  • app (flask.Flask) – The Flask application instance.

  • jsonrpc_app (flask_jsonrpc.blueprints.JSONRPCBlueprint) – The JSON-RPC blueprint to register.

  • url_prefix (str | None) – The URL prefix for the JSON-RPC blueprint. If None, the blueprint’s path will be used.

  • enable_web_browsable_api (bool | None) – Whether to enable the web browsable API. If None, it will be enabled in debug mode. Defaults to None.

  • self (Self)

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC, JSONRPCBlueprint
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>>
>>> my_blueprint = JSONRPCBlueprint('my_blueprint', __name__)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @my_blueprint.method('my_blueprint.my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> jsonrpc.register_blueprint(app, my_blueprint, url_prefix='/my-blueprint')
init_browse_app(app, path=None, base_url=None)[source]

Initialize the JSON-RPC browse application.

Parameters:
  • app (flask.Flask) – The Flask application instance.

  • path (str | None) – The URL path for the JSON-RPC browse application. If None, the browse URL will be generated based on the JSON-RPC application’s path.

  • base_url (str | None) – The base URL for the JSON-RPC browse application. If None, the base URL will be generated based on the JSON-RPC application’s base URL.

  • self (Self)

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>> jsonrpc.init_browse_app(
...     app, path='/api/browse', base_url='http://localhost/api'
... )
register_browse(jsonrpc_app)[source]

Register the JSON-RPC browse application for a given JSON-RPC app.

Parameters:
Raises:

RuntimeError – If the JSON-RPC browse application has not been initialized.

Return type:

None

Examples

>>> from flask import Flask
>>> from flask_jsonrpc import JSONRPC, JSONRPCBlueprint
>>>
>>> app = Flask(__name__)
>>> jsonrpc = JSONRPC(app, path='/api', version='1.0.0')
>>> my_blueprint = JSONRPCBlueprint('my_blueprint', __name__)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @my_blueprint.method('my_blueprint.my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> jsonrpc.register_blueprint(app, my_blueprint, url_prefix='/my-blueprint')
>>> jsonrpc.init_browse_app(app)
>>> jsonrpc.register_browse(my_blueprint)
class JSONRPCView(jsonrpc_site)[source]

Bases: MethodView

JSON-RPC view to handle JSON-RPC requests.

Parameters:

jsonrpc_site (flask_jsonrpc.site.JSONRPCSite) – The JSON-RPC site instance.

jsonrpc_site

The JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

post()[source]

Handle POST requests for JSON-RPC.

If the request is successful, returns a JSON response with the result. If there is a JSON-RPC error, returns a JSON response with the error details.

Returns:

The Flask response object.

Return type:

flask.typing.ResponseReturnValue

Parameters:

self (Self)

methods: ClassVar[Collection[str] | None] = {'POST'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

class JSONRPCBlueprint(name, import_name, version='1.0.0', jsonrpc_site=default_jsonrpc_site, jsonrpc_site_api=default_jsonrpc_site_api)[source]

Bases: JSONRPCDecoratorMixin

JSON-RPC blueprint for Flask applications.

Parameters:
  • name (str) – The name of the blueprint.

  • import_name (str) – The import name of the blueprint.

  • version (str) – The version of the JSON-RPC API. Default is ‘1.0.0’.

  • jsonrpc_site (type[flask_jsonrpc.site.JSONRPCSite]) – The JSON-RPC site class to use. Default is flask_jsonrpc.globals.default_jsonrpc_site.

  • jsonrpc_site_api (type[flask_jsonrpc.views.JSONRPCView]) – The JSON-RPC site API class to use. Default is flask_jsonrpc.globals.default_jsonrpc_site_api.

name

The name of the blueprint.

Type:

str

import_name

The import name of the blueprint.

Type:

str

version

The version of the JSON-RPC API.

Type:

str

jsonrpc_site

The JSON-RPC site instance.

Type:

flask_jsonrpc.site.JSONRPCSite

jsonrpc_site_api

The JSON-RPC site API class.

Type:

type[flask_jsonrpc.views.JSONRPCView]

Examples

>>> from flask_jsonrpc import JSONRPCBlueprint
>>>
>>> jsonrpc_bp = JSONRPCBlueprint('api', __name__, version='1.0.0')
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> @jsonrpc_bp.method('my_method', validate=False)
... def my_method(param1: int) -> str:
...     return str(param1)
get_jsonrpc_site()[source]

Get the JSON-RPC site instance.

Returns:

The JSON-RPC site instance.

Return type:

flask_jsonrpc.site.JSONRPCSite

Parameters:

self (Self)

get_jsonrpc_site_api()[source]

Get the JSON-RPC site API class.

Returns:

The JSON-RPC site API class.

Return type:

type[flask_jsonrpc.views.JSONRPCView]

Parameters:

self (Self)

register(view_func, name=None, **options)[source]

Register a view function with the JSON-RPC blueprint.

Parameters:
  • view_func (Callable[..., Any]) – The view function to register.

  • name (str | None) – The name of the method. If None, the function’s __name__ is used.

  • **options (Any) – Additional options for the method registration.

  • self (Self)

Return type:

None

Examples

>>> from flask_jsonrpc import JSONRPCBlueprint
>>>
>>> jsonrpc_bp = JSONRPCBlueprint('api', __name__, version='1.0.0')
>>>
... def my_method(param1: int) -> str:
...     return str(param1)
>>>
>>> # Disable automatic validation for typechecking limitations with doctests
>>> # We always recommend to use validation in real applications
>>> jsonrpc_bp.register(my_method, name='my_method', validate=False)