https://www.django-rest-framework.org/community/tutorials-and-resources/

This tutorial was used for 50%, the rest is my own demo:

https://tests4geeks.com/django-rest-framework-tutorial/

Set up django:

Then you get the folder structure, run it:

The install worked successfully! Congratulations!

Then run the command:

Then we can start to create an app

Now we have default project for django

Lets make some models, the Bag and Item class, and also add the apps to settings.py “demo.apps.DemoConfig”, then run:

python manage.py makemigrations demo

If that has no errors then apply the migration.

python manage.py migrate

python manage.py runserver

We now need to register the models within django:

Run

Now we need to add a superuser to do CRUD operations.

(I changed the class model to include __str__ method, view picture)

Now we can add a bag and items:


Now we can install REST:

To perform HTTP-based interaction we have to define rules to convert Django models (python objects) to the json strings and vice versa. This is a serialization/deserialization task. So, let’s define some model-based serializers:

from rest_framework import serializers
from .models import Bag, Item

class BagSerializer(serializers.ModelSerializer):
class Meta:
model = Bag
fields = ‘__all__’

class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ‘__all__’

A viewset is a set of views (controllers in traditional MVC terminology). If you take a look at the ModelViewSet code you’ll see that there’s a lot of functionality automatically added there. You are able to create, view, edit and delete objects in your system (and database). It’s a full CRUD set with http as the interface protocol. Let’s configure two viewsets for our classes:

Now we need to add the view to urls.py, so add the file urls.py to api_apps\demo\urls.py (create this), then change the api_apps\urls.py and add the code fields = ‘__all__’ to both serializer classes if it is not there, it will give an error for version lower then xxx.

Now we can view the Nike bag and the caps item we added before from api

Here is the bag from the api, there is also a possibility to post data (the same goes for item):


Now lets post some new items to the bag:

Great, now lets get it in json format, use the get button or url:

So to wrap this up.

To not get an 404 if you browse http://localhost:8000/ , then add the code to project\urls.py

urlpatterns = [
path(”, admin.site.urls),
path(‘admin/’, admin.site.urls),
path(‘api/’, include(“demo.urls”)),
]

Then you get to the admin page….