Wrapper for REST API calls











up vote
0
down vote

favorite
1












This is a wrapper that can be used to do additional external REST call to some API. Since I have to provide support to legacy code so I added three static functions to support them.



However, the question that comes to my mind is where to actually set default value either in the constructor or it should be in the main function.



is_optional = kwargs.get('is_optional', False) can also be set directly in constructor. So what is correct way to handle such situations?



class ExternalRestService:
def __init__(self, endpoint, method=sc.REQUEST_GET):
self.endpoint = endpoint
self.method = method
self.timeout = sc.REQUEST_TIMEOUT

@staticmethod
def get(endpoint, request_headers, timeout):
"""
Handle GET External Call
"""
logging.debug("About to make an external *** GET *** to url %s", endpoint)
response = requests.get(url=endpoint, headers=request_headers,
timeout=timeout)
return response

@staticmethod
def post(endpoint, request_headers, json_data, timeout):
"""
Handle POST External Call
"""
logging.debug("About to make an external *** POST *** to url %s", endpoint)
request_headers["Content-type"] = "application/json"
response = requests.post(url=endpoint, headers=request_headers, json_data=json_data,
timeout=timeout)
return response

@staticmethod
def put(endpoint, request_headers, json_data, timeout, fallback=False):
"""
Handle PUT External Call
"""
logging.debug("About to make an external *** PUT *** to url %s", endpoint)
request_headers["Content-type"] = "application/json"
response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
timeout=timeout)
if fallback and response.status_code == 405:
logging.debug("PUT action failed, applying fallback strategy")
response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
timeout=timeout)
return response

def invoke(self, **kwargs):
"""
Execute the external call
"""
is_fallback = kwargs.get('is_fallback', False)
is_optional = kwargs.get('is_optional', False)
request_headers = kwargs.get('request_headers', {})
json_data = kwargs.get('json_data', {})

response_list = None
try:
logging.info("About to make an external *** %s *** call", self.method)
if self.method == sc.REQUEST_POST:
response = self.post(self.endpoint, request_headers, json_data, self.timeout)
elif self.method == sc.REQUEST_PUT:
response = self.put(self.endpoint, request_headers, json_data,
self.timeout, fallback=is_fallback)
else:
response = self.get(self.endpoint, request_headers, self.timeout)
response_list, error_list = self.__response_handler(response, is_optional)
except requests.RequestException as err:
error_list = err
return response_list, error_list

@staticmethod
def __response_handler(response, is_optional=False):
"""
Handle API response
"""
status_code = response.status_code
if is_optional and status_code == 404:
return response, None
if not 200 <= status_code < 300:
return None, response
response_list = response.json()
return response_list, None









