<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Himanshu👓💻</title>
    <description>The latest articles on DEV Community by Himanshu👓💻 (@ihackthings).</description>
    <link>https://dev.to/ihackthings</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F261441%2F03120c16-26a8-4f63-95f3-e95053c8b097.jpg</url>
      <title>DEV Community: Himanshu👓💻</title>
      <link>https://dev.to/ihackthings</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ihackthings"/>
    <language>en</language>
    <item>
      <title>My 100DaysOfCode Journal Day — 05</title>
      <dc:creator>Himanshu👓💻</dc:creator>
      <pubDate>Tue, 05 Nov 2019 17:21:16 +0000</pubDate>
      <link>https://dev.to/ihackthings/my-100daysofcode-journal-day-05-58j2</link>
      <guid>https://dev.to/ihackthings/my-100daysofcode-journal-day-05-58j2</guid>
      <description>&lt;p&gt;Hey Folks 👋🏻!!&lt;/p&gt;

&lt;p&gt;I am back!! again haha!&lt;/p&gt;

&lt;p&gt;So today, we’ll code together the CRUD of Post/Articles that we did together in &lt;a href="https://medium.com/@aidataguy/my-100daysofcode-journal-day-02-dd08c371946a?source=---------3------------------"&gt;this&lt;/a&gt; blog. So, as usual, we’ll open our backend/app.py file and post our make our code look like this:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    '''Flask App For PyGuy WebSite'''



from flask import (Flask, jsonify, render_template,

request, session, make_response, abort, Response)

from flask_jwt_extended import (

JWTManager, jwt_required, create_access_token,

get_jwt_identity

)

from flask_pymongo import PyMongo

from flask_bcrypt import Bcrypt

from bson.objectid import ObjectId

from http import HTTPStatus




# App Definitions &amp;amp; Configs

app = Flask(__name__, root_path='../frontend')

bcrypt = Bcrypt(app)

jwt = JWTManager(app)

app.config["MONGO_DBNAME"] =  'pysite'

app.config["MONGO_URI"] =  "mongodb://localhost:27017/pysite"

app.secret_key =  'dawudawudbawbfawbfawc3241241j1jnjkjkn141nj4'

app.config['JWT_SECRET_KEY'] =  "dawudawudbawbfawbfawc3241241j1jnjkjkn141nj4"

mongo = PyMongo(app)



# This will be the index route ....




@app.route("/api")

def  index():

return render_template("index.html")




@app.route('/api/v1/posts', methods=['GET'])

def  articles():

articles = mongo.db.articles



output = []



for q in articles.find():

output.append(

{'title': q['title'], 'description': q['description'], 'tags': q['tags']})

return make_response({'code': 200, 'result': output})




@app.route("/api/v1/add_articles", methods=["POST"])

def  add_articles():

"""

add_articles [Adds new article]



[Saves it to databases, with tags, description etc...]



:return: [description]

:rtype: [type]

"""

article = mongo.db.articles

title = request.json['title']

description = request.json['description']

tags = request.json['tags']

article_id = article.insert(

{'title': title, 'description': description, 'tags': tags})



new_article = article.find_one({'_id': article_id})

output = {'title': new_article['title'],

'description': new_article['description'], 'tags': new_article['tags']}

return make_response({'code': 201, 'result': output})




@app.route("/api/v1/edit_article/&amp;lt;article_id&amp;gt;", methods=["GET", "POST"])

def  edit_article(article_id):

article = mongo.db.articles

title = request.json['title']

description = request.json['description']

tags = request.json['tags']

for art in article.find({"_id": ObjectId(article_id)}):

if art['_id'] == ObjectId(article_id):



updated_data = {

'title': title,

'description': description,

'tags': tags

}



existing_data = {"title": art['title'],

"description": art['description'], "tags": art['tags']}



if updated_data != existing_data:

update_article = article.update(

{"_id": art['_id']},

{"$set": updated_data}, upsert=False)

return make_response({'code': 200, "Message": update_article})

else:

return make_response({'code': 404, 'Message': 'No Code Updated'})



return make_response({'code': 404, "Message": "Article Not Found"})




@app.route("/api/v1/delete/&amp;lt;article_id&amp;gt;", methods=["DELETE"])

def  delete(article_id):

article = mongo.db.articles

for art in article.find({"_id": ObjectId(article_id)}):

if art['_id'] == ObjectId(article_id):

article.remove(

{"_id": art['_id']})

return make_response({'code': 200, "Message": "Article Deleted Successfully"})




def  new_user_creation():

"""[User Creation]

Params: Username

Params: Password

Uses: Bcrypt to generate Password

Uses: Users Table

"""

user = mongo.db.users

gen_hashpass = bcrypt.generate_password_hash(request.json['password'])

user.insert(

{'username': request.json['username'], 'password': gen_hashpass})

session['username'] = request.json['username']




@app.route("/api/v1/login", methods=['POST', 'GET'])

def  login():

"""[Logins The User]



Returns:

[Access Token] -- [Returns access token, with code 200]

[!Access Token] -- [Returns code 404]

"""

user = mongo.db.users

username = request.json['username']

password = request.json['password']



for user_details in user.find():

if user_details['username'] == username and bcrypt.check_password_hash(user_details['password'], password):

access_token = create_access_token(identity=username)

