Django Rest: Simple POST api view and how to test it in Linux

A simple example to get started. That’s what I came up with working with DRF for the first time. I believe I will find more graceful ways to handle same issues with time and experience.

I fully embrace critics and suggestions, as I aim to learn as all of us.

If you want to pass arguments with request or have some liberties with the arguments, use POST.

Say, I want to get a Data instance based on integer fields year, month, day:

class Data(models.Model):
    day = models.PositiveIntegerField(null=True)
    month = models.PositiveIntegerField(null=True)
    year = models.PositiveIntegerField(null=True)
    text = models.CharField(max_length=100)

urls.py

urlpatterns = [
     path('/api/data/', get_data),
]

views.py

@api_view(['GET', 'POST'])
def user_create(request):
    if request.method == 'POST':
        year = request.data.get('year', None)
        month = request.data.get('month', None)
        day = request.data.get('day', None)
        if day and month and year:
            try: data = Data.objects.get(year=year, month=month, day=day).text
            except: return Response({"error": 'no_such_data', 'request_data': request.data})
            return Response({"text": data.text, 'request_data': request.data})
        else:
             return Response({"error": 'not_enough_data', 'request_data': request.data})
    return Response({"error": "not_post"})

And to test that

http --form POST http://127.0.0.1:8000/api/data/ day=12 year=2020 month=12

It must get you Data for the 12th of December, 2020, if there is an instance like that. If not, you will receive:

"error": 'no_such_data'

Or if an argument is missing:

"error": 'no_such_data'

And if it is not a POST request:

"error": "not_post"

While you develop and test your API, it is a good idea to return request.data to understand what went wrong.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.