Posted under » Django on 19 May 2022
< From DRF Request and Responses.
To consume Rest API JSON, all you need is the Python import requests function.
Response when used with .get, you will have something like CURL or wget but you can use it to consume API or just invoke the page without CRON.
import requests
from django.shortcuts import render
def index(request):
response = requests.get('https://api.com/diagnostic')
# transform the response to JSON objects
todos = response.json()
return render(request, "consume/index.html", {"todos": todos})
While on the template side, your code should look like
{% if todos %}
<ul>
{% for question in todos %}
<li>{{ question.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No flame.</p>
{% endif %}
If you want to insert rows of records to the Student table
from django.shortcuts import render
import requests
from .models import Student
from django.utils import timezone
def index(request):
current_user_id = request.user.id
current_username = request.user.username
call = requests.get('http://api.com/napi/diagnostic')
# transfer the response to json objects
response = call.json()
calltime = str(call.headers['Date'])
for entry in response:
Student.objects.create(student_id = current_user_id,
student_name = current_username,
diagnostic = 'Y',
title = entry['title'],
question = entry['question'],
question_id = entry['id'],
ans = entry['correct_answer'],
api_call_time = calltime,
date_posted = timezone.now(),
bundle=3)
return render(request, "consume/index.html", {"show": response})
Notice that without .get you can request for user.id and .user.username and even user.profile.birthday if it exist.