return make_response({'code': 200, 'access_token': access_token, "Message": "Ok"})

return make_response({'code': 404, 'Message': "User Not Found, would you like to create one?"})




@app.route("/protected", methods=["GET"])

@jwt_required

def  protected():

"""

protected [JWT]



[extended_summary]



Returns:

[Success] -- [Return Current User If Login Is Successful]

"""

current_user = get_jwt_identity()

return make_response({'code': 200, "logged_in_as": current_user})




@app.route("/api/v1/register", methods=['POST', 'GET'])

def  create_user():

"""

create_user [Route call to create a user]



[Uses the new_user_creation method]



:return: [201, successfully created + Username]

:rtype: [In case of failure, returns, 403]

"""

user = mongo.db.users



# Users table definition for MongoDB

if request.method ==  'POST':

user_exists = user.find_one({'username': request.json['username']})



if user_exists is  None:

new_user_creation()

return make_response({'code': 201, "Message": "User {} has been created successfully".format(session['username'])})

return make_response({'code': 403, "Message": 'Already Exists'})


if __name__ ==  "__main__":

app.run(debug=True)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now, let’s walk through code as we alwaaaaaays do 😁.&lt;/p&gt;

&lt;p&gt;First, we’ll do some facelifting(dunno how i got to use word every now and then)&lt;/p&gt;

&lt;p&gt;we will introduce, docstring because we’ll be introducing swagger later for documentation. so we did something like:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"""

add_articles [Adds new article]

[Saves it to databases, with tags, description etc...]

:return: [description]

:rtype: [type]

"""
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  EDIT POST
&lt;/h3&gt;

&lt;p&gt;Now, We’ll now make our Edit/Update route in our CRUD. Let’s do that now…&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route(“/api/v1/edit_article/&amp;lt;article_id&amp;gt;”, _methods_=[“GET”, “POST”])

_def_ edit_article(_article_id_):

article = mongo.db.articles

title = request.json[‘title’]

description = request.json[‘description’]

tags = request.json[‘tags’]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The code above is pretty much same in every article route. So we don’t can simply skip that and go to next part ….&lt;/p&gt;

&lt;p&gt;So, in the code below I will loop through articles using art keyword(not much good keyword usage by me 😒) and look for the ID we’ll pass as parameter in&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route(“/api/v1/edit_article/&amp;lt;article_id&amp;gt;”, _methods_=[“GET”, “POST”])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;notice, &lt;strong&gt;article_id&lt;/strong&gt; passed as param here, we will use it next.&lt;/p&gt;

&lt;p&gt;Than we’ll compare if article_id that we’re passing does matches with the article id in collection. If yes, we’ll define the dictionary of update_data which will be the data that we’ll hold the data that we’ll be updating.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for art in article.find({“_id”: ObjectId(article_id)}):

if art[‘_id’] == ObjectId(article_id):

updated_data = {

‘title’: title,

‘description’: description,

‘tags’: tags

}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now, next we will define our existing dictionary, which means the data we currently have saved in our db..&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;existing_data = {"title": art['title'],

"description": art['description'], "tags": art['tags']}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Okay, next step is we’ll check if our data that we’re passing as data to be updated is &lt;strong&gt;equal to or not equal&lt;/strong&gt; &lt;strong&gt;to&lt;/strong&gt; our existing data. If data is not same as our existing data it will get updated, with upsert set to &lt;strong&gt;False (will explain what upsert is).&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if updated_data != existing_data:

update_article = article.update(

{"_id": art['_id']},

{"$set": updated_data}, _upsert_=False)

return make_response({'code': 200, "Message": update_article})

else:

return make_response({'code': 404, 'Message': 'No Code Updated'})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We can check the same in our database, let me show you to confirm that’s working.&lt;/p&gt;

&lt;p&gt;This is the data I am seeing when I am browsing my collection&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
 "title": "Hi this is the blacksheep post",  
 "description": "This ïś the aæaãaæaãaæaãaæaãaæaãaæaã",  
 "tags": "hi, testing, zero post"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bX6AYl52--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AEsRPyb8jfGeq2VhdVNZhzA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bX6AYl52--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AEsRPyb8jfGeq2VhdVNZhzA.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To check if data is getting updated.&lt;/p&gt;

&lt;p&gt;we will send new request data set like this.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
 "title": "Hi this is the this is awesome post",  
 "description": "This ïś the awesome post",  
 "tags": "hi, testing, awesome post"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Do a request for update article like this from our edit_article path, your article ID would be different case in my case it’s 5dbb07a99b5d9fc1d7127fa8&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--c4pCmR3p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2Atcwsk_2O7abtljn-bTIcYQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--c4pCmR3p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2Atcwsk_2O7abtljn-bTIcYQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So this shall get updated right? let’s see in our DB if that’s updated&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fhlwGO7T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AUMjQI62Tn4sDbyFbdRt1Wg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fhlwGO7T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AUMjQI62Tn4sDbyFbdRt1Wg.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;YAY!! our data got updated 🙌🏻.&lt;/p&gt;

&lt;h3&gt;
  
  
  Delete Post
&lt;/h3&gt;

&lt;p&gt;So next stop.. DELETE. To this we will use “&lt;strong&gt;DELETE&lt;/strong&gt;” method. Let’s check the code to delete. The code below uses delete method with article_id as parameter.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route("/api/v1/delete/&amp;lt;article_id&amp;gt;", _methods_=["DELETE"])

