Custom json output via API

I’m trying to create a new API function that will return json data at a url like https://erp.example.com/api/method/app_name.module_name.my_method, but I’m not quite sure how to do it. (Ultimate goal is to integrate ERPNext with facebook leads).

From looking at frappe.integrations.oauth2 as an example, I’ve added a whitelisted function:

from __future__ import unicode_literals
import frappe, json
from frappe import _

@frappe.whitelist()
def my_method(*args, **kwargs):
    test = frappe._dict({
        "test": "hello"
        })
    frappe.local.response = test

I think I’m hitting the right URL, but I’m getting an Internal Server Error. From logs/web.error.log:

[2019-10-27 07:29:31 +0545] [32049] [ERROR] Error handling request /api/method/app_name.module_name.my_method
Traceback (most recent call last):
  File "/home/xxx/frappe-bench/apps/frappe/frappe/app.py", line 60, in application
    response = frappe.api.handle()
  File "/home/xxx/frappe-bench/apps/frappe/frappe/api.py", line 55, in handle
    return frappe.handler.handle()
  File "/home/xxx/frappe-bench/apps/frappe/frappe/handler.py", line 32, in handle
    return build_response("json")
  File "/home/xxx/frappe-bench/apps/frappe/frappe/utils/response.py", line 53, in build_response
    return response_type_map[frappe.response.get('type') or response_type]()
  File "/home/xxx/frappe-bench/env/lib/python3.6/site-packages/werkzeug/local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: 'str' object has no attribute 'get'

I’m sure I’m just approaching this completely wrong, but I’ve been trying to find the right way for a while without luck. Any tips to point me in the right direction would be greatly appreciated.

Try just return dict

@frappe.whitelist()
def my_method(*args, **kwargs):
    test = frappe._dict({
        "test": "hello"
        })
    return test
1 Like

I tried the exact same code and it worked on latest develop using Py 3.7

1 Like

Thanks for the reply! With that, I get {"message":{"test":"hello"}}. Unfortunately, since I’m trying to interface with a 3rd part protocol over which I have no control, my result can’t be nested inside a message object.

Thanks! Just to clarify, you mean you used the code from my original post, or vijaywm’s? If it’s mine…strange, though glad to know I’m on the right track. I’ll keep digging.

Update: It’s working now with the code I had listed in the original post. I think the problem had something to do with caching. It seems bench clear-cache isn’t sufficient when introducing new code here. On a bench reset, the expected behavior shows.

Thanks to you both for your suggestions!

1 Like