Django Rest Framework – Part 3

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.

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

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

Create your website with WordPress.com
Get started
%d bloggers like this: