<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by vinod krishna on Medium]]></title>
        <description><![CDATA[Stories by vinod krishna on Medium]]></description>
        <link>https://medium.com/@vinodkv2511?source=rss-65a56abd66fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1mbxtbj4xox-3REc</url>
            <title>Stories by vinod krishna on Medium</title>
            <link>https://medium.com/@vinodkv2511?source=rss-65a56abd66fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:38:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vinodkv2511/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to use short circuit evaluation in javascript]]></title>
            <link>https://medium.com/@vinodkv2511/how-to-use-short-circuit-evaluation-in-javascript-c9e17c3e0321?source=rss-65a56abd66fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9e17c3e0321</guid>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[logicaloperators]]></category>
            <category><![CDATA[short-circuit]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[vinod krishna]]></dc:creator>
            <pubDate>Fri, 07 Jun 2019 05:03:20 GMT</pubDate>
            <atom:updated>2019-06-19T04:09:15.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZriIBKb-h5cH2Xkga2q_Ow.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@boukala?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">nabil boukala</a> on <a href="https://unsplash.com/@boukala?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Almost a year back I came across an interesting piece of code which used logical OR (||) in an assignment statement that looked something like this.</p><pre>let testVariable = &quot;Hello&quot;; <br>let evalResult = testVariable || &quot;Bye&quot;; console.log(evalResult);</pre><p>I got really excited about the how of its working and I started asking myself a lot of questions like <em>“Isn’t it supposed to return a boolean?”</em>, <em>“What happens if I use a &amp;&amp; instead of ||?”</em>, <em>“How does javascript evaluate statements with logical operators?”</em> etc. So I started finding answers to my questions and here are my findings.</p><h3>Under the hood</h3><p>Logical operators ( &amp;&amp; and || ) are supposed to be used with booleans and when used with booleans it returns a boolean. But the interesting thing is, these operators are actually returning one of the operands based on their truth value.</p><p>For instance the Logical OR is supposed to return true if either of the operands is true, To do this, javascript starts evaluating the expression from left to right, it first looks at the left operand, if it is true or it has a truthy value it just returns the first operand and doesn’t even check the second operand. if the first operand isn’t true or it doesn’t have a truthy value, javascript blindly returns the second value, as the truthy value of the second operand will be the result of the evaluation of the entire expression.</p><p>Similarly logical AND (&amp;&amp;) checks for the truth value of the first operand and returns it, if its truth value is false else returns the second argument.</p><blockquote><em>This property of javascript logical operaters not evaluating the expression fully before returning the result is called </em><strong>short circuit evaluation.</strong></blockquote><h3>Using logical operators instead of ternary operator</h3><p>We can take advantage of short circuit evaluation to actually replace some ternary operators with logical operators. Many times we end up in situations in which we have to return the value of a variable only when it is true or not null else return a default value or another variable. We can write a simple ternary operator for this situation which can be read as <em>“If a is true return an else return the string” </em>and it looks like this</p><pre>let a; // a is undefined, will be evaluated to false <br>let b = a ? a : &quot;Something else, because a is false&quot;; //ternary operation <br>console.log(b);</pre><pre>a = &quot;I am a, and not false&quot;; //a is a non empty string, will be evaluated to true <br>b = a ? a : &quot;Something else&quot;; //ternary operator console.log(b);</pre><p>The same code can be rewritten by using logical OR as below</p><pre>let a; // a is undefined, will be evaluated to false <br>let b = a || &quot;Something else, because a is false&quot;; //ternary operation <br>console.log(b);</pre><pre>a = &quot;I am a, and not false&quot;; //a is a non empty string, will be evaluated to true b = a || &quot;Something else&quot;; //ternary operator console.log(b);</pre><p>Similarly, we can have a situation where we want to return the variable only when it is false or evaluated to false else return something else. The ternary operator for such a situation with variable name “a” can be read as <em>“If a is false return an else return the string”. </em>Code examples follow</p><pre>let a = false; // a is false <br>let b = a ? &quot;Something else&quot; : a; //return a because a is false <br>console.log(b);</pre><pre>a = true; //a is true <br>b = a ? &quot;Something else&quot; : a; //returns the string because a is true<br>console.log(b);</pre><p>The ternary operators can be rewritten using logical AND (&amp;&amp;) as below</p><pre>let a = false; // a is false <br>let b = a &amp;&amp; &quot;Something else&quot;; //return a because a is false <br>console.log(b);</pre><pre>a = true; //a is true <br>b = a &amp;&amp; &quot;Something else&quot;; //returns the string because a is true <br>console.log(b);</pre><p>This simple trick makes your code much cleaner, concise and fancy.</p><p>Please feel free to share your feedback or any comments with me on my <a href="/service/mailto:vinokv2511@gmail.com">mail</a>. If you like this article and think this can help any of your friends, don’t hesitate to share this.</p><p><em>Originally published at </em><a href="https://nosynerds.com/short-circuit-evaluation/"><em>https://nosynerds.com</em></a><em> on June 7, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9e17c3e0321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and Deploy a REST API with Django and Docker — Part 4]]></title>
            <link>https://medium.com/@vinodkv2511/build-and-deploy-a-rest-api-with-django-and-docker-part-4-19d55ca1053e?source=rss-65a56abd66fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d55ca1053e</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[vinod krishna]]></dc:creator>
            <pubDate>Sat, 18 May 2019 17:42:43 GMT</pubDate>
            <atom:updated>2019-05-18T18:41:16.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build and Deploy a REST API with Django and Docker — Part 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDux77at0fSVHRvbIrKe0w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Q4bmoSPJM18?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">chuttersnap</a> on <a href="https://unsplash.com/search/photos/containers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We have discussed the project setup and creation of endpoints for our todo application over the last <a href="https://nosynerds.com/build-and-deploy-a-rest-api-with-django-and-docker-part-3/">parts</a>. In today’s post, we will see how we can dockerize this django application so that it can be deployed on any cloud with minimal to no configuration.</p><h3>What is Docker</h3><p>Docker is a tool that leverages the concept of linux containers and makes it easier to use these containers with ease. But what is a container in the first place? There are a lot of formal definitions available for a container on the internet. but I find it very easy to think of container as a set of processes and their dependencies packaged in a file system isolated from the host operating system. You can think of them as light weight virtual machines for time being ( but containers are not virtual machines ).</p><h3>Why use Docker</h3><h4>Configuration Management</h4><ul><li>Docker lets the developer package all the dependencies in a distributable package</li><li>So the operations team doesn’t have to worry about configuration management every time they deploy the application</li></ul><h4>Scalability</h4><ul><li>Docker containers are light weight processes, it usually takes only a few seconds to bring up a container which is very fast when compared to bringing up a virtual machine and setting up all dependencies</li><li>Thus it makes your application scale horizontally according to the demands of traffic quickly</li></ul><h3>Docker Terminology</h3><h3>Engine</h3><p>This is the heart of any docker deployment. This is made of two major components</p><h4>Daemon</h4><p>This is the process that manages all docker objects like images, containers and networks. Functionalities of daemon are exposed via the docker API.</p><h4>Client</h4><p>This is the primary way to interact with docker daemon. It sends commands to docker daemon according to user inputs</p><h3>Images</h3><p>Images are the templates to start and run containers. These are analogous to OS disk images that we use in virtual machines. Users can create their own images or download and use existing images from a registry like <a href="https://hub.docker.com/">dockerhub</a>.</p><h3>Containers</h3><p>Containers are runnable instances of docker images. Like we defined before, it is isolated set of processes with all dependencies. User can run, stop, delete or modify a container using the docker client or API.</p><h3>Registry</h3><p>Registry is a server where image repositories can be stored and served from efficiently. We can use a public registry or can setup our own private registry. This is analogous to github</p><h3>Creating todo Docker Image</h3><p>Our docker container should contain our application code and all its dependencies. We need to provide instructions to docker for it to build an image for us. We must provide these instructions in a file called DockerFile.</p><p>Lets get started by creating Dockerfile in the root directory of project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c626196a37df2e9cff862d65d1e4b2a/href">https://medium.com/media/1c626196a37df2e9cff862d65d1e4b2a/href</a></iframe><p>The first instruction in a typical docker file is to specify a base image, we can do that with the use of FROM command. We will be using ubuntu 18.04 as our base image. Now we need to install all the required dependencies like python and pip and all for our django app to run on it. If it were a ubuntu machine, we install any package by running apt install command on a shell like bash. In Dockerfile, we have the RUN command to tell docker to execute any shell command.</p><p>The logical next step is to copy all the application files to the container, we can do this in Dockerfile by COPY command. Now we will write the RUN command to install required python packages using pip.</p><p>The next command we used in Dockerfile is EXPOSE. This command is to inform docker engine that our application listens on a given port and protocol.</p><p>Finally we need to tell docker to start our application every time the container starts, for this purpose we will use CMD. This command takes a list of arguments, first being the actual command to be executed on shell and rest all will be passed as arguments to it.</p><p>Here in CMD we haven&#39;t started our application using manage.py runserver instead we used a command called uwsgi which is an application server. This server needs some configuration like the module it has to start and the port on which it has to run, this can be provided either in command line arguments or in a file. We have created a basic configuration file for uwsgi as below. Please do not use this in production.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f21e6f6df49356fe9d1e4aa622b7091/href">https://medium.com/media/2f21e6f6df49356fe9d1e4aa622b7091/href</a></iframe><h3>Building the Image</h3><p>So now we have a Dockerfile, lets go ahead and build an image with this Dockerfile. We can do this by using docker build command. We need to pass the path to the location where Dockerfile is. Docker tries to find the Dockerfile automatically and attempts to build the image by running commands given in the Dockerfile. If you named your Dockerfile something else, you need to specify the filename in the file option. We can name our image using the tag option.</p><p>docker build -t todo .</p><p>Don’t miss the ‘.’(dot) at the end of the command, I am running the command from the root directory of project, where Dockerfile is located and this ‘.’ is used for current directory in linux. If you are running this from some other path, replace the dot with the path to the folder in which your Dockerfile is present.</p><p>If everything went well, you should be able to see the image that you just built by running the command docker images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eSUoLmadu_pyY4ZB.png" /></figure><h3>Running the container</h3><p>We can run the container with docker run todo, if you open up your browser and try hitting your service at http://localhost:8000, you will see an error page. This is because we haven&#39;t bound the container port with the host port yet. This means that the app has started and is listening on the specified port, but on the docker&#39;s internal network only. To make it accessible from the host machine ( your laptop/desktop ) you must tell docker which host port to bind with which container port. We can do that using the -p option on docker run command like this docker run -p 8001:8000 todo. You can now goto <a href="http://localhost:8001/">http://localhost:8001</a> in your browser and can see your django app page. If it worked, great job, kudos to you for making it so far. However the container is still attached to current terminal i.e. the container processes&#39; standard input and output are attached to the current terminal, you can chose to run your container in background by specifying the -d flag on the run command. So the final command looks like this docker run -d -p 8001:8000 todo. You can see the running containers with command docker ps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YHBPn9rROm_imMxi.png" /></figure><p>With this we mark the end of this part. In the next part of this series we will quickly demo how the same container can be run on multiple cloud providers.</p><p>Thanks a lot for reading this article. Please feel free to share any feedback or ask any questions that you have by mailing me at <a href="/service/mailto:vinodkv2511@gmail.com">vinodkv2511@gmail.com</a>.</p><p><em>Originally published at </em><a href="https://nosynerds.com/build-and-deploy-a-rest-api-with-django-and-docker-part-4/"><em>https://nosynerds.com</em></a><em> on May 18, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d55ca1053e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and Deploy a REST API with Django and Docker — Part 3]]></title>
            <link>https://medium.com/@vinodkv2511/build-and-deploy-a-rest-api-with-django-and-docker-part-3-2a5c1b04061b?source=rss-65a56abd66fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a5c1b04061b</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[vinod krishna]]></dc:creator>
            <pubDate>Sun, 24 Mar 2019 13:54:46 GMT</pubDate>
            <atom:updated>2019-05-18T18:46:24.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAM22UPhQ37dtRM8hnN5Zw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/_Ft-CKcTQFs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Zdeněk Macháček</a> on <a href="https://unsplash.com/search/photos/hummingbird-macro?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Build and Deploy a REST API with Django and Docker — Part 3</h3><p><em>This article was originally published in </em><a href="https://nosynerds.com/build-and-deploy-a-rest-api-with-django-and-docker-part-3/"><em>nosynerds.com</em></a></p><p>In the last two parts of this series, we have discussed project setup and created endpoints required for implementing authentication. In this post, we will create endpoints for managing lists and tasks in a list. Below is a list of endpoints that we will be creating today. You can always find the API doc <a href="https://documenter.getpostman.com/view/5766986/RztsmQbc">here</a>.</p><ul><li>GET /lists/list</li><li>POST /lists/add</li><li>GET /tasks/list</li><li>POST /tasks/add</li></ul><h3>Data Comes First</h3><p>Before creating the endpoint, we will create our required models and migrate. Its a good practise to start with models as data becomes basis for your endpoint most of the time.</p><p>We need at least two models, one for lists and one for tasks. we will also create one more model for list access permissions. So, lets start with creating our first model</p><h3>Models.py</h3><p>Model represents a table in the database, and all its attributes are the fields in that table. Lets create a file called models.py in ToDo folder and all the models for ToDo will be written in this file.</p><p>For Task<em>List</em> model, we need three fields</p><ul><li>id — Unique Auto increment field</li><li>name — Char field of length 50</li><li>description — A Text field</li></ul><p>We need not write SQL queries to create this, Django ORM does that for you, we just have to create a class which extends django.db.models.model as below</p><pre>from django.db import models<br>from django.conf import settings<br><br><br>class TaskList(models.Model):<br><br>    id = models.AutoField(primary_key=True)<br>    name = models.CharField(max_length=50)<br>    description = models.TextField()</pre><p>Similarly for <em>Task</em> Model we need id, name and description fields, and we will have to create a foreign key to List Model. We can do that by using Django’s models.ForeignKey() as shown below</p><pre>class Task(models.Model):<br><br>    id = models.AutoField(primary_key=True)<br>    list = models.ForeignKey(&#39;TaskList&#39;, on_delete=models.CASCADE)  # Foreign key relation to List<br>    name = models.CharField(max_length=50)<br>    done = models.BooleanField(default=False)<br>    description = models.TextField()</pre><p>Finally the <em>ListAccess</em> model, which is a mapping between user and list along with his access level on that list. Here we will create a foreign key to User model along with List model. One more field is created for role. This model looks as below.</p><pre>class ListAccess(models.Model):<br><br>    # Foreign key relation to user model<br>    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)<br><br>    # Foreign key relation to List<br>    list = models.ForeignKey(&#39;TaskList&#39;, on_delete=models.CASCADE)<br><br>    # this field provides access level of a user on a list, possible values owner, guest<br>    role = models.CharField(max_length=5)</pre><h3>Time to migrate</h3><p>We need to migrate, in order to have our additions or changes to be reflected on the actual database. Before we can migrate we must add ToDo to installed apps section in settings.py. Then, you can run makemigrations as shown below. Your tables are not created yet, it just creates the migrations files and can throw errors if some thing is not right.</p><pre>$ python manage.py makemigrations ToDo<br>Migrations for &#39;ToDo&#39;:<br>  ToDo/migrations/0001_initial.py<br>    - Create model List<br>    - Create model ListAccess<br>    - Create model Task</pre><p>Next step is to run migrate, this is when your migrations are applied on the database.</p><pre>$ python manage.py migrate ToDo<br>Operations to perform:<br>  Apply all migrations: ToDo<br>Running migrations:<br>  Applying contenttypes.0001_initial... OK<br>  Applying auth.0001_initial... OK<br>  Applying ToDo.0001_initial... OK</pre><p>Now you can inspect your DB, and can see the new tables created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*fQZdqQxFLbB8fpiY.png" /></figure><h3>Protecting your endpoints</h3><p>Django Rest Framework provides a few authentication classes, but we will create our own to work with the token based login system we created. Lets create a class called <em>ToDoTokenAuthentication</em> which extends rest framework’s BaseAuthentication in a new file called <em>authentication.py. </em>Rest framework requires any authentication class to override the authenticate method which must return a tuple of (user, auth) if authentication is successful else either None can be returned or an AuthenticationFailed exception can be raised.</p><p>Our Authentication scheme expects the token to sent in http authorization header with Bearer prefix. So we start by getting the token and storing to a variable, then we will use pyjwt modules decode method to validate the token with the secret key set in settings. If the token is valid, we can query the auth_user table with username and return the user, in all other cases we consider the authentication is failed. We also check the type of token as we need an access token for authentication and not refresh token.</p><pre>from django.contrib.auth.models import User <br>from django.utils.six import text_type<br>from rest_framework import authentication, exceptions, HTTP_HEADER_ENCODING<br>import jwt<br>from django.conf import settings<br>from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned<br><br><br>class ToDoTokenAuthentication(authentication.BaseAuthentication):<br>    def authenticate(self, request):<br><br>        # Get the token from request header<br>        auth = request.META.get(&#39;HTTP_AUTHORIZATION&#39;, b&#39;&#39;)<br>        if isinstance(auth, text_type):<br>            # Work around django test client oddness<br>            auth = auth.encode(HTTP_HEADER_ENCODING)<br><br>        auth = auth.split()<br><br>        if not auth or auth[0].lower() != &#39;bearer&#39;.encode():<br>            return None<br><br>        if len(auth) == 1:<br>            msg = &#39;Invalid token header. No credentials provided.&#39;<br>            raise exceptions.AuthenticationFailed(msg)<br>        elif len(auth) &gt; 2:<br>            msg = &#39;Invalid token header. Token string should not contain spaces.&#39;<br>            raise exceptions.AuthenticationFailed(msg)<br><br>        try:<br>            token = auth[1].decode()<br>        except UnicodeError:<br>            msg = &#39;Invalid token header. Token string should not contain invalid characters.&#39;<br>            raise exceptions.AuthenticationFailed(msg)<br><br>        # Validating the token<br>        try:<br>            decoded_token_payload = jwt.decode(token, settings.SECRET_KEY, algorithms=&#39;HS256&#39;)<br>        except jwt.exceptions.InvalidSignatureError:<br>            raise exceptions.AuthenticationFailed(&quot;Invalid Signature, Token tampered!&quot;)<br>        except jwt.exceptions.ExpiredSignatureError:<br>            raise exceptions.AuthenticationFailed(&quot;Token expired&quot;)<br>        except (jwt.exceptions.InvalidTokenError, jwt.exceptions.DecodeError):<br>            raise exceptions.AuthenticationFailed(&quot;Invalid Token&quot;)<br><br>        # Checking token type<br>        if not decoded_token_payload[&#39;type&#39;] or decoded_token_payload[&#39;type&#39;] != &#39;access&#39;:<br>            return None<br><br>        user = None<br>        try:<br>            global user<br>            user = User.objects.get(username=decoded_token_payload[&#39;username&#39;])<br>        except ObjectDoesNotExist:<br>            raise exceptions.AuthenticationFailed(&quot;User doesn&#39;t exist&quot;)<br>        except MultipleObjectsReturned:<br>            raise exceptions.AuthenticationFailed(&quot;Multiple users found&quot;)<br><br>        return user, None</pre><h3>POST /lists/add</h3><p>This endpoint should take name and description as body parameters and return a success message along with list object created. Lets start with creating a view and adding a route to it in urls.py.</p><p>This endpoint can be broken down to five steps:</p><ul><li>Authenticating the user</li><li>Reading the request body parameters, here name is a required parameter and description is optional. So if name is not provided or is blank we will respond back with a error message</li><li>Creating a TaskList model object with request parameters and save it to database</li><li>Creating a ListAccess model object with User from request and TaskList object created in previous step and save to database</li><li>Finally respond back with appropriate message and data</li></ul><p>The below code organised in the same sequence of steps as described above along with some exception handling</p><pre>class ListAdd(APIView):<br>    authentication_classes = (ToDoTokenAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def post(self, request):<br>        if request.data.get(&#39;name&#39;, None) and request.data.get(&#39;name&#39;) != &#39;&#39;:<br>            # Getting request data<br>            name = request.data.get(&#39;name&#39;)<br>            description = request.data.get(&#39;description&#39;) if request.data.get(&#39;description&#39;, None) else &#39;&#39;<br><br>            # Writing to database<br>            try:<br>                new_list = TaskList(name=name, description=description)<br>                new_list.save()<br>                new_list_access = ListAccess(user=request.user, list=new_list, role=&#39;owner&#39;)<br>                new_list_access.save()<br><br>                # Responding back<br>                resp_dict = {<br>                    &#39;status&#39;: &#39;success&#39;,<br>                    &#39;message&#39;: &#39;List created successfully&#39;,<br>                    &#39;data&#39;: {&#39;id&#39;: new_list.id, &#39;name&#39;: new_list.name, &#39;description&#39;: new_list.description}<br>                }<br>                resp = Response()<br>                resp.status_code = 201<br>                resp.data = resp_dict<br>            except ValueError as val_err:<br>                # Responding back<br>                resp_dict = {<br>                    &#39;status&#39;: &#39;failed&#39;,<br>                    &#39;message&#39;: &#39;Something went wrong while writing to database, {0}&#39;.format(val_err),<br>                    &#39;data&#39;: {}<br>                }<br>                resp = Response()<br>                resp.status_code = 400<br>                resp.data = resp_dict<br>            except Exception as er:<br>                # Responding back<br>                resp_dict = {<br>                    &#39;status&#39;: &#39;failed&#39;,<br>                    &#39;message&#39;: &#39;Something unexpected happened!, {0}&#39;.format(er),<br>                    &#39;data&#39;: {}<br>                }<br>                resp = Response()<br>                resp.status_code = 400<br>                resp.data = resp_dict<br><br>        else:<br>            resp_dict = {<br>                &#39;status&#39;: &#39;failed&#39;,<br>                &#39;message&#39;: &#39;List name is required but not provided&#39;,<br>                &#39;data&#39;: {}<br>            }<br>            resp = Response()<br>            resp.status_code = 400<br>            resp.data = resp_dict<br><br>        return resp</pre><p>For Authentication, we have used the ToDoTokenAuthentication class that we created earlier. We just have to provide the authentication_classes and permission_classes as shown above and rest framework automatically authenticates the user using the class we provided and responds back with failure message if authentication is failed else it lets the rest of the code to be executed.</p><p>Reading data from the request object is simple, we leverage data and data.get methods provided on the request object and verify if the required value i.e. <em>name </em>is sent in the body and is not empty.</p><p>The next step is to create model objects and save them using the Django ORM. We can create model object by instantiating the model class with values, then calling the save method on this object saves it to the database. First we need to create a TaskList object and save it to database and then create a ListAccess object with the task list object and save it. Here, the order of saving these objects is important as a ForeignKey constraint is set.</p><p>Now we can respond back with a success message and newly created list data if all the above steps are successful else we will respond back with an appropriate error message.</p><h3>GET /lists/list</h3><p>This endpoint will be fairly simple. The only main steps in this endpoint will be</p><ul><li>Authenticate the user</li><li>Fetch lists belonging to this user from databse</li><li>Respond back with list of Lists</li></ul><p>Like other endpoints, we need to create a view and add a route in urls.py.</p><p>Authentication in this endpoint will be exactly same as explained above, so, I will not discuss this here.</p><p>Next step is to fecth lists from database and filter for lists that the current user has access to. Access information is stored in ListAccess table so first we will filter this table for current user which we will get from request and select the list only. Here we have used <em>values_list(‘list’), </em>this is used to get values of one or more columns in a tuple. Since the column list is a foreign_key field, we will get the list of list_ids. We use these list_ids to filter and fetch lists from the TaskList model. Here we have used <em>values() </em>function on the query set, this function is very similar to values_list used above but it returns a dictionary instead of tuple.</p><p>Now we have the array of lists, which we are assinging to data key of resp_dict and sending in Response. This resp_dict is just for aesthetic purpose. we could have directly sent the array of list in response as well.</p><pre>class ListFetch(APIView):<br>    authentication_classes = (ToDoTokenAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def get(self, request):<br>        resp_dict = {<br>            &#39;status&#39;: &#39;&#39;,<br>            &#39;message&#39;: &#39;&#39;,<br>            &#39;data&#39;: None<br>        }<br><br>        try:<br>            list_ids = ListAccess.objects.values_list(&#39;list&#39;).filter(user=request.user)<br>            lists = TaskList.objects.filter(id__in=list_ids).values()<br>            resp_dict[&#39;status&#39;] = &#39;Success&#39;<br>            resp_dict[&#39;message&#39;] = &#39;Retrieved the list of todo lists&#39;<br>            resp_dict[&#39;data&#39;] = lists<br><br>        except Exception as e:<br>            print(e)<br>            resp_dict[&#39;status&#39;] = &#39;Failed&#39;<br>            resp_dict[&#39;message&#39;] = &#39;Something went wrong while fetching data. Error: &#39;+e.__str__()<br>            resp_dict[&#39;data&#39;] = None<br><br>        return Response(resp_dict)</pre><h3>POST /tasks/add</h3><p>This endpoint will be very similar to POST /lists/add. One extra parameter we get in the request is the list_id to which this taks has to be added. We will have to check if a list exists with this id and the current user is the owner of this list before we make changes to the database, else we should respond with a permission error.</p><pre>class TaskAdd(APIView):<br>    authentication_classes = (ToDoTokenAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def post(self, request):<br>        resp_dict = {<br>            &#39;status&#39;: None,<br>            &#39;message&#39;: None,<br>            &#39;data&#39;: None<br>        }<br><br>        req_list_id = request.data.get(&quot;list_id&quot;)<br>        req_task_name = request.data.get(&quot;name&quot;)<br>        req_task_desc = request.data.get(&#39;description&#39;) if request.data.get(&#39;description&#39;, None) else &#39;&#39;<br><br>        if req_list_id and TaskList.objects.filter(id=req_list_id).exists() and \<br>                req_task_name and req_task_name != &#39;&#39;:<br>            try:<br>                task_list = TaskList.objects.get(id=req_list_id)<br><br>                user_perm = ListAccess.objects.filter(user=request.user, list=task_list)<br><br>                if user_perm.count() != 1 or user_perm.first().role != &#39;owner&#39;:<br>                    raise PermissionError(&quot;You do not have permission to edit this list&quot;)<br><br>                new_task = Task(name=req_task_name, list=task_list, description=req_task_desc)<br>                new_task.save()<br><br>                resp_dict[&#39;status&#39;] = &quot;success&quot;<br>                resp_dict[&#39;message&#39;] = &quot;Task creation successful&quot;<br>                resp_dict[&#39;data&#39;] = {&quot;name&quot;: new_task.name, &quot;description&quot;: new_task.description, &quot;done&quot;: new_task.done,<br>                                     &quot;list_id&quot;: new_task.list.id}<br>                resp = Response(resp_dict)<br>                resp.status_code = 200<br><br>            except PermissionError as pe:<br>                resp_dict[&#39;status&#39;] = &quot;failed&quot;<br>                resp_dict[&#39;message&#39;] = pe.__str__()<br>                resp_dict[&#39;data&#39;] = None<br>                resp = Response(resp_dict)<br>                resp.status_code = 403<br>            except Exception as e:<br>                resp_dict[&#39;status&#39;] = &quot;failed&quot;<br>                resp_dict[&#39;message&#39;] = &quot;Something went wrong, Error: &quot;+e.__str__()<br>                resp_dict[&#39;data&#39;] = None<br>                resp = Response(resp_dict)<br>                resp.status_code = 500<br><br>        else:<br>            resp_dict[&#39;status&#39;] = &quot;failed&quot;<br>            resp_dict[&#39;message&#39;] = &quot;Invalid name or list_id passed&quot;<br>            resp_dict[&#39;data&#39;] = None<br>            resp = Response(resp_dict)<br>            resp.status_code = 400<br><br>        return resp</pre><h3>GET /tasks/list</h3><p>This endpoint will take a single mandatory query parameter, list_id, and should return the list of tasks in that list. Similar to the previous endpoint, here we need to check if the user has access to this list before returning the data. Rest of the code is pretty straight forward.</p><pre>class TaskFetch(APIView):<br>    authentication_classes = (ToDoTokenAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def get(self, request):<br><br>        resp_dict = {<br>            &#39;status&#39;: None,<br>            &#39;message&#39;: None,<br>            &#39;data&#39;: None<br>        }<br><br>        try:<br>            list_id = request.query_params.get(&quot;list_id&quot;, None)<br><br>            # checking if the list id is provided<br>            if list_id is None or list_id == &#39;&#39;:<br>                raise ValueError(&quot;Invalid list_id&quot;)<br><br>            # fetching list object<br>            try:<br>                task_list_obj = TaskList.objects.get(id=list_id)<br>            except ObjectDoesNotExist:<br>                raise ValueError(&quot;Invalid list_id&quot;)<br><br>            # checking if the user has permission on the given list<br>            try:<br>                list_perm_qs = ListAccess.objects.get(user=request.user, list=task_list_obj)<br>            except ObjectDoesNotExist:<br>                raise PermissionError(&quot;You do not have permission to access this list&quot;)<br><br>            # fetching tasks<br>            tasks = Task.objects.filter(list=task_list_obj).values()<br><br>            resp_dict[&#39;status&#39;] = &quot;success&quot;<br>            resp_dict[&#39;message&#39;] = &quot;Fetched tasks successfully&quot;<br>            resp_dict[&#39;data&#39;] = tasks<br>            resp = Response(resp_dict)<br>            resp.status_code = 200<br><br>        except PermissionError as pe:<br>            resp_dict[&#39;status&#39;] = &quot;failed&quot;<br>            resp_dict[&#39;message&#39;] = pe.__str__()<br>            resp_dict[&#39;data&#39;] = None<br>            resp = Response(resp_dict)<br>            resp.status_code = 403<br>        except ValueError as ve:<br>            resp_dict[&#39;status&#39;] = &quot;failed&quot;<br>            resp_dict[&#39;message&#39;] = ve.__str__()<br>            resp_dict[&#39;data&#39;] = None<br>            resp = Response(resp_dict)<br>            resp.status_code = 400<br>        except Exception as e:<br>            resp_dict[&#39;status&#39;] = &quot;failed&quot;<br>            resp_dict[&#39;message&#39;] = &quot;Something went wrong, Error: &quot; + e.__str__()<br>            resp_dict[&#39;data&#39;] = None<br>            resp = Response(resp_dict)<br>            resp.status_code = 500<br><br>        return resp</pre><p>We will need one more endpoint to change the status of the task, I am not dicussing it here as it will be very similar to the previous endpoints.</p><p>With this, we have completed the creation of APIs. There are a couple of things I want to talk about before move on.</p><ol><li>Serializers<br> In our endpoints where we have model objects and need to send it in the response as a JSON object we ended up creating a dictionary in place by accessing each value (you can find this in tasks/add endpoint). This is not a scalable approach, instead we shoud have created a serializer class and used that for the conversion part. Django rest framework also provides model serializers which help you achieve this conversion with ease. We haven’t used serializers considering the length of this post.</li><li>Test Cases<br> It is always a good practice to write atleast the unit test cases for your code with a decent amount of coverage. We will try to dicuss this topic in another post.</li></ol><p>In the <a href="https://nosynerds.com/build-and-deploy-a-rest-api-with-django-and-docker-part-4/">next part</a> we will dicuss the dockerization of this django application and how this can be deployed on AWS. You can find the code until this point in my github repository <a href="https://github.com/vinodkv2511/ToDoAPI/tree/5c9ae3fb897d503d5c8db9b4ef09b233b10026d3">here</a>. Please feel free to comment any question you have and do share your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a5c1b04061b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and Deploy a REST API with Django and Docker — Part 2]]></title>
            <link>https://medium.com/@vinodkv2511/build-and-deploy-a-rest-api-with-django-and-docker-part-2-8c375cc5e89f?source=rss-65a56abd66fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c375cc5e89f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[vinod krishna]]></dc:creator>
            <pubDate>Sun, 25 Nov 2018 18:20:46 GMT</pubDate>
            <atom:updated>2019-03-24T14:29:58.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NYhCnCQjSeOTM6j_n53XA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/gr7ZkoZnHXU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Boris Smokrovic</a> on <a href="https://unsplash.com/search/photos/abstract-macro?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Build and Deploy a REST API with Django and Docker — Part 2</h3><p>In <a href="https://medium.com/@vinodkv2511/build-and-deploy-a-rest-api-with-django-and-docker-part-1-3645e7a4d182">part 1</a> of this series, we discussed the project set up and created a hello world API. In this post, we will build the three APIs required for authentication. The below are the endpoints that we will create today.</p><ul><li>POST /login</li><li>POST /login/refresh</li><li>POST /login/register</li></ul><h3>Let’s Migrate first!</h3><p>A Migration is how Django applies your models and their changes to actual database schema. But what’s a model? It is just a Python class representing a table of your database schema. Django comes with a built-in ORM which provides a good number of convenient methods to operate on DB without worrying about the connectors or writing raw SQL queries. We will see more about how to use it a little later.</p><p>When you ran the server, you might have seen an error like this one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*deoc5pZc2jKqr6-WTDpl8g.png" /></figure><p>This is because Django comes with a few inbuilt models in auth and admin apps and these models need to be migrated in-order-to apply these changes to the actual schema. We can run the migration using the <em>migrate </em>command<em>.</em></p><pre>python manage.py migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*Ms1UO0_z0J-6Hxubsd_IWg.png" /></figure><h3>POST /login/register</h3><p>In this post call, we will accept a body with some required parameters like username and password and do some basic validations, then save the user to the database and respond back with an appropriate response. In this endpoint, we are going to use the default user model from <em>django.contrib.auth.</em></p><p>Let&#39;s create a view class for our register endpoint and add a post method.</p><pre># View class to Register users<br>class Register(APIView):<br>    def post(self,request):<br>        data = request.data<br>        return Response(request.data)</pre><p>Add the /login/register path in <em>urls.py</em> and map it to this view class. Now your urlpatterns should look like below</p><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;hello_world&#39;, views.HelloWorld.as_view()),<br>    # Paths for login<br>    path(&#39;login/register&#39;, views.Register.as_view())<br>]</pre><p>At this point, this endpoint does nothing but echo the request body.</p><p>Now that the structure is ready, let’s start building the actual logic. We will need username, password and email so let’s consider them as <strong>required</strong> <strong>parameters </strong>and store these keys to a list required_params. Our first step is to check if these are available and have valid values. To check the validity of required params we created a method <a href="https://gist.github.com/vinodkv2511/3b8fcd871be3cbf321710836497b54c3">validate_required_params</a> which takes the param key, value and return value if it is valid else raises a ValidationError. We handled this exception to respond with a HTTP_400_BAD_REQUEST.</p><p>As we have validated the required parameters, We can create a new User object and set all the required fields directly from the variables. Similarly we will set optional parameters if available. Now all the values that the user passed are set to the new_user object, we call the save method on it, which will save it to database and the user registration is successful. So, we will just respond back with a success message. You can always find fullviews.py file <a href="https://github.com/vinodkv2511/ToDoAPI/blob/master/ToDo/views.py">here</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e59906413edc6fc0e3a947c45672552a/href">https://medium.com/media/e59906413edc6fc0e3a947c45672552a/href</a></iframe><h3>POST /login</h3><p>This endpoint should basically take user credentials, validate them and return access and refresh tokens. Let’s start with creating an APIView with a post method. Credentials should always be passed in Authorization header of HTTP request, it should follow the Authorization: &lt;type&gt; &lt;credentials&gt; syntax. For this endpoint we will use Basic type which requires the credentials to be base64 encoded in &lt;username&gt;:&lt;password&gt; format.</p><p>To handle basic authentication requests, django rest framework has an inbuilt authentication class BasicAuthentication. This has to be added in the Login class along with the IsAuthenticated permission class. This makes the Login endpoint protected by basic authentication. At this point your Login class should look like this.</p><pre>class Login(APIView):<br>    authentication_classes = (BasicAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def post(self, request):<br>        return Response(&quot;Authentication Successful&quot;)</pre><p>Add a new path for login in urls.py. This time, we will use a regular expression in the url_patterns. To use regex, we should use re_path instead of path from django 2.0. Find an explanation for the login regex <a href="https://regex101.com/r/HENS2k/2">here</a>.</p><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;hello_world&#39;, views.HelloWorld.as_view()),<br>    # Paths for login<br>    re_path(r&#39;^login(?:\/)?$&#39;, views.Login.as_view()),<br>    path(&#39;login/register&#39;, views.Register.as_view())<br>]</pre><p>The logical next step is to generate token(s) for authenticated users. For this we will use Json Web Tokens (JWT) with the help of PyJWT. Basically, JWT is structured to have three parts separated by a dot(.). The first part is header which usually contain the type of the token and the hashing algorithm used. The second part is payload, where actual user claims are stored. The last part is the signature, which is basically a hash of header and payload generated using the algorithm specified in the header. You can learn more about jwt <a href="https://jwt.io/introduction/">here</a>.</p><p>Install PyJWT with pip by running this command in your terminal</p><pre>pip install PyJWT</pre><p>Our token payload should contain some recommended claims like issued time, issuer, audience, expiry etc. along with some user information. So, we will create a payload dictionary and sign the jwt with the SECRET_KEY which is generated by django in your app’s settings.py (to use this secret, you have to import settings from django.conf). We will also generate the refresh token in the same way but it will live longer than the access token. Finally send the response with these tokens and some other information. Our Login class will look like below.</p><pre>class Login(APIView):<br>    authentication_classes = (BasicAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def post(self, request):<br>        utc_now = datetime.utcnow()<br>        access_payload = {<br>            &#39;iat&#39;: utc_now,<br>            &#39;exp&#39;: utc_now + timedelta(minutes=60),<br>            &#39;nbf&#39;: utc_now,<br>            &#39;iss&#39;: &quot;http://localhost:8000/login&quot;,  # this has to be replaced with application domain after deploying<br>            &#39;username&#39;: request.user.username,<br>            &#39;email&#39;: request.user.email,<br>            &#39;type&#39;: &#39;access&#39;<br>        }<br><br>        access_token = jwt.encode(access_payload, settings.SECRET_KEY, algorithm=&#39;HS256&#39;)<br><br>        refresh_payload = {<br>            &#39;iat&#39;: utc_now,<br>            &#39;exp&#39;: utc_now + timedelta(days=2),<br>            &#39;nbf&#39;: utc_now,<br>            &#39;iss&#39;: &quot;http://localhost:8000/login&quot;,  # this has to be replaced with application domain after deploying<br>            &#39;username&#39;: request.user.username,<br>            &#39;type&#39;: &#39;refresh&#39;,<br>        }<br><br>        refresh_token = jwt.encode(refresh_payload, settings.SECRET_KEY, algorithm=&#39;HS256&#39;)<br><br>        response = {<br>            &#39;access_token&#39;: access_token,<br>            &#39;expires_in&#39;:  3600,<br>            &#39;token_type&#39;: &quot;bearer&quot;,<br>            &#39;refresh_token&#39;: refresh_token<br>        }<br><br>        return Response(response)</pre><p>This way of signing a token with a hardcoded secret is not recommended, this is not at all meant to be used in production and only for understanding purposes. A more secure way of signing the token is using a RSA key pair but it is not discussed here to keep things simple.</p><p>Since we will use the entire token generation code in the refresh endpoint as well, we created a utils.py and created a generate_token method which takes User as argument and return access_token, refresh_token. So, the updated Login class will look like</p><pre>class Login(APIView):<br>    authentication_classes = (BasicAuthentication,)<br>    permission_classes = (IsAuthenticated,)<br><br>    def post(self, request):<br><br>        access_token, refresh_token = utils.generate_tokens(request.user)<br><br>        if access_token is None or refresh_token is None:<br>            return Response({&quot;error&quot;: &quot;Something went wrong&quot;}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)<br><br>        response = {<br>            &#39;access_token&#39;: access_token,<br>            &#39;expires_in&#39;:  3600,<br>            &#39;token_type&#39;: &quot;bearer&quot;,<br>            &#39;refresh_token&#39;: refresh_token<br>        }<br><br>        return Response(response)</pre><p>And the utils.py file looks like</p><pre>from datetime import datetime, timedelta<br>from django.contrib.auth.models import User<br>import jwt<br>from django.conf import settings<br><br><br>def generate_tokens(user):<br><br>    if not (isinstance(user, User)):<br>        return None<br><br>    utc_now = datetime.utcnow()<br>    access_payload = {<br>        &#39;iat&#39;: utc_now,<br>        &#39;exp&#39;: utc_now + timedelta(minutes=60),<br>        &#39;nbf&#39;: utc_now,<br>        &#39;iss&#39;: &quot;http://localhost:8000/login&quot;,  # this has to be replaced with application domain after deploying<br>        &#39;username&#39;: user.username,<br>        &#39;email&#39;: user.email,<br>        &#39;type&#39;: &#39;access&#39;<br>    }<br><br>    access_token = jwt.encode(access_payload, settings.SECRET_KEY, algorithm=&#39;HS256&#39;)<br><br>    refresh_payload = {<br>        &#39;iat&#39;: utc_now,<br>        &#39;exp&#39;: utc_now + timedelta(days=2),<br>        &#39;nbf&#39;: utc_now,<br>        &#39;iss&#39;: &quot;http://localhost:8000/login&quot;,  # this has to be replaced with application domain after deploying<br>        &#39;username&#39;: user.username,<br>        &#39;type&#39;: &#39;refresh&#39;,<br>    }<br><br>    refresh_token = jwt.encode(refresh_payload, settings.SECRET_KEY, algorithm=&#39;HS256&#39;)<br><br>    return access_token, refresh_token</pre><h3>POST /login/refresh</h3><p>This API is supposed to take refresh token and respond with a new set of access and refresh tokens if the refresh token is valid. We will create this endpoint similar to the login endpoint, but it will not need authentication.</p><p>For validating the refresh token, we will use PyJWT’s decode method. It will throw exceptions if the token is invalid for whatever reason. So, we need to handle these exceptions and respond back with an appropriate error message. After decoding we have to check the token’s type, if it is anything other than refresh, we will respond with a error. Then we will read the username from the token and use this to get the User object from the database. We pass this User object to generate_token method of utils to get access_token and refresh_token. If both of them are not none, we will respond back with tokens. The LoginRefresh class looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0746fff89c1db75d2d6918ce4b3d5dd9/href">https://medium.com/media/0746fff89c1db75d2d6918ce4b3d5dd9/href</a></iframe><p>This kind of token based approach is only secure if all the communications are made over HTTPS. It fails big time if used over HTTP. For real world use you can always rely on OAUTH2 for token based authentication, there are some good packages available for django for implementing OAUTH2.</p><p>This marks the end of part-2, You can find the source code at this point <a href="https://github.com/vinodkv2511/ToDoAPI/tree/503afe43f09133720e50f62b3b039abe02d8cb44">here</a>. In the <a href="https://nosynerds.com/build-and-deploy-a-rest-api-with-django-and-docker-part-3/">next part</a> we will implement the rest of the APIs and authenticate all the requests to these API’s using a custom authentication class. Feel free to post any of your questions or thoughts here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c375cc5e89f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and Deploy a REST API with Django and Docker — Part 1]]></title>
            <link>https://medium.com/@vinodkv2511/build-and-deploy-a-rest-api-with-django-and-docker-part-1-3645e7a4d182?source=rss-65a56abd66fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3645e7a4d182</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[vinod krishna]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 13:41:54 GMT</pubDate>
            <atom:updated>2018-11-25T18:21:31.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X59cooPsNF_XzwnQ9UKNPw.jpeg" /></figure><h3>Build and Deploy a REST API with Django and Docker — Part 1</h3><p>This series aims to give a glimpse at how to quickly build a REST API using Django and deploy the same application with docker on multiple major cloud platforms including Amazon Web Services (AWS), Google Cloud Platform (GCP). In this journey, we will be building a simple API for a To-Do application.</p><p>To begin with, we need to have an API design in place, which means the list of HTTP endpoints along with their methods, parameters, headers, and response structure. It is common practice in the industry to create an API specification document shortly called API spec before the development starts. This serves as an agreement between the frontend developers and the API developers.</p><h3>How does our API look</h3><p>To keep things simple, we will only have a basic set of endpoints even though a good To-Do list application can contain a lot of convenience methods. Below is the list of endpoints we are going to develop.</p><ul><li>POST /login</li><li>POST /login/refresh</li><li>POST /login/register</li><li>GET /lists/list</li><li>POST /lists/add</li><li>GET /tasks/list</li><li>POST /tasks/add</li></ul><p>We will see in detail about each endpoint right before we develop it.</p><h3>Lets start coding</h3><p>Before we begin we need to setup our development environment. If you are using Ubuntu machine python is already installed else you can always download the latest version of python for your platform from <a href="https://www.python.org/downloads/">here</a>. Once you have python and pip ready, lets go ahead and install <em>Django </em>and <em>Django Rest Framework</em>. But, wait this can get quite messy with different versions of the packages. Python has a great way to manage this, <em>Virtual Environments. </em>So first lets install python3-venv and create a virtual environment as below.</p><pre>$ sudo apt-get install -y python3-venv # installing venv on ubuntu<br>$ python3 -m venv todo # creating venv called todo<br>$ source todo/bin/activate # activating the venv</pre><p>Now lets install Django and Django Rest Framework using pip as shown below</p><pre># Installing Django and Django Rest Framework<br>$ pip install Django<br>$ pip install djangorestframework</pre><p>Django provides a good command line tool called django-admin to quickly bootstrap a project. So we will now create ToDo project using django-admin</p><pre>$ django-admin startproject ToDo</pre><p>This command will create a folder structure as show below and our first Django app ready. You can start a development server by using manage.py’s runserver command, Now open your browser and go to localhost:8000 to see Django’s landing page.</p><pre>ToDo<br>├── manage.py<br>└── ToDo<br>    ├── __init__.py<br>    ├── settings.py<br>    ├── urls.py<br>    └── wsgi.py</pre><pre>$ cd ToDo<br>$ python manage.py runserver</pre><p>Lets take a look at two important files from the above folder structure.</p><ul><li><em>settings.py </em>is the file in which we specify all your configurations like installed apps, django middlewares, database connection details, cache configuration, listen address, debug setting etc. We will discuss in detail about some of the settings when needed but you can always have a look at <a href="https://docs.djangoproject.com/en/1.11/ref/settings/">official docs</a> anytime.</li><li><em>urls.py</em> takes care of routing in the app. Here, we specify which view (don’t panic, we will explain what a view is, for time being it is just a python class with some methods to handle http requests) should be called on a particular endpoint or path. This file contains a python list of django.urls.path() instances called urlpatterns. You can have any number of these files and include them in root urls file specified ROOT_URLCONF setting.</li></ul><h3>Time for hello world!</h3><p>In Django, views are either classes or functions which take a request and returns a response. Class based views should subclass View class or any of its children and should define an appropriate view method (get, post, put etc.) corresponding to HTTP method.</p><p>Lets build a simple GET request which will return hello world. To start with create a views.py file, and create a class for our <em>HelloWorld</em> view which extends <em>APIView</em> class of <em>rest_framework.view</em>. Now, we will define the get method to handle HTTP GET requests, it should take atleast two arguments self and request. In method body, simply return a Response object initialized with a string. The final views.py file will look like below.</p><pre>#views.py<br>from rest_framework.views import APIView<br>from rest_framework.response import Response</pre><pre>class HelloWorld(APIView):<br>    def get(self, request):<br>        return Response(&#39;HELLO WORLD! from Django.&#39;)</pre><p>Our view class is ready, Now we have to add a path in urls.py to send the request to the appropriate view. Import the views from current directory and then add a path to <em>urlpatterns</em> as shown below.</p><pre>from django.contrib import admin<br>from django.urls import path<br>from . import views</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;hello_world&#39;, views.HelloWorld.as_view())<br>]</pre><p>We have to add rest_framework to INSTALLED_APPS in settings.py to access any of its functionalities. The installed apps section will look like below.</p><pre># Application definition</pre><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;rest_framework&#39;,<br>]</pre><p>Lets try if it works!. Make sure your server is running, open up your browser and hit <a href="http://127.0.0.1:8000/hello_world">http://127.0.0.1:8000/hello_world</a>. You should see a Django Rest Framework page with <em>HELLO WORLD! from Django. </em>You can also use curl on terminal to make the same request and it looks like below.</p><pre>$ curl <a href="http://127.0.0.1:8000/hello_world">http://127.0.0.1:8000/hello_world</a><br>&quot;HELLO WORLD! from Django.&quot;</pre><p>That’s all for part-1. You can see the source code <a href="https://github.com/vinodkv2511/ToDoAPI/tree/1b9d748cf197a404c8eef4f762a48159d40f1253">here</a>. In the <a href="https://medium.com/@vinodkv2511/build-and-deploy-a-rest-api-with-django-and-docker-part-2-8c375cc5e89f">next part</a> of this series, we will see how to implement a custom token based authentication and create endpoints for users to register, get tokens and refresh an expired token.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3645e7a4d182" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>