简体   繁体   中英

How to Use RESTful APIs with Django

I have been trying to integrate a REST API developed using Django-rest framework with another Django web app. But stuck in passing JSON data into the front-end. I would appreciate any help. Here are my respective files.

I have tried two different urls on views.py file, one is AWS API Gateway API, when used no errors are thrown but data is not displayed in front-end.

AWS API JSON data where object is like {'key': 'value'}. it contains only one object though

views.py

def ClientList(request):
      response = requests.get('A URL')
      client_data = response.json()
      return render(request, 'clients/client_list.html', context=client_data)

When I change the url in views.py for django-rest framework API then I get an error like " the JSON object must be str, bytes or bytearray, not list " JSON data where objects are like [{key: value},{key:value}, ...] Table body was changed accordingly.

FrontEnd HTML

<table class="table data-list-view">
             <thead>
               <tr>
                 <th></th>
                 <th>NAME</th>
                 <th>EMAIL</th>
                 <th>MOBILE</th>
                 <th>ADDRESS</th>
                 <th>ROLE</th>
                 <th>ACTION</th>
               </tr>
             </thead>
             <tbody>
               {% for client in client_data %}
               <tr>
                 <td></td>
                 <td class="product-name">{{client.UserId}}</td>
                 <td class="product-category">{{client.Height}}</td>
                 <td class="product-category">{{client.Income}}</td>
                 <td class="product-category">{{client.Age}}</td>
                 <td>
            </td>
               </tr>
               {% endfor %}
            </tbody>
          </table>

Modified view. The returned json list is converted into dictionary. And it worked. Note: dictionary key need to match in html too.

def ClientList(request):
    response = requests.get('http://127.0.0.1:8000/clients/')
    client_data = response.json()
    context = {'client_data': client_data}
    return render(request, 'clients/client_list.html', context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM