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.
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.
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.
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.
Now lets retrieve the data of all the products and see if the data is saved.