0

I would like to use a URL with a 'from' and 'to' date where it is also possible to only provide one of the two arguments. Due to that I need to know via a keyword if only one argument is provided if it is the 'from' or 'to' date.

How can I set the URL such that I can check if either of the arguments are provided and use them as variable in the respective class?

These threads did not solve my problem: flask restful: passing parameters to GET request and How to pass a URL parameter using python, Flask, and the command line.

class price_history(Resource):
    def get(self, from_, to):
        if from_ and to:
            return 'all data'
        if from_ and not to:
            return 'data beginning at date "from_"'
        if not from_ and to:
            return 'data going to date "to"'
        if not from_ and not to:
            return 'please provide at least one date'

api.add_resource(price_history, '/price_history/from=<from_>&to=<to>')
Aaron Scheib
  • 358
  • 4
  • 18

2 Answers2

0

I do think that with the adjustment of this answer you should be able to.

class Foo(Resource):
    args = {
        'from_': fields.Date(required=False),
        'to': fields.Date(required=False)
    }

    @use_kwargs(args)
    def get(self, from_, to):
        if from_ and to:
            return 'all data'
        if from_ and not to:
            return 'data beginning at date "from_"'
        if not from_ and to:
            return 'data going to date "to"'
        if not from_ and not to:
            return 'please provide at least one date'
Joost
  • 3,609
  • 2
  • 12
  • 29
  • it seems I have trouble extracting the arguments from the URL. When assigning the elements in ```args``` they apparently are assigned to ```_Missing``` which results in a ```TypeError``` since the object is not subscritable. I think the issue of passing optional parameters to a URL is rather common, yet I am not able to find a good resource to tackle the problem... – Aaron Scheib Sep 07 '18 at 11:09
0

The answers provided in this thread worked for me. It allows you to leave out optional parameters in the URL completely.

This is the adjusted code example:

class price_history(Resource):
    def get(self, from_=None, to=None):
        if from_ and to:
            return 'all data'
        if from_ and not to:
            return 'data beginning at date "from_"'
        if not from_ and to:
            return 'data going to date "to"'
        if not from_ and not to:
            return 'please provide at least one date'

api.add_resource(price_history,
                '/price_history/from=<from_>/to=<to>',
                '/price_history/from=<from_>',
                '/price_history/to=<to>'
                )
Aaron Scheib
  • 358
  • 4
  • 18