Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add decorator to simplify creating JSON REST endpoints #473

Open
wants to merge 48 commits into
base: develop
Choose a base branch
from

Conversation

marcusschiesser
Copy link

Adds the decorator json_handler to simplify creating JSON REST endpoints. It automatically adds an exception handler and injects the following parameters to the handle method:

  1. request, which is json.loads(in_string)
  2. query, which contains the URL parameters as a dict
  3. payload, which contains the payload as dict (remember to set passPayload = true in restmap.conf)

Here's an example for a GET handler with URL and path parameters:

from splunk.persistconn.application import PersistentServerConnectionApplication
from splunklib.customrest import json_handler

class GetHandler(PersistentServerConnectionApplication):
    def __init__(self, _command_line, _command_arg):
        PersistentServerConnectionApplication.__init__(self)

    @json_handler
    def handle(self, request, query, **kwargs):
        path_param = request['path_info']
        url_param1 = query.get('param1', 1)
        url_param2 = query.get('param2', 1)
        return {'payload': {'path_param': path_param, 'url_param1': url_param1, 'url_param2': url_param2},
                'status': 200
                }

(Called with something like: http://localhost:8000/en-US/splunkd/__raw/servicesNS/-/{app-name}/myapi/333?param1=4)

And an example for a POST handler (with passPayload = true) which processes a JSON payload:

from splunk.persistconn.application import PersistentServerConnectionApplication
from splunklib.customrest import json_handler

class PostHandler(PersistentServerConnectionApplication):
    def __init__(self, _command_line, _command_arg):
        PersistentServerConnectionApplication.__init__(self)

    @json_handler
    def handle(self, payload, **_kwargs):
        data = payload['flag']
        
        return {'payload': {'data': data},
                'status': 200

@marcusschiesser marcusschiesser force-pushed the simplify-writing-json-rest-endpoints branch from 1b73120 to 1a0f7d9 Compare December 23, 2022 09:11
@marcusschiesser marcusschiesser force-pushed the simplify-writing-json-rest-endpoints branch from 1a0f7d9 to 1481673 Compare December 23, 2022 09:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants