flask_jsonrpc package¶
Subpackages¶
- flask_jsonrpc.conf package
- flask_jsonrpc.contrib package
- flask_jsonrpc.types package
- Submodules
- flask_jsonrpc.types.methods module
- flask_jsonrpc.types.params module
- flask_jsonrpc.types.types module
- Module contents
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:
JSONRPCDecoratorMixinFlask 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.
- jsonrpc_site¶
The JSON-RPC site instance.
- jsonrpc_site_api¶
The JSON-RPC site API class.
- jsonrpc_apps¶
The set of registered JSON-RPC applications.
- jsonrpc_browse¶
The JSON-RPC browse application instance.
- Type:
- 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:
- Parameters:
self (Self)
- get_jsonrpc_site_api()[source]¶
Get the JSON-RPC site API.
- Returns:
The JSON-RPC site API type.
- Return type:
- 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:
app (flask.Flask) – The Flask application instance.
self (Self)
- 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:
- 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:
jsonrpc_app (flask_jsonrpc.app.JSONRPC | flask_jsonrpc.blueprints.JSONRPCBlueprint) – The JSON-RPC application or blueprint to register the browse interface for.
self (Self)
- 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:
JSONRPCDecoratorMixinJSON-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.
- jsonrpc_site¶
The JSON-RPC site instance.
- jsonrpc_site_api¶
The JSON-RPC site API class.
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:
- Parameters:
self (Self)
- get_jsonrpc_site_api()[source]¶
Get the JSON-RPC site API class.
- Returns:
The JSON-RPC site API class.
- Return type:
- Parameters:
self (Self)
- register(view_func, name=None, **options)[source]¶
Register a view function with the JSON-RPC blueprint.
- Parameters:
- 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:
objectJSON-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.
- service_describe()[source]¶
Get the service description.
- Returns:
Service description.
- Return type:
- Parameters:
self (Self)
- register(jsonrpc_site)[source]¶
Register the service description method.
The ‘rpc.describe’ is automatically registered to provide service description.
- Parameters:
jsonrpc_site (flask_jsonrpc.site.JSONRPCSite) – JSON-RPC site instance.
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') >>> 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:
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'}
flask_jsonrpc.exceptions module¶
- exception JSONRPCError(message=None, code=None, data=None, status_code=None)[source]¶
Bases:
ExceptionError class based on the JSON-RPC 2.0 specs.
- Parameters:
- 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'}, ... }
- property jsonrpc_format: dict[str, Any]¶
Return the Exception data in a format for JSON-RPC
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:
JSONRPCErrorInvalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
- exception InvalidRequestError(message=_('Invalid Request'), code=-32600, data=None, status_code=400)[source]¶
Bases:
JSONRPCErrorThe JSON sent is not a valid Request object.
- exception MethodNotFoundError(message=_('Method not found'), code=-32601, data=None, status_code=400)[source]¶
Bases:
JSONRPCErrorThe method does not exist / is not available.
- exception InvalidParamsError(message=_('Invalid params'), code=-32602, data=None, status_code=400)[source]¶
Bases:
JSONRPCErrorInvalid method parameter(s).
- exception InternalError(message=_('Internal error'), code=-32603, data=None, status_code=400)[source]¶
Bases:
JSONRPCErrorInternal JSON-RPC error.
- exception ServerError(message=_('Server error'), code=-32000, data=None, status_code=500, original_exception=None)[source]¶
Bases:
JSONRPCErrorReserved 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:
- Returns:
The deserialized parameter value.
- Return type:
- Raises:
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')
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:
objectA node in a tree structure.
- Parameters:
- name
Name of the node.
- Type:
str | None
- 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': []}, ... ], ... }
- children: list[Node]
- find_child(name)[source]
Find a child node by name.
- 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.
- clean()[source]
Clean the node by removing empty children.
- Parameters:
self (Self)
- Return type:
None
- urn(name, *args)[source]
Return the URN name.
- Parameters:
- Returns:
URN name.
- Return type:
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:
tp (Any) – Python type.
default (flask_jsonrpc.types.types.JSONRPCNewType | None, optional) – Default type if no match is found. Defaults to Object.
- Returns:
Corresponding JSONRPCNewType or
default.- Return type:
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,defaultis returned.- Parameters:
- Keyword Arguments:
default (Any) – Default value to return if path doesn’t exist.
None. (Defaults to)
- Returns:
Value of
objat path.- Return type:
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:
objectJSON-RPC site to handle JSON-RPC requests.
- Parameters:
- error_handlers¶
A mapping of exception types to their handlers.
- view_funcs¶
A mapping of method names to their view functions.
- Type:
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:
- 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:
- 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:
- 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)
- to_json(request_data)[source]¶
Convert the request data to JSON.
- Parameters:
- Returns:
The JSON-decoded data.
- Return type:
- 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:
- Returns:
The result of the view function.
- Return type:
- Raises:
flask_jsonrpc.exceptions.InvalidParamsError – If the parameters are invalid.
flask_jsonrpc.exceptions.InvalidParamsError – If there is an annotated metadata type error.
flask_jsonrpc.exceptions.InvalidParamsError – If there is a type checking error.
TypeError – If there is a type mismatch.
- dispatch(req_json)[source]¶
Dispatch the JSON-RPC request.
- Parameters:
- 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.MethodNotFoundError – If the requested method is not found.
flask_jsonrpc.exceptions.InvalidRequestError – If the request is invalid.
- 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.
- 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.
- 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]]]
- 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]]]
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)
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)
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- value: t.Any¶
- 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)
- 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- 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:
- 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- 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:
- 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¶
flask_jsonrpc.views module¶
- class JSONRPCView(jsonrpc_site)[source]¶
Bases:
MethodViewJSON-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.
- 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"]) asrouteandadd_url_ruleby default.
flask_jsonrpc.wrappers module¶
- class JSONRPCDecoratorMixin[source]¶
Bases:
objectMixin 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:
- get_jsonrpc_site()[source]¶
Get the JSON-RPC site.
- Returns:
The JSON-RPC site instance.
- Return type:
- Parameters:
self (Self)
- get_jsonrpc_site_api()[source]¶
Get the JSON-RPC site API.
- Returns:
The JSON-RPC site API type.
- Return type:
- 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:
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:
- Returns:
The decorator function.
- Return type:
- 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:
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:
JSONRPCDecoratorMixinFlask 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.
- jsonrpc_site¶
The JSON-RPC site instance.
- jsonrpc_site_api¶
The JSON-RPC site API class.
- jsonrpc_apps¶
The set of registered JSON-RPC applications.
- jsonrpc_browse¶
The JSON-RPC browse application instance.
- Type:
- 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:
- Parameters:
self (Self)
- get_jsonrpc_site_api()[source]¶
Get the JSON-RPC site API.
- Returns:
The JSON-RPC site API type.
- Return type:
- 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:
app (flask.Flask) – The Flask application instance.
self (Self)
- 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:
- 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:
jsonrpc_app (flask_jsonrpc.app.JSONRPC | flask_jsonrpc.blueprints.JSONRPCBlueprint) – The JSON-RPC application or blueprint to register the browse interface for.
self (Self)
- 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:
MethodViewJSON-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.
- 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"]) asrouteandadd_url_ruleby default.
- class JSONRPCBlueprint(name, import_name, version='1.0.0', jsonrpc_site=default_jsonrpc_site, jsonrpc_site_api=default_jsonrpc_site_api)[source]¶
Bases:
JSONRPCDecoratorMixinJSON-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.
- jsonrpc_site¶
The JSON-RPC site instance.
- jsonrpc_site_api¶
The JSON-RPC site API class.
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:
- Parameters:
self (Self)
- get_jsonrpc_site_api()[source]¶
Get the JSON-RPC site API class.
- Returns:
The JSON-RPC site API class.
- Return type:
- Parameters:
self (Self)
- register(view_func, name=None, **options)[source]¶
Register a view function with the JSON-RPC blueprint.
- Parameters:
- 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)