How can I retrieve data from my API using JavaScript?
My objective is to present my model data in the form of charts or graphs. For the visualization part, I have chosen Charts.js. Currently, I am able to display a chart in my template with default data. Now, I want to send my model data to the template and integrate it into Chart.js. Chart.js requires data in JSON format, so I have set up an API with the Django REST Framework to get the output.
Folder Structure
visual # -- my project
├── cars # -- API
│ ├── templates
│ │ └── cars
│ │ └── cars_home.html
│ ├── <...>
│ ├── urls.py
│ ├── serializers.py
│ └── views.py
├── charts
├── static
│ ├── css
│ ├── img
│ └── js
│ ├── chart_2.js
│ └── <...>
├── templates
│ ├── base
│ │ └── base.html
│ └── includes
├── visual
│ ├── settings.py
│ ├── urls.py
│ └── views.py *db.sqlite3
└── manage.py
../ cars / urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from cars import views
from cars.views import CarsHomeView
app_name = 'cars'
urlpatterns = [
path('carshome/', CarsHomeView.as_view(), name='cars_home'),
path('cars/', views.SnippetList.as_view()),
path('cars/<int:pk>/', views.SnippetDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
Here is the Output of my API
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"count": 4,
"next": null,
"previous": null,
"results": [
{
"id": 3,
"name": "Audi",
"price": 11
},
{
"id": 4,
"name": "Audi",
"price": 11
},
{
"id": 2,
"name": "Mercedes",
"price": 22
},
{
"id": 1,
"name": "BMW",
"price": 99
}
]
}
How can I fetch the data from my API using JavaScript?
My approach is to first simply print the data in my template to verify that it works. I am also trying two different methods. One is to place the JavaScript code in an external file in my static/js folder, which worked with Chart.js and default values. However, I am also including the JS code in my template, as there may be issues with referencing my API from the static folder.
Here is the template.html. I have added the JS fetch code from a tutorial site, but unfortunately, I could not find a Django-JS example.
../ cars / templates / cars / cars_home.py
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<h1>Welcome to Cars Home</h1>
</div>
<div class="row">
<!--via external js-->
<script src="{% static 'js/chart_2.js' %}"></script>
<!--via internal js-->
<script>
fetch('http://127.0.0.1:8000/cars/?format=json')
.then(response => {
return response.json()
})
.then(data => {
// Work with JSON data here
console.log(data)
})
.catch(err => {
// Do something for an error here
})
</script>
</div>
</div>
{% endblock content %}
Another question I have is, do I need all the additional information in my API output?
{"count":4,"next":null,"previous":null,"
I believe it would be neater if it looked like this?
"results":[{"id":3,"name":"Audi","price":11},{"id":4,"name":"Audi","price":11},{"id":2,"name":"Mercedes","price":22},{"id":1,"name":"BMW","price":99}]}
Update: It appears that my Firefox console was experiencing some issues and was not displaying the array and objects. Switching to the Chrome console resolved the problem and showed me everything.