|
| 1 | +# Methods |
| 2 | + |
| 3 | +Methods are functions that can be called by a JSON-RPC request. To write one, |
| 4 | +decorate a function with `@method`: |
| 5 | + |
| 6 | +```python |
| 7 | +from jsonrpcserver import method, Result, Success, Error |
| 8 | + |
| 9 | +@method |
| 10 | +def ping() -> Result: |
| 11 | + return Success("pong") |
| 12 | +``` |
| 13 | + |
| 14 | +If you don't need to respond with any value simply `return Success()`. |
| 15 | + |
| 16 | +## Responses |
| 17 | + |
| 18 | +Methods return either `Success` or `Error`. These are the [JSON-RPC response |
| 19 | +objects](https://www.jsonrpc.org/specification#response_object) (excluding the |
| 20 | +`jsonrpc` and `id` parts). `Error` takes a code, message, and optionally 'data'. |
| 21 | + |
| 22 | +```python |
| 23 | +@method |
| 24 | +def test() -> Result: |
| 25 | + return Error(1, "There was a problem") |
| 26 | +``` |
| 27 | + |
| 28 | +> 📝 Alternatively, raise a `JsonRpcError`, which takes the same |
| 29 | +> arguments as `Error`. |
| 30 | +
|
| 31 | +## Parameters |
| 32 | + |
| 33 | +Methods can accept arguments. |
| 34 | + |
| 35 | +```python |
| 36 | +@method |
| 37 | +def hello(name: str) -> Result: |
| 38 | + return Success("Hello " + name) |
| 39 | +``` |
| 40 | + |
| 41 | +Testing it: |
| 42 | + |
| 43 | +```sh |
| 44 | +$ curl -X POST http://localhost:5000 -d '{"jsonrpc": "2.0", "method": "hello", "params": ["Beau"], "id": 1}' |
| 45 | +{"jsonrpc": "2.0", "result": "Hello Beau", "id": 1} |
| 46 | +``` |
| 47 | + |
| 48 | +## Invalid params |
| 49 | + |
| 50 | +A common error response is _invalid params_. The JSON-RPC error code |
| 51 | +for this is **-32602**. A shortcut, _InvalidParams_, is included so |
| 52 | +you don't need to remember that. |
| 53 | + |
| 54 | +```python |
| 55 | +from jsonrpcserver import method, Result, InvalidParams, Success, dispatch |
| 56 | + |
| 57 | +@method |
| 58 | +def within_range(num: int) -> Result: |
| 59 | + if num not in range(1, 5): |
| 60 | + return InvalidParams("Value must be 1-5") |
| 61 | + return Success() |
| 62 | +``` |
| 63 | + |
| 64 | +This is the same as saying |
| 65 | + |
| 66 | +```python |
| 67 | +return Error(-32602, "Invalid params", "Value must be 1-5") |
| 68 | +``` |
0 commit comments