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

In this article, we’re going to continue to look at how to make a basic REST API using Django. Specifically, we will be looking at a POST request in this article, which sends data to the application.

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)

Now, we create the view, which will handle the request. It takes 4 URL parameters as input. We then save the new record to the model, using those parameters to populate it, we link the API key back to the user in order to do the mapping.

@csrf_exempt
def put_skill(request, api_key, category, skill_name, points):
    user = apikeys.objects.filter(key=api_key).values_list('user', flat=True)[0]
    if request.method == 'POST':
        try:
            api_key = str(api_key)
            points = int(points)
            target_date = '2023-12-15'
            order = 10
            ordering = 1
            time_required = 0
            status = 'open'

            length = random.randint(5, 50)
            characters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
            thepass = ''
            i=0
            while i < length:
                i=i+1
                thepass = thepass + random.choice(characters)

            skill_id = thepass 
      
            syllabus = 'unknown'

            i = skills(ordering=ordering, order=order, skill_name = skill_name, points=points, time_required=time_required,
                                target_date = target_date, category=category, status=status, skill_id=skill_id, creator=user, syllabus=syllabus)
            i.save()
            response = json.dumps([{ 'Success': 'Skill Added'}])
            return HttpResponse(response, content_type='text/json')
    
        except:
            response = json.dumps([{ 'Error':'err'}])
            return HttpResponse(response, content_type='text/json')

Finally, we create a URL path. Where we have <str: tags, this is where the user can enter their own data to be used in the function. In this case, the user can enter category, skill_name, api_key and points.

#urls.py
path('api/PUT/skills_data/<str:api_key>/<str:category>/<str:skill_name>/<str:points>', views.put_skill),

We can systematically make the POST request in Python as below.

import requests
r = requests.post('https://app.example.com/api/PUT/skills_data/zDsdfUR9FdheiGhksdgfhgOA3fsdfVI8QqxOCnpDegykXb3v9O3ulG5Ms/rust/learn%20about%20variables/10000')
r.content

#b'[{"Success": "Skill Added"}]'

In the next post, I will cover a little bit more about APIs and we may even add another secret key to ensure users can’t post to anothers account. Note that these API designs are for learning purposes & may not be appropriate for your application – make sure you review it first!

Kodey