fastapi-jsonrpc icon indicating copy to clipboard operation
fastapi-jsonrpc copied to clipboard

Using Entrypoint instance outside main module leads to "Method not found"

Open lemeshkob opened this issue 3 years ago • 1 comments

Hey! I've found this lib quite great to combine both fastapi and rpc together. Great work!

But I'm struggling with only one thing: if I'm trying to define rpc methods outside the python file where the entrypoint is defined - it leads to a "Method not found" error on the response.

Maybe I'm doing something wrong, so you can point me where exactly I am wrong

app.py

app = API(name=settings.app_name, debug=settings.debug)
jsonrpc = Entrypoint('/jsonrpc', middlewares=[rpc_logging_middleware])
app.bind_entrypoint(jsonrpc)

rpc.py

from fastapi_jsonrpc import BaseModel, BaseError, Body
from app import jsonrpc

@jsonrpc.method(name="echo")
async def echo(
    data: str = Body(..., example='123'),
) -> str:
    if data == 'error':
        raise MyError(data={'details': 'error'})
    else:
        return data

And the request/response example with my setup:

# request:
{
    "jsonrpc": "2.0",
    "method": "echo",
    "params": {
        "data": "test"
    },
    "id": 1
}

# response:
{
    "jsonrpc": "2.0",
    "error": {
        "code": -32601,
        "message": "Method not found"
    },
    "id": 1
}

Looking forward to any advice or help here!

Thanks

lemeshkob avatar Jun 27 '22 17:06 lemeshkob

The best practice is place entrypoint near methods and then import entrypoint in app module

So, for your case i recommend move Entrypoint to rpc.py and then import rpc.py from app.py

It's just how python work - you need import modules manually. The best way it's make modules to be imported by design. Or implement autodiscover feature like in Django / Celery for applications and tasks.

spumer avatar Jun 29 '22 18:06 spumer