elykl33t elykl33t - 1 month ago 4
HTTP Question

Making HTTP request with Django and deserializing output

So I'm almost totally new to web development as a whole, but have been thrown into a side project using Django to pull and parse data from a web service, and am struggling to understand exactly how things work, even while looking through the Django documentation.

In Django, I have everything set up and working at a basic level (using templates, a page is displayed saying "Hello World").

Now in order to pull the data from the webservice, I need to make a request to a URL of the following format:


In the provided PHP example, they do this using cURL, and then json_decode.

What would I do to get similar functionality out of Django? Thanks in advance!


You would use urllib2 and json standard modules (or, alternatively, the excellent library requests and json):

import urllib2
import json

url = 'http://wbsapi.withings.net/[service_name]?action=[action_name]&[parameters]'
serialized_data = urllib2.urlopen(url).read()

data = json.loads(serialized_data)


If you want it on a page, you want it in a view, which you will need to associate with an url.

Your urls.py will contain something like

from django.conf.urls import patterns, url, include

urlpatterns = patterns('',
    (r'^get_data/$', 'myapp.views.get_data'),

And your myapp/views.py will contain something like

from django.http import HttpResponse
import urllib2
import json

def get_data(request):
    url = 'http://wbsapi.withings.net/[service_name]?action=[action_name]&[parameters]'
    serialized_data = urllib2.urlopen(url).read()

    data = json.loads(serialized_data)

    html = "<html><body><pre>Data: %s.</pre></body></html>" % json.dumps(data, indent=2)

    return HttpResponse(html)

Of course, I don't know how you wanted your data to be displayed, so I just serialized it again :)