def delete(_article_id_):

article = mongo.db.articles

for art in article.find({"_id": ObjectId(article_id)}):

if art['_id'] == ObjectId(article_id):

article.remove(

{"_id": art['_id']})

return make_response({'code': 200, "Message": "Article Deleted Successfully"})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;so we’ll again use a loop with .find method looking for &lt;strong&gt;id&lt;/strong&gt; key which have article_id as value. P.S ObjectID is method imported from bson.ObjectID to actually convert parameter id as mongo compatible and do a comparison.&lt;/p&gt;

&lt;p&gt;We than did an if/else block to do the comparison and than called &lt;strong&gt;.remove&lt;/strong&gt; method to remove the respective post with that article.&lt;/p&gt;

&lt;p&gt;Let’s see how we did that delete call in postman, pass the relative article id&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EenJ9Z9k--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AjsNVmZAVrGlh-uAp644adQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EenJ9Z9k--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AjsNVmZAVrGlh-uAp644adQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When you hit send it will delete the related post. You can check the collection to see if the post actually go deleted.&lt;/p&gt;

&lt;p&gt;Awesome!!! we deleted our post….&lt;/p&gt;

&lt;p&gt;That’s it folks.. We’ve successfull done the CRUD implementation on our Posts.&lt;/p&gt;

</description>
      <category>python</category>
      <category>webdev</category>
      <category>code</category>
      <category>flask</category>
    </item>
    <item>
      <title>My 100DaysOfCode Journal — Day03/04</title>
      <dc:creator>Himanshu👓💻</dc:creator>
      <pubDate>Sun, 03 Nov 2019 18:11:39 +0000</pubDate>
      <link>https://dev.to/ihackthings/my-100daysofcode-journal-day03-04-5dhl</link>
      <guid>https://dev.to/ihackthings/my-100daysofcode-journal-day03-04-5dhl</guid>
      <description>&lt;p&gt;Hey folks!&lt;/p&gt;

&lt;p&gt;So it’s day 03 and day 04 of my 100daysofcode journal.&lt;/p&gt;

&lt;p&gt;Here is a list of what we’ll be covering today:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Features listing&lt;/li&gt;
&lt;li&gt; Login Implementation🤩&lt;/li&gt;
&lt;li&gt; JWT integration.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Features listing
&lt;/h3&gt;

&lt;p&gt;Here is the list of features we’ll be introducing for our application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authentication&lt;/strong&gt;: JWT&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SMS&lt;/strong&gt;: &lt;a href="https://twitter.com/hashtag/twilio?src=hashtag_click"&gt;#twilio&lt;/a&gt; by &lt;a href="https://twitter.com/twilio"&gt;@twilio&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Email&lt;/strong&gt;:&lt;a href="https://twitter.com/Mailchimp"&gt;@Mailchimp&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Project Management&lt;/strong&gt;: &lt;a href="https://twitter.com/hashtag/Trello?src=hashtag_click"&gt;#Trello&lt;/a&gt; by &lt;a href="https://twitter.com/trello"&gt;@trello&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Comments&lt;/strong&gt;: custom&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Payments&lt;/strong&gt;: stripe by &lt;a href="https://twitter.com/stripe"&gt;@stripe&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Login Implementation
&lt;/h3&gt;

&lt;p&gt;So continuing with our code last time, we’ll be implementing login credentials as below. You might see that I have given some facelift, i will be explaining at some point.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route("/api/v1/login", _methods_=['POST', 'GET'])

def login():
user = mongo.db.users
username = request.json['username']
password = request.json['password']
for user_details in user.find():
if user_details['username'] == username and bcrypt.check_password_hash(user_details['password'], password):
access_token = create_access_token(_identity_=username)
return make_response({'code': 200, 'access_token': access_token, "Message": "Ok"})
return make_response({'code': 404, 'Message': "User Not Found, would you like to create one?"})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The code is at followng URL :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/aidataguy/pyguy/tree/Part3"&gt;https://github.com/aidataguy/pyguy/tree/Part3&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So let me walk you through the code. Here, we will be defining our route for login. I have made URL’s a bit unique by making it something like:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/api/v1/login
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Below I’ve defined the login url with GET and POST both. I&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route("/api/v1/login", _methods_=['POST', 'GET'])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So, next we’ll define the user table object and username which we’ll be getting from request(Postman)&lt;/p&gt;

&lt;p&gt;def login():&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user = mongo.db.users

username = request.json['username']

password = request.json['password']
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Next, we’ll loop through existing users in table to find if the user exists. Also, before doing that, we’ll install following packages&lt;/p&gt;

&lt;p&gt;flask_bcrypt &amp;amp; flask by running following command&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install flask-jwt-extended flask-bcrypt
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Then we would need to add definition at top of the our backend/app.py&lt;/p&gt;

&lt;p&gt;from flask_pymongo import PyMongo&lt;br&gt;&lt;br&gt;
from flask_bcrypt import Bcrypt&lt;/p&gt;

