How to Create a REST API -WildTech

There are different approaches to compose an API in Django, however I don’t need you confound them. I will show you the two most ideal approaches to actualize APIs, which will cover practically all the situations.

The two different ways are like one another. They are:

APIView

ModelViewSet

APIView is more nonexclusive, while ModelViewSet is explicit to a Model’s CRUD tasks (for example ModelViewSet is utilized to perform List, Create, Read, Update, Delete (CRUD ) activities just.) Whereas with APIView, you can actualize CRUD tasks as well as other Non-CRUD functionalities like login, logout, produce receipt, download receipt, change fields of different models, and so forth.

You should think, “with APIView we can execute such a great amount of, for what reason to realize ModelViewSet?” Well, you will make sense of the explanation exceptionally not long after actualizing them both.

How about we start with APIView first.

Essential

Make a Django task and application utilizing the accompanying advances.

Introduce Django Rest Framework

Presently, we are prepared with the Django Rest Framework arrangement. How about we make our first API utilizing APIView.

APIView

With APIView, we can execute Get, Post, Delete, Patch, Put techniques. We should make a Book information model and actualize CRUD usefulness on it.

Alter the record –  DemoProject > DemoApplication > models.py and make a model. (Django will make another SQL table in Database.)

Alter the record – DemoProject > DemoApplication > views.py

Alter the record – DemoProject > urls.py

Presently, Migrate and run the task.

Open 127.0.0.1/book/from your program.

Presto! Your first API has made.

Presently Imagine, We have 10 information models (tables in database) and we need to make 10 such APIS and furthermore execute CRUD usefulness for the equivalent. Isn’t that a repetitive errand?

To stay away from redundant code, Django has ModelViewSet where you can spare 1000 of such lines.

ModelViewSet

Alter the document –  DemoProject > DemoApplication > models.py and make another information model.

Make another record  – DemoProject > DemoApplication > serializers.py

Alter the document –  DemoProject > DemoApplication > views.py

Alter the document – DemoProject > urls.py

Presently run the worker and open 127.0.0.1/understudy/from your program.

Look at the view class of APIView and ModelViewSet. In ModelViewSet, we spared heaps of lines of code. Additionally, Django itself is actualizing the CRUD usefulness — less possibilities for us to commit errors.

Leave a Reply

Your email address will not be published. Required fields are marked *