Search code examples
pythondjangoapi-design

API Integration in Django


I am trying to use the OpenDOTA API in my pet project. At the moment, I am having problem displaying the content of the API into my CBV.

My views.py:

from django.views.generic import TemplateView

import requests
import json

# Create your views here.


class HeroList(TemplateView):
   template_name = 'dota/heroes.html'
   url = 'https://api.opendota.com/api/heroes'
   r = requests.get(url)
   r.text
   result = r.json()

I am lost on how to call the json in my HTML. I've tried running the same code in python IDLE, and when I type the "result" and hit enter, it gives my the dict. Any idea on how should I display the dict into my template?


Solution

  • What you need to do is first dump your json to a dictionary format.

    import json
    from django.shortcuts import render
    
    rdict = json.loads(r.json())
    
    return render(request, template_name=<template name>, context=rdict)
    

    All this reside insides your function inside your views.py

    Now after this using Django template language - https://docs.djangoproject.com/en/1.11/topics/templates/

    You can render data in keys in your dictionary to your template.