top of page

Creating API Using Python Flask And MongoDB Client

realcode4you

First Import All Related Libraries

#Import Libraries
from flask import Flask
from pymongo import MongoClient
from flask import request
import json
from bson.json_util import dumps

Creating Connection With MongoDB Client

client = MongoClient('localhost:27017')
db = client.market

Implementation

@app.route("/")
def hello():
    return "Ok it works"

@app.route('/stock', methods=['GET', 'POST', 'PUT', 'DELETE'])
def stock():
    if request.method=='GET':
        try:
            result = db.stocks.find()
            return dumps(result)
        except Exception:
            return dumps({'error' : str("error")})
        

    elif request.method=='POST':
        try:
            result = db.stocks.insert({"Ticker":"XYZ"})
            return dumps(result)
        except Exception:
            return dumps({'error' : str("error")})
        
    elif request.method=='PUT':
        try:
            result = db.stocks.updateMany({"Ticker":"AAMC"},{'$set':{"Ticker":"ABC"}})
            return dumps(result)
        except Exception:
            return dumps({'error' : str("error")})
    
    
    elif request.method=='DELETE':
        try:
            delete_user = db.stocks.delete_one({"Ticker":"ABC"})
            if delete_user.deleted_count > 0 :
                return "", 204
            else:
                return "", 404
        except:
            return "", 500
    else:
        return("ok")

if __name__ == "__main__":
    app.run()


Follow Below Steps Before Run Above Code


step first:

open cmd prompt


step second:

----------------------------


>mkdir rest
>cd rest

----------------------------


step third

----------------------------------


check rest folder created copy path and run command as per screenshot 3


step fourth

----------------------------------------


C:\Users\naveen kumar\rest>virtualenv flask
installation start
script and other folder are created


step fifth

----------------------------------------


again go to the rest folder and copy path where script folder exist
then activate virtual environment by activate command

C:\Users\naveen kumar\rest\flask\Scripts>activate


step six

------------------------------------------


Create python file using any editor but save it into the scipt folder

-------------------------------------------------------


step seven


Now install flask by using given command and see in screeshot

(flask) C:\Users\naveen kumar\rest\flask\Scripts>pip install flask

-------------------------------------------

step eight


Now intall pymongo by using command

(flask) C:\Users\naveen kumar\rest\flask\Scripts>pip install pymongo


step ninth


run python file using command line(sure python file is open in editor)

(flask) C:\Users\naveen kumar\rest\flask\Scripts>python restfullapiflask.py

url is generated on command line

-------------------------------------------


step ten


copy url and paste it into webbrowser like chrome and run 

as per screenshot 8

and you see the output -----Ok it works

-------------------------------------------



now start mongod and mongo
and import json file which you already complete this


-----------------------------------------



install postman and run url http://127.0.0.1:5000/stoks

as per get, put and delete

find output result


thanks



---------------------------------------------------



Get


Post


Delete




If you need Other Help Related to Python then contact us or send your project requirement details at realcode4you@gmail.com and get instant help with an affordable price.

Comments


REALCODE4YOU

Realcode4you is the one of the best website where you can get all computer science and mathematics related help, we are offering python project help, java project help, Machine learning project help, and other programming language help i.e., C, C++, Data Structure, PHP, ReactJs, NodeJs, React Native and also providing all databases related help.

​

Hire Us to get Instant help from realcode4you expert with an affordable price.

USEFUL LINKS

Discount

ADDRESS

Noida, Sector 63, India 201301

Follows Us!

  • Facebook
  • Twitter
  • Instagram
  • LinkedIn

OUR CLIENTS BELONGS TO

  • india
  • australia
  • canada
  • hong-kong
  • ireland
  • jordan
  • malaysia
  • new-zealand
  • oman
  • qatar
  • saudi-arabia
  • singapore
  • south-africa
  • uae
  • uk
  • usa

© 2023 IT Services provided by Realcode4you.com

bottom of page