&lt;p&gt;Now that we have that sorted, we’ll loop through the user detail in users table. We are checking if the username and password do exists in the database. We’re using .check_password_hash method of bcrypt. You can check out the bcrypt the &lt;a href="https://flask-bcrypt.readthedocs.io/en/latest/"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for user_details in user.find():  
if user_details[‘username’] == username and bcrypt.check_password_hash(user_details[‘password’], password):  
access_token = create_access_token(_identity_=username)  
return make_response({‘code’: 200, ‘access_token’: access_token, “Message”: “Ok”})  
return make_response({‘code’: 404, ‘Message’: “User Not Found, would you like to create one?”})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Awesome!! we have the login implemented. But before we could actually check this, we have to do changes to our &lt;strong&gt;register&lt;/strong&gt; method. So here are changes I have implemented. I have implemented a new_user_creation method which we can be used anywhere in app.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def new_user_creation():
user = mongo.db.users
gen_hashpass = bcrypt.generate_password_hash(request.json['password'])
user.insert(
{'username': request.json['username'], 'password': gen_hashpass})
session['username'] = request.json['username']
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The bcrypt’s generate_password_hash method actually helps in generating hash passwords and than with help of our check_hash_password method we can do comparison later on in &lt;strong&gt;Login&lt;/strong&gt; method&lt;/p&gt;

&lt;h3&gt;
  
  
  JWT integration
&lt;/h3&gt;

&lt;p&gt;We’ll introduce JWT extended in our application like so. Update the import and app configs to something like this in app. py . Also, we’ve introduced JWT_SECRET_KEY &amp;amp; app_secret key which will be used JWT. Additionally, we used JWTManager(app) so JWTManager can be used across the app.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'''Flask App For PyGuy WebSite'''
from flask import (Flask, jsonify, render_template,
request, session, make_response)
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
)
from flask_pymongo import PyMongo
from flask_bcrypt import Bcrypt
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h1&gt;
  
  
  App Definitions &amp;amp; Configs
&lt;/h1&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app = Flask(__name__, _root_path_='../frontend')
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
app.config["MONGO_DBNAME"] = 'pysite'
app.config["MONGO_URI"] = "mongodb://localhost:27017/pysite"
app.secret_key = 'dawudawudbawbfawbfawc3241241j1jnjkjkn141nj4'

app.config['JWT_SECRET_KEY'] = "dawudawudbawbfawbfawc3241241j1jnjkjkn141nj4"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;mongo = PyMongo(app)&lt;/p&gt;

&lt;p&gt;You can read more about JWT-Extended &lt;a href="https://flask-jwt-extended.readthedocs.io/en/stable/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Every aspect of JWT based authentication is based on access tokens. So what we would be needing here is implement an protected method that would do all the heavy lifting in terms of providing and validating access_token. So let’s walk through the current code below.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route(“/protected”, _methods_=[“GET”])  
@jwt_required  
_def_ protected():  
current_user = get_jwt_identity()  
return make_response({‘code’: 200, “logged_in_as”: current_user})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;We are defining a GET method for protected route, which would use jwt_required method, and next we defined the method. Current user is set to get_jwt_identity, which will get the identity of the user. If it’s true, we’ll send a response.&lt;/p&gt;

&lt;p&gt;Now in order to get the access token we have to make changes to our &lt;strong&gt;login&lt;/strong&gt; method. So after looping through the users, we will create access token by setting the identity as username, because username is the entity that we would like access token to be generated for. If all is successful, we will make a response sending access token and 200 code.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route("/api/v1/login", _methods_=['POST', 'GET'])

def login():
user = mongo.db.users
username = request.json['username']
password = request.json['password']
for user_details in user.find():

**if user_details['username'] == username and bcrypt.check_password_hash(user_details['password'], password):**

**access_token = create_access_token(_identity_=username)**

**return make_response({'code': 200, 'access_token': access_token, "Message": "Ok"})**

return make_response({'code': 404, 'Message': "User Not Found, would you like to create one?"})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Voila!! we’ve created access token and authenticated our user too 😎&lt;/p&gt;

&lt;h3&gt;
  
  
  POSTMAN TIME!!
&lt;/h3&gt;

&lt;p&gt;Now, we shall test our JWT implementation. You can open postman and first do a register call to register a new user with that will use our bcrypt implementation once user is created, for login request url add &lt;strong&gt;localhost:5000/api/v1/login&lt;/strong&gt; then in Body -&amp;gt; raw (select JSON from dropdown) and paste your registered user context like so :&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{  
 "username": "admin",  
 "password": "b lalala Password"  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Refer to the below image in case you aren’t sure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--682i5BBW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A6tlr4LK9h9hPKJFhjUpRPw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--682i5BBW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A6tlr4LK9h9hPKJFhjUpRPw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That’s all folks!! we’ve successfully implemented JWT &amp;amp; Bcrypt.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>api</category>
    </item>
    <item>
      <title>My 100daysOfCode Journal — Day 02</title>
      <dc:creator>Himanshu👓💻</dc:creator>
      <pubDate>Fri, 01 Nov 2019 19:05:29 +0000</pubDate>
      <link>https://dev.to/ihackthings/my-100daysofcode-journal-day-02-321c</link>
      <guid>https://dev.to/ihackthings/my-100daysofcode-journal-day-02-321c</guid>
      <description>&lt;p&gt;Hey folks!&lt;/p&gt;

&lt;p&gt;So it’s day 02 of my 100daysofcode journal. Today, we’ll do first POST call for flask api.&lt;/p&gt;

&lt;p&gt;Here is a list of what we’ll be covering today:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Setup ROBO 3T
&lt;/li&gt;
&lt;li&gt;Writing POST Call 🤩
&lt;/li&gt;
&lt;li&gt;Using our letterbox aka POSTMAN :)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Setup ROBO 3T&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;We’re going to setup ROBO 3T on mac, so in order to install that you need to go to &lt;a href="https://robomongo.org/download"&gt;https://robomongo.org/download&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you’ve installed ROBO 3T, open the application and than follow the steps to add a new MongoDB connection. P.S for tutorial purposes, I haven’t actually used any DB authentication, will do so later down the line .&lt;/p&gt;

