1
\$\begingroup\$

I kind of started making an API for my site in a Django class based view because it seemed logical and now it has gotten quite large and unruly and I am starting to wonder if I am doing this correctly.

class URLAPI(View):

    def get(self, request):

         if request.GET.get('param') == "foo":
             ...

         elif request.GET.get('param') == "bar":
             ...

         elif request.GET.get('param') == "foo" and request.GET.get('param2') == "arg":
             ...

I did the same thing with the post function creating conditionals for the data that is coming in. What do you think about this?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Huge recommendation: use an existing framework like Django REST framework instead of rolling your own. You'll save a lot of time down the road, because you won't have to handle all of the special casing that's required. (Disclaimer: I'm a maintainer of DRF, but if there is a better API framework that suits your needs, my comment also applies to it) \$\endgroup\$ Commented Aug 17, 2016 at 1:45
  • \$\begingroup\$ I've been meaning to look into that, I had this one nearly complete by the time I realized that did what I needed. Will definitely check it out in the future \$\endgroup\$
    – Joff
    Commented Aug 18, 2016 at 8:52

1 Answer 1

3
\$\begingroup\$

If you are going to have a lot of cases, and each one is quite complex (more than a few lines) I would ditch the if/elif approach.

Instead I would have inner functions, one for each case. Then a dictionary will map each case ('foo', 'bar' etc) to its function.

For example:

class URLAPI(View):
    def get(self, request):
        def act_on_foo():
            ...
        def act_on_bar():
            ...

        func_dict = {'foo': act_on_foo,
                     'bar': act_on_bar}

        param = request.GET.get('param')
        func_dict[param]()

Perhaps an even better design would be to move the act_on_foo and act_on_bar functions to another module to decouple the view from the logic behind it.


And some nitpicking: Try to avoid mixing " and ' in the same piece of code. Pick one and stick to it.

\$\endgroup\$
1
  • \$\begingroup\$ ahh I know about the " and ' it is bothering me too. I switched some time back to " and I didn't want to go through the code and change everything \$\endgroup\$
    – Joff
    Commented Aug 17, 2016 at 1:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.