Friday, January 13, 2023

Python Flask Rest Api with Mongodb Atlas and consume it with Python Requests

REpresentational State Transfer also known as REST and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. I thought that it is very necessary to post about this topic but in Cybersecurity, this kind of design approach introduces a lot risks but can be mitigated with the help of thorough testing and scanning.

 Today, I have created a very simple demo program written in python flask that that will store the data on a web based mondodb database called atlas and will be consumed by another python program just to test that the rest api is working. Here is the basic python-flask program:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from flask import Flask, jsonify, request
from pymongo import MongoClient
import pprint
import dns.resolver
dns.resolver.default_resolver=dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers=['8.8.8.8']
app = Flask(__name__)

# connect to the MongoDB Atlas database
password = 'ccc'
connection_string = f'mongodb+srv://bbb:{password}@cluster0.fniq5.mongodb.net/?retryWrites=true&w=majority'
client = MongoClient(connection_string, connectTimeoutMS=30000, socketTimeoutMS=None)
db = client.grades

@app.route('/store_grade', methods=['POST'])
def store_grade():
    data = request.get_json()
    student_id = data['student_id']
    subject = data['subject']
    grade = data['grade']
    # insert the grade data into the 'grades' collection
    db.grades.insert_one({'student_id': student_id, 'subject': subject, 'grade': grade})
    return jsonify(message='Grade stored successfully')

if __name__ == '__main__':
    app.run(debug=True)

This is the python script that will access the rest api. The first program should be running on a localhost before running this second program:


1
2
3
4
5
6
7
8
9
import requests

url = "http://localhost:5000/store_grade"

data = {"student_id": 111, "subject": "algebra", "grade":85}

response = requests.post(url, json=data)

print(response.json())

And to check it the data was posted successfully, just go to your mongodb atlas account and you will see a record like this:


For more detailed explanation on how to insert a record to you cloud based mongdb, you may check out Tim's tutorial on youtube:


The youtube video help a lot with the preparation of this demo program.


No comments:

Post a Comment