Monday, May 25, 2015

how to mock REST calls during development?

Hello everyone,

I'm working on a Django application which needs to communicate with a 3rd-party REST API. In production the flow would be like this;
  1. end-user browser sends a request to my django server
  2. my server makes a remote REST call to 3rd party server
  3. 3rd party server responds
  4. my server sends back response to end-user's browser
I'm simulating the above flow during development by using the Httpretty mocking library. Here is how my view looks like;

import httpretty

THIRD_PARTY_SERVER
= http://api.gitlab.com/

def my_view(request):
   
if settings.DEBUG:
       
httpretty.enable()
       
httpretty.register_uri(httpretty.GET, THIRD_PARTY_SERVER, body='{some_mock_response_here}')

    partner_response
= requests.get(THIRD_PARTY_SERVER)

   
if settings.DEBUG:
       
httpretty.disable()
       
httpretty.reset()

   
# Do some stuff here
   
# ...

   
return render(request, 'template.html', context)


For the most part, the above works. I can experiment around without hitting the 3rd-party API. But it doesn't feel good. My mocking code is now part of the view function - not what I consider a good design. Problem is, I'm not sure how else this can be done? Does anyone have any better ideas? Note - I'm not doing any testing here. Just need a way to mock 3rd-party REST responses during development when I run "python manage.py runserver" for debugging/experimentation. 

Ideally, I'd like to move all the mocking code to it's own file and away from my views. This should somehow get activated when I start 'runserver' and work for all my views. 

Puzzled,
Abraham V.






--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/59821a72-3471-4a9a-affd-3875d28e3a03%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment