So till now we have seen all things that we need to write or configure to make a new rest api and configure new endpoints. A lot of code in a model based structure is repetitive if you look closely. A model needs to respond to GET , POST, PUT , DELETE requests etc through a view. Mixins allow us to fire a new endpoint with all the default functions really fast and we dont need to write all the code that we wrote in previous tutorials. So all we have to do is create our model, serializer and map it to a url. The view also needs update but its very simple, a lot of handling will be done by the framework. Let look at an example.
Step1
Suppose we need an endpoint for company. So create a model and serializer like below
models.pyserializer.py
Step 2
Now mixins provides a bunch of different ways to configure your view. We will look at one of them. But you can explore other configurations as well based on your need.
Create two classes in the views.py file, one to list all the companies and accept a post request to add a company and other to access a single company or delete a single company which will handle GET, PUT, DELETE request.
Notice the mixins used in the CompanyListView, one is the ListModelMixin andother is the CreateModelMixin Mixin. One to list the data and other to create. All we do here is tell the class where to fetch the objects from and which is the serializer class using the queryset variable and the serializer_class variable. Then we have defined two methods GET and POST and used the list and create methods from the mixins to list or create a new object.
Now let looks at more concise way of writing the above functionality on the company view with which we can retrieve a single company or delete a company.
view.py
Notice we have extended from RetrieveDestroyAPIView class from generics. This will abstract everything for us and all that we have to provde is the queryset and serializer_class and its done.
So we have now configured the CompanyView and CompanyListView. Now lets add them to the urls.py file.
In the previous tutorial we have seen how to create rest api and add GET, POST request using independent functions. Now we will see how to create class based views. So with a class based views we can have more separation of concerns of different parts of our application wrapped within a class serving different http requests.
Step 1
It is very simple and aimed at reducing and creating reusable code. Lets create model having seller information as below in the models.py file.
products/models.py
Step 2
Now create a serializer class for the Seller class in the serializer.py file as below
serializer.py
Step 3
Now in the views.py file we define a new class “SellerView” which extends it self from the APIView class. The APIView class is a wrapper class which provided additional standard handling of the various http requests thus abstracting us from the finer details and we can write our functionality faster and in an efficient way. Notice that we have created two methods, one for GET request and one for POST request. The framework will automatically invoke respective methods based on the HttpRequest.
Ignore the additional imports for generics and mixins, we will need them later, we can ignore them for now.
Also note that we have used the format variable and set it None, it means that the function can handle multiple formats. Res t of the code is pretty standard that we have seen in earlier tutorials
Step 4
Now we need to map url pattern to this new Seller class view. See below screenshot where we have added the seller url pattern, we need to pass the as_view return unlike functions itself that we passed earlier with function based views and its done.
Step 5
Its time to test. Lets open the ARC and add one new seller to the rest service and then retrieve it back.
Add new seller to the serviceRetrieve the seller back
So we have now completed how to add a GET request and how to add a POST request. Lets look at an example on how to add a url parameter to the request and use it to fetch data. It is extremely simple. Let look at the steps
Step1
Update the urls.py file as below to parse the integer field that we will pass from in the rest request. The integer field will be the primary key of the product object that we stored earlier in the tutorials. Notice we have added <int:pk> as part of the url pattern which indicates django to map any request with integer values after the product to the get_product function in the views.py we defined in the previous step
Step 2
Now lets move to views.py file in the products app and create a new method to handle the get request for a particular object. Notice how we have passed the pk parameter to this method, this will be the parameter that we will pass in the rest request as the pk of the object that we want to respond with. We will use the serializer created in our previous tutorials to serialize the fetched object and send the response back
Step 3
Now lets look at sample request through ARC chrome plugin. Notice we have sent 4 as the pk of the Product object that we want to retrieve and we have received the response back from the server in json format.
So we have now completed how to add a GET request and how to add a POST request. Lets look at an example on how to add a url parameter to the request and use it to fetch data. It is extremely simple. Let look at the steps
Step1
Update the urls.py file as below to parse the integer field that we will pass from in the rest request. The integer field will be the primary key of the product object that we stored earlier in the tutorials. Notice we have added <int:pk> as part of the url pattern which indicates django to map any request with integer values after the product to the get_product function in the views.py we defined in the previous step
Step 2
Now lets move to views.py file in the products app and create a new method to handle the get request for a particular object. Notice how we have passed the pk parameter to this method, this will be the parameter that we will pass in the rest request as the pk of the object that we want to respond with. We will use the serializer created in our previous tutorials to serialize the fetched object and send the response back
Step 3
Now lets look at sample request through ARC chrome plugin. Notice we have sent 4 as the pk of the Product object that we want to retrieve and we have received the response back from the server in json format.
In the previous tutorial we have created a simple rest framework and configured a “GET” request and successfully displayed data from the server through Django Rest framework. Now lets learn quickly how to add a POST request so that we can add new products through a rest call and then view it later.
Step1
Lets first define a new function in the views.py file in the products app and decorate it with POST attribute of the api_view annotation. Lets call this function as add_product. We fetch the data into the serializer instance of ProductSerializer and then check if the object is a valid Product object. This will confirm if we have received correct types in the fields as defined in our Product class. Once it is termed valid by the framework, we save it into the database.
Step 2
Now that we have defined the function we need to call, we need to configure the url that it should map to. So lets go the url.py in the products app and configure “product” to map to our newly defined function.
Step 3
And we are done with our project configuration. Now lets send a rest call to our server with the product object and check if the save was successful. I am using ARC(Advanced Rest Client) to send the rest request, you can use any one you like.
As you can see I have received a successful response back from the server. I have save a new product having name “Samsung X2” Make sure to choose a correct content type and POST method as shown else it will result into an error.
Step 4
Now lets retrieve the data of all the products and see if the data is saved.
In the previous tutorial we have created a simple rest framework and configured a “GET” request and successfully displayed data from the server through Django Rest framework. Now lets learn quickly how to add a POST request so that we can add new products through a rest call and then view it later.
Step1
Lets first define a new function in the views.py file in the products app and decorate it with POST attribute of the api_view annotation. Lets call this function as add_product. We fetch the data into the serializer instance of ProductSerializer and then check if the object is a valid Product object. This will confirm if we have received correct types in the fields as defined in our Product class. Once it is termed valid by the framework, we save it into the database.
Step 2
Now that we have defined the function we need to call, we need to configure the url that it should map to. So lets go the url.py in the products app and configure “product” to map to our newly defined function.
Step 3
And we are done with our project configuration. Now lets send a rest call to our server with the product object and check if the save was successful. I am using ARC(Advanced Rest Client) to send the rest request, you can use any one you like.
As you can see I have received a successful response back from the server. I have save a new product having name “Samsung X2” Make sure to choose a correct content type and POST method as shown else it will result into an error.
Step 4
Now lets retrieve the data of all the products and see if the data is saved.
We will quickly go through a simple tutorial to create django rest project. It is extremely easy to configure a rest project work with Djange rest framework. Lets go through the steps. I am using PyCharm but it is not required but it will make development much easier with PyCharm. So lets begin.
Step1
Create a new project in PyCharm. Those not using PyCharm can skip this step. Create a directory otherwise.
Step 2
Install django using command “pip install django==3.1” on the terminal. You should see a successful installation of the django library.
Step 3
Now create a django project using command on terminal “django-admin startproject restproject .” “.” is used to create project in the current directory
Step 4
Now that we have the project ready, we will create a django app. The project consist only the configuration information. The app contains the application code. Execute the command “python manage.py startapp products“
Step 5
Lets now create a model to store and retrieve. Lets create a model with name “Product” with fields “name”, “price”, “desc” as per the below screenshot.
Now, execute the command “python manage.py makemigrations” and “python manage.py migrate” . You will see following output. This will create a table in sqlite3 db being used in django.
Step 6
Install the django rest framework executing the command “pip install djangorestframework”
Step 7
Create a new file with name “serializers.py” under the products app as shown in the snapshot below. The “serializers” are used to transform between various formats between the rest client and the server so that communication can happen seamlessly. Here we create a class ProductSerializer class which extends from the ModelSerializer class. The ModelSerializer class maps the fields between the model and serializer and performs validation based on the model defined under the meta class. We don’t need to think much here, just we need to understand that this is required for transofmation between an object to json/xml or vice versa.
Step 8
Now update the views.py file under the products app as below. Here we create a new function “product_list” which takes request as input parameter. We retrieve all the elements in the products table and then use the ProductSerializer created in the previous step to create a json response. Please see 1,2,3 points in the snapshot. We annotate the function to process “GET” request with api_view
Step 9
Now create a urls.py file in the products app if not present already and map “products” url to “product_list” function we created in the views.py file
Now update the urls.py file in the restproject as below to map urls starting with api to the products app
Step 10
We are done with the rest framework basic setup. To demonstrate its working, lets add some values to the products object/table using the admin functionality provided by django.
First register your “product” object to the admin. For this create a file admin.py file under products app and update with below content.
Lets create a superuser to manage admin functionality provided by django. Execute below commands. Provide details of username and password to create a super user
Now lets run our server with command “python manage.py runserver“. This will run the server at http://localhost/8000
Now navigate to url http://127.0.01:8000/admin. you will see below below screenshot and provide username and password created in the step above. for me it is admin/admin. Provide the details and press login.
Now you should see below screenshot
Now lets add a few products to the list, click on add and fill the details
This should add to the products table. This is really easy and fast way to populate some data. The admin functionality can do a lot of this, but will see more of it in future tutorials.
Step 11
Now we are all set to retrieve the list of the products using django rest framework. Hit the url http://127.0.0.1:8000/api/products to see the products we have created in previous step. You should response in json for the products you have created.
We have just now successfully created a basic setup of django restframework. We will look at some advanced features in the next tutorial. The git link for this project is “https://github.com/letsblogcontent/SampleRestProject“
Learn Django project creation. Its is extremely easy and fast to develop with django
We will quickly go through a simple tutorial to create django rest project. It is extremely easy to configure a rest project work with Djange rest framework. Lets go through the steps. I am using PyCharm but it is not required but it will make development much easier with PyCharm. So lets begin.
Step1
Create a new project in PyCharm. Those not using PyCharm can skip this step. Create a directory otherwise.
Step 2
Install django using command “pip install django==3.1” on the terminal. You should see a successful installation of the django library.
Step 3
Now create a django project using command on terminal “django-admin startproject restproject .” “.” is used to create project in the current directory
Step 4
Now that we have the project ready, we will create a django app. The project consist only the configuration information. The app contains the application code. Execute the command “python manage.py startapp products“
Add the newly created app to the settings.py file of the project, in our case it is our restproject.
Step 5
Lets now create a model to store and retrieve. Lets create a model with name “Product” with fields “name”, “price”, “desc” as per the below screenshot.
Now, execute the command “python manage.py makemigrations” and “python manage.py migrate” . You will see following output. This will create a table in sqlite3 db being used in django.
Step 6
Install the django rest framework executing the command “pip install djangorestframework”
Import this into the installed apps of the project’s settings.py
Step 7
Create a new file with name “serializers.py” under the products app as shown in the snapshot below. The “serializers” are used to transform between various formats between the rest client and the server so that communication can happen seamlessly. Here we create a class ProductSerializer class which extends from the ModelSerializer class. The ModelSerializer class maps the fields between the model and serializer and performs validation based on the model defined under the meta class. We don’t need to think much here, just we need to understand that this is required for transofmation between an object to json/xml or vice versa.
Step 8
Now update the views.py file under the products app as below. Here we create a new function “product_list” which takes request as input parameter. We retrieve all the elements in the products table and then use the ProductSerializer created in the previous step to create a json response. Please see 1,2,3 points in the snapshot. We annotate the function to process “GET” request with api_view
Step 9
Now create a urls.py file in the products app if not present already and map “products” url to “product_list” function we created in the views.py file
Now update the urls.py file in the restproject as below to map urls starting with api to the products app
Step 10
We are done with the rest framework basic setup. To demonstrate its working, lets add some values to the products object/table using the admin functionality provided by django.
First register your “product” object to the admin. For this create a file admin.py file under products app and update with below content.
Lets create a superuser to manage admin functionality provided by django. Execute below commands. Provide details of username and password to create a super user
Now lets run our server with command “python manage.py runserver“. This will run the server at http://localhost/8000
Now navigate to url http://127.0.01:8000/admin. you will see below below screenshot and provide username and password created in the step above. for me it is admin/admin. Provide the details and press login.
Now you should see below screenshot
Now lets add a few products to the list, click on add and fill the details
This should add to the products table. This is really easy and fast way to populate some data. The admin functionality can do a lot of this, but will see more of it in future tutorials.
Step 11
Now we are all set to retrieve the list of the products using django rest framework. Hit the url http://127.0.0.1:8000/api/products to see the products we have created in previous step. You should response in json for the products you have created.
We have just now successfully created a basic setup of django restframework. We will look at some advanced features in the next tutorial. The git link for this project is “https://github.com/letsblogcontent/SampleRestProject“