&lt;p&gt;So as soon as you open your ROBO 3T app , you will be greeted with something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qwMeDQzr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1200/1%2A8bFSCWuq9augurhhaxkuWw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qwMeDQzr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1200/1%2A8bFSCWuq9augurhhaxkuWw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we’re going to connect do the connection. Click on the small computer like icon on top left and fill up the connection details like shown(name it whatever you want) and than hit saveeeeee!!!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FEnxZ6Fx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AVf1Af9ToXZeSKxD8JqPJdQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--FEnxZ6Fx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AVf1Af9ToXZeSKxD8JqPJdQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Okay , now that we have our connection in place. We will go back to our window and select the connection and click on connect button&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tx6_BZuq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2ABLTCuINd5GqOPi-QpIiFRA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tx6_BZuq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2ABLTCuINd5GqOPi-QpIiFRA.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On next window that opens we will create our very first database first here. Select the connection name and right click on connection name and click on create database option on the menu presented like shown below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--g7VL4agV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A9jSH0emd472tjonXkBPTrQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--g7VL4agV--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A9jSH0emd472tjonXkBPTrQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As soon as you click on “Create database” option you will see a window to post Database Name and than you need to enter name and hit create.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bPeFf4KZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AD00Qi-5x-6BiQ76r_-zfTA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bPeFf4KZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AD00Qi-5x-6BiQ76r_-zfTA.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we have our database created. If you all goes right there shall be the db in left pane like shown in figure above.&lt;/p&gt;

&lt;h3&gt;
  
  
  Writing POST Call
&lt;/h3&gt;

&lt;p&gt;We are going to write our very first POST call, excited?? Let’s do it!&lt;/p&gt;

&lt;p&gt;So continuing with our app.py as we’ve done in my last post*&lt;em&gt;.&lt;/em&gt;* If you don’t know what we’re talking about here, you can go through my post &lt;a href="https://medium.com/@aidataguy/my-100daysofcode-journal-day-01-202767ecdc27"&gt;&lt;strong&gt;here&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open the very same file and paste the code right after our very first &lt;strong&gt;GET&lt;/strong&gt; call before the &lt;strong&gt;main&lt;/strong&gt; declaration like this.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route(“/add_articles”, _methods_=[“POST”])
def_ add_articles():
    article = mongo.db.articles
    title = request.json[‘title’]
    description = request.json[‘description’]
    tags = request.json[‘tags’]
    article_id = article.insert(
     {‘title’: title, ‘description’: description, ‘tags’: tags})
    new_article = article.find_one({‘_id’: article_id})
    output = {‘title’: new_article[‘title’],
    ‘description’: new_article[‘description’], ‘tags’: new_article[‘tags’]}

    return jsonify({‘result’: output})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Don’t worry, I will explain the code as I always do 😁.&lt;/p&gt;

&lt;p&gt;Okay so as you know our articles had following fields, &lt;strong&gt;title, description, tags.&lt;/strong&gt; So accordingly we want to post our data in same manner right?&lt;/p&gt;

&lt;p&gt;So first thing first,&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route(“/add_articles”, _methods_=[“POST”])
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The code above is definition of POST route which is using route &lt;strong&gt;add_articles,&lt;/strong&gt; so something like this will be our url “&lt;strong&gt;&lt;a href="http://localhost:5000/add_articles"&gt;http://localhost:5000/add_articles&lt;/a&gt;&lt;/strong&gt;”&lt;/p&gt;

&lt;p&gt;Next step is to add definition that will define how our add article will work. We will define each our our variables like &lt;strong&gt;request.json[‘title’],&lt;/strong&gt; what this means? whatever we’ll be sending in title will be a json value. We’ll do same for our rest of the values that we want to insert.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def_ add_articles():
    article = mongo.db.articles
    title = request.json[‘title’]
    description = request.json[‘description’]
    tags = request.json[‘tags’]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now next step is to insert the values into database. Alright! let’s do it.&lt;/p&gt;

&lt;p&gt;So for this we will be using article.insert ( as it will be one single article at a time). The article_id variable is very important keep an eye on it !!&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;article_id = article.insert(
{‘title’: title, ‘description’: description, ‘tags’: tags})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;So what we did here is inserting key:value pair while inserting them.&lt;/p&gt;

&lt;p&gt;One more thing is that we’ve have to set a new_article variable and new_article = article.find_one({‘_id’: article_id}) will set the same along with article_id as _id. So every new article that we post, will have a new unique ID thanks to the new_article we’ve set here.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new_article = article.find_one({‘_id’: article_id})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Okay now we will set an output variable which will output our new post values. and we’ve set a result key which will return json for us with the ID 😁&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;output = {‘title’: new_article[‘title’],
‘description’: new_article[‘description’], ‘tags’: new_article[‘tags’]}
return jsonify({‘result’: output})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  Using our letterbox aka POSTMAN
&lt;/h3&gt;

