Developing a REST API using Django

Django for beginners: Making an API for Django (GET)

In this article, we’re going to look at how to make a basic REST API using Django. This is a nice, simple method to implement an API using unique keys. Specifically, we will be looking at a GET request in this article, which requests data from a specified resouce, via HTTP.

In the below, we have a snippet from my signup function of the views.py file. Here, we generate a randomised API key, between 25 and 50 characters of length and save it to the apikeys model, along with the username selected during registration.

    form = SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')

        API_Key = ''
        lent = random.randint(25, 50)
        characters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
        z=0
        while z < lent:
            z=z+1
            API_Key = API_Key + random.choice(characters)

        apikeys.objects.create(user=username, key=API_Key)

We then create a new view in views.py which is called get_skills. Here, we take the API key as a URL parameter and extract all data from the voxi_skills model where the user is associated to that API key. The response is then serialised and returned as JSON.

from django.http import HttpResponse
from django.core import serializers

def get_skills(request, api_key):
    if request.method == 'GET':
        try:
            api_key = str(api_key)

            names = ('id', 'status', 'skill_name', 'creator', 'target_date', 'points')

            query ='''
            SELECT category as id, status, skill_name, creator, target_date, points
            FROM voxi_skills 
            where creator = (select voxi_apikeys.user from voxi_apikeys where key = %s)'''
            
            response = serializers.serialize('json', skills.objects.raw(query, [api_key]), fields=names)

        except:
            response = json.dumps([{ 'Error': 'Not a valid API key'}])

    return HttpResponse(response, content_type='text/json')

We create that URL parameter in the urls.py file, as shown below. The <str:api_key> parameter lets the user pass a value to be used in the view.

#urls.py
 path('api/GET/skills_data/<str:api_key>', views.get_skills)]

When we choose a specific user & pass their API into the URL as below, we see a nice JSON response, with all the data we need.


If we want to extract this data systematically, we can do so using the below structure. This will convert the JSON data into a Pandas dataframe, for easy consumption.

import requests 
import pandas as pd
r =requests.get('https://app.example.com/api/GET/skills_data/zDUR9FdheiGhkOAdsfuHJBUId3fVI8QqxOCnpDegykXb3v9O3ulG5Ms')
r = r.json()

out = []

i = 0
while i < len(r):
    skill_name = r[i]['fields']['skill_name']
    points = r[i]['fields']['points']
    target_date = r[i]['fields']['target_date']

    out.append([skill_name, points, target_date])
    i=i+1
    
df = pd.DataFrame(out)
df.columns = ['skill_name', 'points', 'target_date']
df

In the next article, we will be looking at making a POST API request. Note that these API designs are for learning purposes & may not be appropriate for your application – make sure you review it first!

Total
0
Shares
Previous Article
Django for beginners: Security considerations

Django for beginners: Security considerations

Next Article
Django for beginners: Making an API for Django (POST)

Django for beginners: Making an API for Django (POST)

Related Posts