share|improve this question




























    up vote
    0
    down vote

    favorite
    1












    This is a wrapper that can be used to do additional external REST call to some API. Since I have to provide support to legacy code so I added three static functions to support them.



    However, the question that comes to my mind is where to actually set default value either in the constructor or it should be in the main function.



    is_optional = kwargs.get('is_optional', False) can also be set directly in constructor. So what is correct way to handle such situations?



    class ExternalRestService:
    def __init__(self, endpoint, method=sc.REQUEST_GET):
    self.endpoint = endpoint
    self.method = method
    self.timeout = sc.REQUEST_TIMEOUT

    @staticmethod
    def get(endpoint, request_headers, timeout):
    """
    Handle GET External Call
    """
    logging.debug("About to make an external *** GET *** to url %s", endpoint)
    response = requests.get(url=endpoint, headers=request_headers,
    timeout=timeout)
    return response

    @staticmethod
    def post(endpoint, request_headers, json_data, timeout):
    """
    Handle POST External Call
    """
    logging.debug("About to make an external *** POST *** to url %s", endpoint)
    request_headers["Content-type"] = "application/json"
    response = requests.post(url=endpoint, headers=request_headers, json_data=json_data,
    timeout=timeout)
    return response

    @staticmethod
    def put(endpoint, request_headers, json_data, timeout, fallback=False):
    """
    Handle PUT External Call
    """
    logging.debug("About to make an external *** PUT *** to url %s", endpoint)
    request_headers["Content-type"] = "application/json"
    response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
    timeout=timeout)
    if fallback and response.status_code == 405:
    logging.debug("PUT action failed, applying fallback strategy")
    response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
    timeout=timeout)
    return response

    def invoke(self, **kwargs):
    """
    Execute the external call
    """
    is_fallback = kwargs.get('is_fallback', False)
    is_optional = kwargs.get('is_optional', False)
    request_headers = kwargs.get('request_headers', {})
    json_data = kwargs.get('json_data', {})

    response_list = None
    try:
    logging.info("About to make an external *** %s *** call", self.method)
    if self.method == sc.REQUEST_POST:
    response = self.post(self.endpoint, request_headers, json_data, self.timeout)
    elif self.method == sc.REQUEST_PUT:
    response = self.put(self.endpoint, request_headers, json_data,
    self.timeout, fallback=is_fallback)
    else:
    response = self.get(self.endpoint, request_headers, self.timeout)
    response_list, error_list = self.__response_handler(response, is_optional)
    except requests.RequestException as err:
    error_list = err
    return response_list, error_list

    @staticmethod
    def __response_handler(response, is_optional=False):
    """
    Handle API response
    """
    status_code = response.status_code
    if is_optional and status_code == 404:
    return response, None
    if not 200 <= status_code < 300:
    return None, response
    response_list = response.json()
    return response_list, None









    share|improve this question


























      up vote
      0
      down vote

      favorite
      1









      up vote
      0
      down vote

      favorite
      1






      1





      This is a wrapper that can be used to do additional external REST call to some API. Since I have to provide support to legacy code so I added three static functions to support them.



      However, the question that comes to my mind is where to actually set default value either in the constructor or it should be in the main function.



      is_optional = kwargs.get('is_optional', False) can also be set directly in constructor. So what is correct way to handle such situations?



      class ExternalRestService:
      def __init__(self, endpoint, method=sc.REQUEST_GET):
      self.endpoint = endpoint
      self.method = method
      self.timeout = sc.REQUEST_TIMEOUT

      @staticmethod
      def get(endpoint, request_headers, timeout):
      """
      Handle GET External Call
      """
      logging.debug("About to make an external *** GET *** to url %s", endpoint)
      response = requests.get(url=endpoint, headers=request_headers,
      timeout=timeout)
      return response

      @staticmethod
      def post(endpoint, request_headers, json_data, timeout):
      """
      Handle POST External Call
      """
      logging.debug("About to make an external *** POST *** to url %s", endpoint)
      request_headers["Content-type"] = "application/json"
      response = requests.post(url=endpoint, headers=request_headers, json_data=json_data,
      timeout=timeout)
      return response

      @staticmethod
      def put(endpoint, request_headers, json_data, timeout, fallback=False):
      """
      Handle PUT External Call
      """
      logging.debug("About to make an external *** PUT *** to url %s", endpoint)
      request_headers["Content-type"] = "application/json"
      response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
      timeout=timeout)
      if fallback and response.status_code == 405:
      logging.debug("PUT action failed, applying fallback strategy")
      response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
      timeout=timeout)
      return response

      def invoke(self, **kwargs):
      """
      Execute the external call
      """
      is_fallback = kwargs.get('is_fallback', False)
      is_optional = kwargs.get('is_optional', False)
      request_headers = kwargs.get('request_headers', {})
      json_data = kwargs.get('json_data', {})

      response_list = None
      try:
      logging.info("About to make an external *** %s *** call", self.method)
      if self.method == sc.REQUEST_POST:
      response = self.post(self.endpoint, request_headers, json_data, self.timeout)
      elif self.method == sc.REQUEST_PUT:
      response = self.put(self.endpoint, request_headers, json_data,
      self.timeout, fallback=is_fallback)
      else:
      response = self.get(self.endpoint, request_headers, self.timeout)
      response_list, error_list = self.__response_handler(response, is_optional)
      except requests.RequestException as err:
      error_list = err
      return response_list, error_list

      @staticmethod
      def __response_handler(response, is_optional=False):
      """
      Handle API response
      """
      status_code = response.status_code
      if is_optional and status_code == 404:
      return response, None
      if not 200 <= status_code < 300:
      return None, response
      response_list = response.json()
      return response_list, None









      share|improve this question















      This is a wrapper that can be used to do additional external REST call to some API. Since I have to provide support to legacy code so I added three static functions to support them.



      However, the question that comes to my mind is where to actually set default value either in the constructor or it should be in the main function.



      is_optional = kwargs.get('is_optional', False) can also be set directly in constructor. So what is correct way to handle such situations?



      class ExternalRestService:
      def __init__(self, endpoint, method=sc.REQUEST_GET):
      self.endpoint = endpoint
      self.method = method
      self.timeout = sc.REQUEST_TIMEOUT

      @staticmethod
      def get(endpoint, request_headers, timeout):
      """
      Handle GET External Call
      """
      logging.debug("About to make an external *** GET *** to url %s", endpoint)
      response = requests.get(url=endpoint, headers=request_headers,
      timeout=timeout)
      return response

      @staticmethod
      def post(endpoint, request_headers, json_data, timeout):
      """
      Handle POST External Call
      """
      logging.debug("About to make an external *** POST *** to url %s", endpoint)
      request_headers["Content-type"] = "application/json"
      response = requests.post(url=endpoint, headers=request_headers, json_data=json_data,
      timeout=timeout)
      return response

      @staticmethod
      def put(endpoint, request_headers, json_data, timeout, fallback=False):
      """
      Handle PUT External Call
      """
      logging.debug("About to make an external *** PUT *** to url %s", endpoint)
      request_headers["Content-type"] = "application/json"
      response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
      timeout=timeout)
      if fallback and response.status_code == 405:
      logging.debug("PUT action failed, applying fallback strategy")
      response = requests.put(url=endpoint, headers=request_headers, json_data=json_data,
      timeout=timeout)
      return response

      def invoke(self, **kwargs):
      """
      Execute the external call
      """
      is_fallback = kwargs.get('is_fallback', False)
      is_optional = kwargs.get('is_optional', False)
      request_headers = kwargs.get('request_headers', {})
      json_data = kwargs.get('json_data', {})

      response_list = None
      try:
      logging.info("About to make an external *** %s *** call", self.method)
      if self.method == sc.REQUEST_POST:
      response = self.post(self.endpoint, request_headers, json_data, self.timeout)
      elif self.method == sc.REQUEST_PUT:
      response = self.put(self.endpoint, request_headers, json_data,
      self.timeout, fallback=is_fallback)
      else:
      response = self.get(self.endpoint, request_headers, self.timeout)
      response_list, error_list = self.__response_handler(response, is_optional)
      except requests.RequestException as err:
      error_list = err
      return response_list, error_list

      @staticmethod
      def __response_handler(response, is_optional=False):
      """
      Handle API response
      """
      status_code = response.status_code
      if is_optional and status_code == 404:
      return response, None
      if not 200 <= status_code < 300:
      return None, response
      response_list = response.json()
      return response_list, None






      python python-3.x rest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 5 mins ago









      200_success

      127k15148412




      127k15148412










      asked 7 hours ago









      Dinesh Saini

      8511




      8511



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208835%2fwrapper-for-rest-api-calls%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208835%2fwrapper-for-rest-api-calls%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Costa Masnaga

          Fotorealismo

          Sidney Franklin