&lt;p&gt;Okay, you must be saying… dude how on earth are we going to test this 😆&lt;/p&gt;

&lt;p&gt;Let’s post it using letterbox.. aka Postman :)&lt;/p&gt;

&lt;p&gt;Okay first thing first what is postman?? As per &lt;a href="https://www.getpostman.com/"&gt;&lt;strong&gt;Postman official website&lt;/strong&gt;&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Postman is a collaboration platform for API development. Postman’s features simplify each step of building an API and streamline collaboration so you can create better APIs — faster.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, you need download and install the postman at your end and open the postman app. You will see a window like this&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--87lYL_NJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AAE7RUnwflRhckHbrhxZb4A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--87lYL_NJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AAE7RUnwflRhckHbrhxZb4A.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On this window, we will put our URL in request tab, put “localhost:5000/add_articles” and choose POST from drop down. Than click on “Body” option below and than what you need to do is , select raw option under Body and paste your json like this:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   {  
     “title”: “Hi this is the zero post”,  
     “description”: “This is the zero description”,  
     “tags”: “hi, testing, zero post”  
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gBGOZFqc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2Axxidno1R1GZO4s0_lROrvQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gBGOZFqc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2Axxidno1R1GZO4s0_lROrvQ.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you have everything set like that, hit send. You shall see a response below something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ME-WFT7F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AFb4O0Di5JyCWWBQBu3291A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ME-WFT7F--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AFb4O0Di5JyCWWBQBu3291A.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wooohooo!!! we have made the post call tooo 😎&lt;/p&gt;

&lt;p&gt;That’s all folks!! If you have any questions let me know!!&lt;/p&gt;

</description>
      <category>python</category>
      <category>react</category>
      <category>webdev</category>
      <category>mongodb</category>
    </item>
    <item>
      <title>My 100daysOfCode Journal — Day 01</title>
      <dc:creator>Himanshu👓💻</dc:creator>
      <pubDate>Thu, 31 Oct 2019 18:18:43 +0000</pubDate>
      <link>https://dev.to/ihackthings/my-100daysofcode-journal-day-01-36o8</link>
      <guid>https://dev.to/ihackthings/my-100daysofcode-journal-day-01-36o8</guid>
      <description>&lt;p&gt;Hey folks!&lt;/p&gt;

&lt;p&gt;So it’s day 01 of my 100daysofcode journal. Today, we’ll do setup and first GET call for flask api.&lt;/p&gt;

&lt;p&gt;Here is a list of what we’ll be covering today:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Environment Setup&lt;/li&gt;
&lt;li&gt; Project Setup&lt;/li&gt;
&lt;li&gt; Making first API call 🤩&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Environment Setup&lt;/strong&gt;:
&lt;/h3&gt;

&lt;p&gt;So I am using a Mac machine, so for my environment setup I have to install following software:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Python3&lt;/li&gt;
&lt;li&gt; MongoDB&lt;/li&gt;
&lt;li&gt; Pipenv&lt;/li&gt;
&lt;li&gt; Flask&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;let’s go one by one over the dependencies and software&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Python&lt;/strong&gt; 3:
&lt;/h3&gt;

&lt;p&gt;In order to install python3 on a Mac you need to install &lt;strong&gt;Homebrew&lt;/strong&gt; first. You can go to following &lt;a href="https://brew.sh/"&gt;&lt;strong&gt;link&lt;/strong&gt;&lt;/a&gt; to install homebrew and simply follow the instructions.&lt;/p&gt;

&lt;p&gt;Once you have hombrew install simply run following command&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;brew install python3&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If everything goes well, you shall be able to run following command on Iterm or Terminal and get output in return as shown below, run&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;python – –version&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pPYIazQi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AZkV9haVJQ_Juk53-_6vP5Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pPYIazQi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AZkV9haVJQ_Juk53-_6vP5Q.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Python Version&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;MongoDB&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now that we have Python3 installed on machine, we need to install MongoDB on mac machine. We will be using brew for this purpose also. So open the terminal again and run following set of commands.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;brew tap mongodb/brew&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will add mongodb formula. Done? let’s install the MongoDB community edition. To do so, we will run next command&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;brew install &lt;a href="mailto:mongodb-community@4.2"&gt;mongodb-community@4.2&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This shall install mongo on your system. To double check run&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;mongod --version&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You will get following output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;pyguy@Himanshus-MacBook-Pro ~ % mongod — version&lt;br&gt;&lt;br&gt;
db version v4.2.1&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, we need to make sure that mongodb is running as a service in the background. so we will execute&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;brew services start &lt;a href="mailto:mongodb-community@4.2"&gt;mongodb-community@4.2&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So we’re all set with MongoDB , it’s running in the backend, silently 🤫.&lt;/p&gt;

&lt;p&gt;We’ll move come back to mongoDB later at some point. Let’s move on to next step.&lt;/p&gt;

&lt;h3&gt;
  
  
  Project Setup
&lt;/h3&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Pipenv, Flask &amp;amp; flask_pymong&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now, In order to install pipenv &amp;amp; flask, we have to first create a code directory, so create one with any name using UI or command line. I mostly prefer command line so yeah…&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;mkdir pyguy&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once that’s created cd into the directory and let’s install pipenv using pip3 which is already installed when we install python3 using brew. Ok, so now run&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;pip3 install pipenv&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Okay now that pipenv environment is setup in the code directory a Pipfile will be created.&lt;/p&gt;

&lt;p&gt;Let’s activate this 😁. you need to run&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;pipenv shell&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You will see something like this once it’s activated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--n66RnU6x--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AAYUrSy-pKyeQxR416HPgrw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--n66RnU6x--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2AAYUrSy-pKyeQxR416HPgrw.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Pipenv is activated&lt;/p&gt;

&lt;p&gt;See that (pyguy), in front of our terminal window? That means environment is ACTIVE!!&lt;/p&gt;

&lt;p&gt;All good, now we will install our dependencies. Now that our pipenv is active, we will install flask and pymongo. To do so we will run&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;pip3 install flask_pymongo flask&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Alright, we have our dependencies installed so all we need to do right now is do directory setup.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Directory Setup&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;We will segregate our backend and frontend for our project. As we will be having a separate front end that will be &lt;strong&gt;React.&lt;/strong&gt; So this is how our directory structure will be like.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bBNLm3Gs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A6FmU7DDLVnTre8DrqEQc9Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bBNLm3Gs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/800/1%2A6FmU7DDLVnTre8DrqEQc9Q.png" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Directory structure&lt;/p&gt;

&lt;p&gt;You can ignore the Pipfile.lock , PyGuy.code-workspace files. Pipfile.lock will auto-generate and the other one is generated by my vscode, because I have saved it as workspace.&lt;/p&gt;

&lt;h3&gt;
  
  
  Making first API call 🤩
&lt;/h3&gt;

&lt;p&gt;Now that we’ve everything setup, let’s buckle up and make our API call.&lt;/p&gt;

&lt;p&gt;Go into backend directory and then create app.py file. The app.py file will be our very base file. Open the file in your favourite editor and paste following code. I will explain the code one by one.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'''Flask App For PyGuy WebSite'''  

from flask import Flask, jsonify  
from flask_pymongo import PyMongo  

#App Definitions &amp;amp; Configs  
app = Flask(__name__)  
app.config["MONGO_DBNAME"] = 'pysite'  
app.config["MONGO_URI"] = "mongodb://localhost:27017/pysite"  
mongo = PyMongo(app)  

#This will be the index route ....  


"""  
Defining all API routes.   
"""  


@app.route("/", methods=['GET'])  
def index():  
    return "&amp;lt;h1&amp;gt; Hi I am Himanshu :)&amp;lt;/h1&amp;gt;"  



    @app.route('/posts', methods=['GET'])  
    def articles():  
        articles = mongo.db.articles  

        output = []  

        for q in articles.find():  
            output.append(  
                {'title': q['title'], 'description': q['description'], 'tags': q['tag']})  
        return jsonify({'result': output})  


    if __name__ == "__main__":  
        app.run(debug=True)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Let’s go through the code….&lt;/p&gt;

&lt;p&gt;'''Flask App For PyGuy WebSite'''&lt;/p&gt;

&lt;p&gt;This is our app definition.&lt;/p&gt;

&lt;p&gt;Than let’s import flask and jsonify to convert things to json. Also, import PyMongo in order to connect to our MongoDB.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, jsonify  
from flask_pymongo import PyMongo
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Next, we are defining App definitions &amp;amp; configs. The very first line is where we set our current class. Here, we’ve set Flask as our name.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app = Flask(__name__)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now, we’ll set our app configs to set, dbname, mongo db uri and then define the MongoDb connected using PyMongo passing app as parameter.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.config["MONGO_DBNAME"] = 'pysite'  
app.config["MONGO_URI"] = "mongodb://localhost:27017/pysite"  
mongo = PyMongo(app)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Okay, next we will make our index call. Here is how we define index route with GET method and returning a H1 text when you browse to index of api.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route("/", methods=['GET'])  
def index():  
    return "&amp;lt;h1&amp;gt; Hi I am Himanshu :)&amp;lt;/h1&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Okay, so in order to list our posts, we will create our routes as follows. First, we define the url we will be using to go to particular api route. In our case its &lt;strong&gt;/posts.&lt;/strong&gt; Next, we will write definition which will tell us what to do. We want to list all the posts so in that case we will query through our collection. By setting article variable with mongo.db.articles value. Here, mongo is coming from our definition above, we use .db.articles to access the articles collection that’s in our mongoDB.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/posts', methods=['GET'])  
def articles():  
    articles = mongo.db.articles
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In the code below, we have initialized a blank array, output. Once we’ve collection accessed, we will do a for loop to query through the &lt;strong&gt;articles&lt;/strong&gt; defined above. We will append each q key value in our output and will return jsonified output in result key.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;output = []  

    for q in articles.find():  
        output.append(  
            {'title': q['title'], 'description': q['description'], 'tags': q['tag']})  
    return jsonify({'result': output})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This very last line will run the named program which is &lt;strong&gt;app&lt;/strong&gt; as our main application. app.run statement with debug=True will run our application in debug mode.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == "__main__":  
    app.run(debug=True)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now to run our flask application open terminal(activate pipenv if not already) and navigate to our “backend” folder and issue &lt;strong&gt;flask run&lt;/strong&gt; command. This will give a similar output in terminal like below.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(pyguy) pyguy@Himanshus-MacBook-Pro backend % flask run  
Environment: production  
WARNING: This is a development server. Do not use it in a production deployment.  
Use a production WSGI server instead.  
Debug mode: off  
Running on [http://127.0.0.1:5000/](http://127.0.0.1:5000/) (Press CTRL+C to quit)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If you want to see if your api calls are working, go to &lt;a href="http://localhost:5000/,"&gt;http://localhost:5000/,&lt;/a&gt; you shall see something like this on index page&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Hi I am Himanshu :)&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This tutorial doesn’t covers creating collections on MongoDB, which I will cover in 2nd part of same. That’s all for today, if you have comments, feel free to comment.&lt;/p&gt;

</description>
      <category>react</category>
      <category>python</category>
      <category>mongodb</category>
    </item>
    <item>
      <title>My 100daysOfCode Journal - Introduction….</title>
      <dc:creator>Himanshu👓💻</dc:creator>
      <pubDate>Thu, 31 Oct 2019 09:40:22 +0000</pubDate>
      <link>https://dev.to/ihackthings/my-100daysofcode-journal-introduction-3goh</link>
      <guid>https://dev.to/ihackthings/my-100daysofcode-journal-introduction-3goh</guid>
      <description>&lt;p&gt;Before I start my 100DaysOfCode Journal, it's time for a little bit of introduction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;About me…&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;I am &lt;strong&gt;Himanshu Patel&lt;/strong&gt;, I am self taught developer from India. To add.. I have a degree in Bachelor Of Commerce, but my love for computers motivated me to try learning web development and sorts. In my earlier years of college, I didn't had internet at home. So I preferred learning from books.. since than these books became my best friends. &lt;/p&gt;

&lt;p&gt;First language or shall i say thing that i learned was C &amp;amp; C++, to my taste it was booooooring(I was not finding it interesting, duh)and not my cup of tea. So I started learning some PHP, my first project was total s**t, but that gave me an idea. So i starting making some mooore PHP projects. While I was learning PHP, I came to know about Python and well.. dropped PHP as i came to know how awesome Python is. In early days of python I was learning how to make programs work. Well my first program was simple application that I used to read PDF and text file. That got me more interested in Python. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;My First Job.. I mean an internship and so on....&lt;/strong&gt;&lt;br&gt;
My very first job was that of an intern, I was asked to work on PHP. I wanted to get into the tech so I accepted it. Learned a few things here and there while learning more and more python. I was in it for almost an year while trying to finish my college. I took RHCE certification at around same time of my last year in college (2019) and made it to top 5 of my class. &lt;/p&gt;

&lt;p&gt;In Year 2009, I passed out from my college and looked for my a job in IT. It was difficult for me to get something, but got one as a systems administrator. I learned so much about networking, systems, technology and what not. It was a good exposure for me.&lt;br&gt;
Eventually, after working my butt off for almost 4 years, I left that job too. I got my very first job as a developer at CodeKrieg. It was a Ruby on Rails developer job. That was the point when i was actually happy and was enjoying the work I am doing. I built so many robust systems and applications that helped our clients. Down the line, I climbed up to position as a Lead Developer at the same company. My work was appreciated by people I was working with. &lt;/p&gt;

&lt;p&gt;Over the course of time, the company did grew. But due to some financial crunches, everything went down and they ran out of business in 2015. It was a sad day for me, but hey! that's not the end of it. While i was not having a job, I started working as freelancer and got some gigs, that got the ball rolling. &lt;br&gt;
In August of 2016 I landed another job as a Associate Infrastructure Analyst, where I was suppose to work with servers, and help developers with different issue they might face on infrastructure side. This was a good job but short lived. Well, again… i left that too. &lt;/p&gt;

&lt;p&gt;For an year, I was doing more than 2 jobs as a freelancer and learning and coding using python. Finally, i landed the job as Technical Team Lead and working on Python now. I have developed a number of products in 1 year span and successfully delivered them too. &lt;/p&gt;

&lt;p&gt;I love the idea of continuity of learning in Tech, this keeps me running. In the past years, I have worked on number of languages. I worked with C C++, Python, Laravel, Haskell Language. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why 100daysofcode…..???&lt;/strong&gt;&lt;br&gt;
Because, I love challenges!!. Well that and the fact that I have a few projects that I wanted to finish, but was not able to as I was too lazy to take time for my own learning. For past year, I was trying to finish my website/portfolio/blog you can call it anything but due to my engagements at work, I was not able to do that at all. I was more or less feeling awkward about not getting started and finishing them off… 100DaysOfCode was one of the best reason for me to challenge my self up(or end up in putting myself to shame over the internet for not finishing it lol :D)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What I will be covering in 100DaysOfCode&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Flask&lt;/li&gt;
&lt;li&gt; React &lt;/li&gt;
&lt;li&gt;Mongo &lt;/li&gt;
&lt;li&gt;Self Driven cars&lt;/li&gt;
&lt;li&gt; A.I&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I will try to record all my 100daysofcode each day here. &lt;br&gt;
If you would like to know more about me you can connect me over &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://twitter.com/Ihackthings"&gt;Twitter&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>mongodb</category>
      <category>python</category>
      <category>flask</category>
    </item>
  </channel>
</rss>
