1

How can you get a JSON object from an API and then display it nicely in the template?

I've been beating my head against this one for awhile. I have some experience with Django apps, but I've never built an API-only app before so the requests and json libraries are new to me. The API is built with Rails. Stumbling through documentation, I have been able to authenticate and get the data. Now I'm just struggling with how to display it in the template.

Views.py

def accounts(request):
    # To-Do: Better check for user logged with API
    if not request.session.get('api_token'):
        return HttpResponseRedirect('/')
    token = 'Token token=' + request.session.get('api_token')
    path = 'https://myrailsapi.heroku.com/accounts'
    req = requests.get(path, headers={'Authorization': token})
    accounts = req.json()

    print(accounts)

    context = {'accounts': accounts}
    return render(request, 'accounts.html', context)

accounts (the data) looks like this:

[{'created_at': None, 'account_username': 'woof', 'id': 12, 'updated_at': None, 'account_password': 'woof', 'user_id': 3, 'account_type': 'credit', 'institution_name': 'test'}, {'created_at': None, 'account_username': 'ge', 'id': 22, 'updated_at': None, 'account_password': 'ge', 'user_id': 3, 'account_type': 'checking', 'institution_name': 'test2'}]

accounts.html

{% for account in accounts %}
          <div class="card small>
            <div class="card-content white-text">
              <span class="card-title no_margin">
                {{ account.account_name }}
              </span>
              <span class="card_subtitle">
                {{ account.account_type }}
                <span class="right">Balance</span>
              </span>
            </div>
{% endfor %}

How can I access the json data like I would with a queryset/python object?

So far I've tried creating a class and creating a python object as described here.

class j_object(object):
    def __init__(self,j):
        self.__dict__ = json.loads(j)

This gives me an error TypeError: the JSON object must be str, not 'list'. Then I try to parse the data so it is a string and get the error ValueError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2). I know there might be trouble with calling json.loads on accounts because it is set to req.json(), so I've also tried it without it and still no go.

Community
  • 1
  • 1
cpett
  • 40
  • 5

1 Answers1

2

Suggestion

views.py

data = [{'created_at': None, 'account_username': 'woof', 'id': 12, 'updated_at': None, 'account_password': 'woof', 'user_id': 3, 'account_type': 'credit', 'institution_name': 'test'}, {'created_at': None, 'account_username': 'ge', 'id': 22, 'updated_at': None, 'account_password': 'ge', 'user_id': 3, 'account_type': 'checking', 'institution_name': 'test2'}]

print type(data) ## list
result_data = {}
result_data['data'] = data

print type(result_data) ## dict    
print "FFFFFFFFFFFFFFFFFFFFFFfffffffffffffffffffffffffff"
ddd = json.dumps(result_data)
dd = json.loads(ddd)

return render(request,'accounts.html',
        {
          'accounts':dd['data'],
        }
    )


## HTML
{% for account in accounts %}
          <div class="card small>
            <div class="card-content white-text">
              <span class="card-title no_margin">
                {{ account.account_name }}
              </span>
              <span class="card_subtitle">
                {{ account.account_type }}
                <span class="right">Balance</span>
              </span>
            </div>
{% endfor %}
Cadmus
  • 665
  • 7
  • 13
  • That worked beautifully! And it was pretty simple--I still have a lot to learn. Thank you! – cpett Feb 24 '17 at 23:36