Implement real-time updates with Django REST Framework | Building Cryptocurrency API
Tags: python, django, webdev, tutorial
Published: 2019-12-15 20:45:13

This post cross-published with [OnePublish](https://www.onepubli.sh)

<h1>What's up DEVs?</h1>

<p>It is time to create another cool project using Django and REST Framework.</p>

<p>In this post we are going to build real-time REST API.</p>

<p>Youtube Channel with video tutorials - <a href="https://www.youtube.com/channel/UCEwYRHE5ZAOMfUaIpCQvjEQ">Reverse Python Youtube</a></p>

<p>Before we go on, please take a look <a href="https://reversepython.net/">REVERSE PYTHON</a>. You can find more articles like this with UI UX design and if you liked it please share on social media or with your friends.</p>

<p>Currently I am interested in cryptocurrency, so I decided to create Cryptocurrency API to use it in React. Well, we need to crawl and update data continuously and avoid from long request timeout.</p>

<h3>Installation and Configuration</h3>
<p>Let's start with creating new project named <b>cryptocurrencytracking</b> and inside your project create app named <b>trackingAPI</b></p>

```
django-admin startproject cryptocurrencytracking
cd cryptocurrencytracking
django-admin startapp trackingAPI
```
<p>and install REST Framework:</p>

```
pip install djangorestframework
```
<p>Once installation completed, open your <b>settings.py</b> and update INSTALLED_APPS.</p>

```python
INSTALLED_APPS = [
    ...

    'rest_framework',
    'trackingAPI',  
]
```

<p>So, I stated before we need to handle long term requests. <b>Celery</b> is the best choice for doing background task processing in the Python/Django ecosystem. It has a simple and clear API, and it integrates beautifully with Django. So, we are using Celery to handle the time-consuming tasks by passing them to queue to be executed in the background and always keep the server ready to respond to new requests.</p>

<p>To install celery run following command:</p>

```
pip install Celery
```

<p>Celery requires a solution to send and receive messages; usually this comes in the form of a separate service called a message broker. We will be configuring celery to use the <b>RabbitMQ</b> messaging system, as it provides robust, stable performance and interacts well with celery.</p>

<p>We can install RabbitMQ through Ubuntu’s repositories by following command:</p>

```
sudo apt-get install rabbitmq-server
```
<p>Then enable and start the RabbitMQ service:</p>

```
sudo systemctl enable rabbitmq-server
sudo systemctl start rabbitmq-server
```

<a href="https://www.rabbitmq.com/install-homebrew.html">Install RabbitMQ on Mac</a>

<p>Once installation completed, add the CELERY_BROKER_URL configuration to the end of <b>settings.py</b> file: </p>

```python
CELERY_BROKER_URL = 'amqp://localhost'
```
<p>Then, create <b>celery.py</b> inside your project.</p>

<img src="https://thepracticaldev.s3.amazonaws.com/i/307eagil3qtve1hhr1qa.png" alt="celery" />

<b>celery.py</b>
```python
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cryptocurrencytracking.settings')

app = Celery('cryptocurrencytracking')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
```
<p>We are setting the default Django settings module for the 'celery' program and loading task modules from all registered Django app configs.</p>
<p>Now inside your <b>__init__.py</b> import the celery:</p>

```python
from .celery import app as celery_app

__all__ = ['celery_app']
```
<p>This will make sure our Celery app loaded every time Django starts.</p>

<h3>Creating model</h3>
<p>In your <b>models.py</b>:</p>

```python
from django.db import models

class Cryptocurrency(models.Model): 
    cryptocurrency = models.CharField(max_length=100)
    price = models.CharField(max_length=100)
    market_cap = models.CharField(max_length=100)
    change = models.CharField(max_length=100)

    def __str__(self):
        return self.cryptocurrency
```
<p>We are going to crawl website named <a href="https://coinranking.com">Coinranking</a> and if you visit the site you can see the field names there.</p>

<img src="https://thepracticaldev.s3.amazonaws.com/i/ww7c9ysvy4kh435timj3.png" alt="Reverse Python" />

<h3>Crawling Cryptocurrency Data</h3>
<p>We will use BeautifulSoup to crawl cryptocurrency values in given URL.</p>
<p>Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work. Run the following command in your terminal to install beautifulsoup:</p>

```
pip install beautifulsoup4
```
<p>Now, create new file named <b>tasks.py</b> inside our app <b>trackingAPI</b>.</p>

```python
# tasks.py

from time import sleep
from celery import shared_task
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request

from .models import Cryptocurrency


@shared_task
# do some heavy stuff
def crawl_currency():
    print('Crawling data and creating objects in database ..')
    req = Request('https://coinranking.com', headers={'User-Agent': 'Mozilla/5.0'})
    html = urlopen(req).read()
    bs = BeautifulSoup(html, 'html.parser')
    # Find first 5 table rows
    rows = bs.find('tbody', class_="table__body").find_all('tr', class_="table__row")[0:5]
    for row in rows:
        cryptocurrency = row.find('span', class_="profile__name").get_text().strip().replace('\n', '')
        values = row.find_all('div', class_="valuta")
        price = values[0].get_text().strip().replace('\n', '')
        market_cap = values[1].get_text().strip().replace('\n', '')
        change = row.find('div', class_="change").find('span').get_text().strip().replace('\n', '')
        print({'cryptocurrency': cryptocurrency, 'price':price, 'market_cap':market_cap, 'change':change}) 
        # Create object in database from crawled data 
        Cryptocurrency.objects.create(
            cryptocurrency = cryptocurrency,
            price = price,
            market_cap = market_cap,
            change = change
        )
        # Sleep 3 seconds to avoid any errors
        sleep(3)
```

<p>@shared_task will create the independent instance of the task for each app, making task reusable. This makes the @shared_task decorator useful for libraries and reusable apps, since they will not have access to the app of the user.</p>

<p>As you see we are crawling our data and cleaning it from useless characters, then creating new object in database.<p>

<p>Once data crawled we need contentiously update these objects.</p>

```python
#tasks.py
@shared_task
def update_currency():
    print('Updating data ..')
    req = Request('https://coinranking.com', headers={'User-Agent': 'Mozilla/5.0'})
    html = urlopen(req).read()
    bs = BeautifulSoup(html, 'html.parser')
    
    rows = bs.find('tbody', class_="table__body").find_all('tr', class_="table__row")[0:5]
    for row in rows:
        cryptocurrency = row.find('span', class_="profile__name").get_text().strip().replace('\n', '')
        values = row.find_all('div', class_="valuta")
        price = values[0].get_text().strip().replace('\n', '')
        market_cap = values[1].get_text().strip().replace('\n', '')
        change = row.find('div', class_="change").find('span').get_text().strip().replace('\n', '')
        print({'cryptocurrency': cryptocurrency, 'price':price, 'market_cap':market_cap, 'change':change})
        data = {'cryptocurrency': cryptocurrency, 'price':price, 'market_cap':market_cap, 'change':change}
       Cryptocurrency.objects.filter(cryptocurrency=cryptocurrency).update(**data)
        
        sleep(3)   
# Run this function if database is empty
if not Cryptocurrency.objects.all():      
    crawl_currency()

while True:
    sleep(15)
    update_currency()
```
<p>As you see, we are crawling data every 15 seconds and updating our objects.</p>

<p>If you want to see the result start celery in terminal:</p>

```
celery -A cryptocurrencytracking worker -l info
```

<p>and go check your admin to see created objects.</p>

<h3>Building API</h3>
<p>Alright! Now our objects are updating and we need to create API using REST Framework.</p>

<p>Now, create <b>serializers.py</b> inside our app.</p>

<p>Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.</p>

```python
#serializers.py

from rest_framework import serializers
from .models import Cryptocurrency


class CryptocurrencySerializer(serializers.ModelSerializer):
    class Meta:
        model = Cryptocurrency
        fields = ['cryptocurrency', 'price', 'market_cap', 'change']
```
<p>The <i>ModelSerializer</i> class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.</p>

<p>For more information take look <a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer">documentation</a></p>

<p>Next step is building API views, so open <b>views.py</b>:</p>

```python
#views.py
from django.shortcuts import render
from rest_framework import generics
from .models import Cryptocurrency
from .serializers import CryptocurrencySerializer

class ListCryptocurrencyView(generics.ListAPIView):
    """
    Provides a get method handler.
    """
    queryset = Cryptocurrency.objects.all()
    serializer_class = CryptocurrencySerializer
```

<p>and finally configure <b>urls.py</b></p>

```python
#urls.py
from django.contrib import admin
from django.urls import path
from trackingAPI.views import ListCryptocurrencyView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', ListCryptocurrencyView.as_view()),
]

```

<p>when you run the server and celery (separate terminals) you will see following result:</p>

<img src="https://thepracticaldev.s3.amazonaws.com/i/yihndhf32hcbtk6ih145.png" alt="Reverse Python" />

<p>Try to refresh the page every 15 second or every minute and you will notice that values are changing.</p>

<p>You can clone or download this project from my GitHub:</p>

{% github raszidzie/Cryptocurrency-REST-API-Django %}

<h3>Mission Accomplished!</h3>
<p>I hope you learned something from this tutorial and make sure you are following me on social media. Also check <a href="https://reversepython.net/">REVERSE PYTHON</a></p>