easy_c0mpany80 easy_c0mpany80 - 3 months ago 8
JSON Question

How to return data from an API in Django?

Im trying to learn how to use APIs in Django and I want to return some simple data from one within a web page in html. The API is Mozscape and when running it in a terminal one can obtain the score of a website out of 100 like so:

from mozscape import Mozscape

client = Mozscape(
'api_user_id',
'secret_key')

url = 'http://www.google.com'

get_da = client.urlMetrics(url, cols=68719476736)

print(get_da)


and this prints the following

{u'pda': 100}


the '100' is all I want there. I want a user to enter a url into a form in a page in Django and to get that score int back so I have made the following models, views and form

class DomainAuthority(models.Model):
url = models.URLField(max_length=300)


def __str__(self):
return self.url

class Meta:
verbose_name = 'Domain'
verbose_name_plural = 'Domains'


views.py

def DomainAuthorityView(request):


form = DomainAuthorityForm(request.POST or None)


if form.is_valid():
new_domain = form.save(commit=False)
new_domain.save()


return render(request, 'domain_authority.html', {'form': form})


forms.py

class DomainAuthorityForm(forms.ModelForm):
class Meta:
model = DomainAuthority
fields = ['url']


so I have the form working and when a url is entered in the html form its saved in the admin backend but what I dont know how to do now is how to pass that url into the Mozscape API so that I can get the score back.

I took a look at the Django rest framework and installed it and followed some quick tutorial videos on Youtube and other places but in those examples they were taking saved Django objects such as blog posts and returning them as JSON data which is not what I want to do.

I tried import the API into the views file and then adding this line into then view

get_da = client.urlMetrics(new_domain, cols=68719476736)


but then I get this error after entering the url into the form in the web page

<DomainAuthority: https://www.google.com> is not JSON serializable


what do I need to do here to pass the user inputted urls to the API and return the correct response in a web page?

thanks

Answer

I suggest this approach:

import requests

response = requests.get(url)
json_response = response.json()

score = json_response['key_name']

You can then simply render a template, add the score to the template context and display the value using {{ }}.

You may also want to define a rest_framework serializer (otherwise you don't need django_rest_framework) and verify the response against this serializer in order to ensure that you've received what you expected:

serializer = MySerializer(data=json_response)
  if serializer.is_valid():
      score = json_response['key_name']