HomeBack-End & DatabaseIntegrating Rest API

Integrating Rest API

In this blog, we try something interesting. We can do one thing suppose we have a full working website, and we want to use website login API in our API. So for this, we use python library requests, and we will see how this works. So Let’s start.

Problem: So the problem is at this stage we don’t know where we will get API URL, we don’t know which URL will work for login.

Solution: We follow some steps for this first we need to get the login API URL.

Step1: Go to the website login page.
Step2: Use the inspect element for getting the login API URL (press F12).
Step3: Then fire the login API.

After following the first and second steps, this will look like an image below.

Then we click on sign in and go to network option in the inspect window. After that, we click on the first API, which is showing in the inspect window and click on the header, then we get this.

Problem: At this stage, we may have to face some problems like we don’t know which API we use for login users. We are confused about whether we are on the right API or not or any error in our code.

Solution: To solve this problem, we can do one thing we try API request URL fire in postman first with payload data. If we get a login successfully or get token, then we are on the right API.


So we get the right login API, and we got token. Now we can try this with the payload.

Problem: Now, the problem is where we get payloads. So to find the payload, let’s follow this solution.

Solution: In an inspect elements window, we can see we got General, Response Headers, Request Headers, and Requests payload. So here we find Request URL in General and payload actions in Requests payload. We copy these two things from the header.


Request URL:
https://hr.excellencetechnologies.in/attendance/API_HR/api.php

Payload :
{action: "login", username: "aayush_saini", password: "****", token: null}

Now we try to get login token by this URL and payload for this purpose we use requests library, which we have already discussed in the previous blog. So we write a simple code for this.

 
import requests

URL = 'https://hr.excellencetechnologies.in/attendance/API_HR/api.php'
payload = {'username': 'aayush_saini', "password": '****', "action": "login", "token": None} #change the username and password
r = requests.post(url=URL, json=payload)
print(r.status_code)
print(r.json())

So in this code, we try to login by our website username and password using requests and print status code and JSON data, which we got after running this code. Let see the output in the terminal.

Problem: So that’s fine. However, there are some issues like we don’t have any route to test this in postman. Second is we get complex data not only token, and we need to change username or password every time in our code. So first, we fix these issues and modify our code to solve these issues.

Solution: For the solution of this problem, we fetch only token from all JSON data by using simple code. Use this to find the only token from dictionary data.

 
token['data']['token']
 
import requests
from flask import (Flask, request, abort, jsonify)


app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
if not request.json:
abort(500)
URL_login = 'https://hr.excellencetechnologies.in/attendance/API_HR/api.php'
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username:
return jsonify(msg="Missing username parameter"), 400
if not password:
return jsonify(msg="Missing password parameter"), 400

payload_user_login = {'username': username, "password": password, "action": "login", "token": None}
response_user_token = requests.post(url=URL_login, json=payload_user_login)
token = response_user_token.json()
user_token = token['data']['token']
return jsonify({"Token":user_token})


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

Now check our code in postman give the username and password in post request and see what happens.

Now it is looking good, and also we got a login user token.

Now we try something else with this. We can do one thing we try to store user profile data into the database at the time of login. For this first, we need a user profile API URL link from the website. So move back to the website inspect window and try to find an API link.

Now we follow some steps to get the second API link.

Step1: Click on the profile on the website menu.
Step2: Click on the first API in Headers.

Copy Request URL and action from Requests payload.

https://hr.excellencetechnologies.in/attendance/sal_info/api.php
action: "get_user_profile_detail",

Now we write a simple code for store user info in the database and create an access token.

 
import requests
from flask import (Flask, request, abort, jsonify)
from flask_cors import CORS
from flask_restful import Resource,Api
from flask_pymongo import PyMongo
import datetime
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity, get_current_user, jwt_refresh_token_required,
verify_jwt_in_request
)


app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/test_db_manish"
mongo = PyMongo(app)
api = Api(app)
CORS(app)

app.config['JWT_SECRET_KEY'] = 'xxxx' # Change this!
jwt = JWTManager(app)


@app.route('/login', methods=['POST'])
def login():
if not request.json:
abort(500)
URL_login = 'https://hr.excellencetechnologies.in/attendance/API_HR/api.php'
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username:
return jsonify(msg="Missing username parameter"), 400
if not password:
return jsonify(msg="Missing password parameter"), 400

payload_user_login = {'username': username, "password": password, "action": "login", "token": None}
response_user_token = requests.post(url=URL_login, json=payload_user_login)
token = response_user_token.json()

if token['data'] == {'message': 'Invalid Login'}:
return jsonify(msg='invalid login')
else:
URL_details = 'https://hr.excellencetechnologies.in/attendance/sal_info/api.php'
payload_user_details = {"action": "get_user_profile_detail", "token": token['data']['token']}
response_user_details = requests.post(url=URL_details, json=payload_user_details)
username = request.json.get("username", None)
result = response_user_details.json()

user = mongo.db.users.count({
"username": username})
if user > 0:
user = mongo.db.users.update({
"username": username
}, {
"$set": {
"profile": result
}
})
else:
user = mongo.db.users.insert_one({
"profile": result,
"username": username
}).inserted_id
expires = datetime.timedelta(days=1)
access_token = create_access_token(identity=username, expires_delta=expires)
return jsonify(access_token=access_token), 200

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

Explanation – In this code, we get the token from login API, and after that, we put a token into the second API payload to find the user data. After that, we get user profile data from the second API response, and we store user data into the database if a user does not exist else we update the database with updated information. In the end, we create an access token by username, which will use to access other routes.

Let’s check the code in POSTMAN.

Problem: See, we got access_token. However, at this state, access_token will not work because we don’t have any route for testing this token.

Solution: We make a new profile route that returns our current login username and user data stored in the database.


 
@app.route('/profile', methods=['GET'])
@jwt_required
def protected():
current_user = get_current_user()
return jsonify(logged_in_as=current_user["username"]), 200

Now test the profile route in postman.

Problem: We got an error because this code does not have proper requirements to get current user identity as we did not use jwt identity_loader and jwt loader_callback_loader in our code.

Solution: So we will use user_identity_loader and user_loader _callback _loader.

 

@jwt.user_identity_loader
def user_identity_lookup(user):
print("user_identity_lookup")
return str(user)


@jwt.user_loader_callback_loader
def user_loader_callback(identity):
print("user_loader_callback")
user = mongo.db.users.find_one({
"username": identity
})
if user is None or "username" not in user:
return None
return(user)

Now, after adding loaders, we run our code and see the response.

See, we got the current user name now.

Here is the entire final code for reference.

 
import requests
from flask import (Flask, request, abort, jsonify)
from flask_cors import CORS
from flask_restful import Resource,Api
from flask_pymongo import PyMongo
import datetime
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity, get_current_user, jwt_refresh_token_required,
verify_jwt_in_request
)


app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/test_db_manish"
mongo = PyMongo(app)
api = Api(app)
CORS(app)

app.config['JWT_SECRET_KEY'] = 'xxxx' # Change this!
jwt = JWTManager(app)


@app.route('/login', methods=['POST'])
def login():
if not request.json:
abort(500)
URL_login = 'https://hr.excellencetechnologies.in/attendance/API_HR/api.php'
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username:
return jsonify(msg="Missing username parameter"), 400
if not password:
return jsonify(msg="Missing password parameter"), 400

payload_user_login = {'username': username, "password": password, "action": "login", "token": None}
response_user_token = requests.post(url=URL_login, json=payload_user_login)
token = response_user_token.json()

if token['data'] == {'message': 'Invalid Login'}:
return jsonify(msg='invalid login')
else:
URL_details = 'https://hr.excellencetechnologies.in/attendance/sal_info/api.php'
payload_user_details = {"action": "get_user_profile_detail", "token": token['data']['token']}
response_user_details = requests.post(url=URL_details, json=payload_user_details)
username = request.json.get("username", None)
result = response_user_details.json()

user = mongo.db.users.count({
"username": username})
if user > 0:
user = mongo.db.users.update({
"username": username
}, {
"$set": {
"profile": result
}
})
else:
user = mongo.db.users.insert_one({
"profile": result,
"username": username
}).inserted_id
expires = datetime.timedelta(days=1)
access_token = create_access_token(identity=username, expires_delta=expires)
return jsonify(access_token=access_token), 200



@app.route('/profile', methods=['GET'])
@jwt_required
def protected():
current_user = get_current_user()
return jsonify(logged_in_as=current_user["username"]), 200


@jwt.user_identity_loader
def user_identity_lookup(user):
print("user_identity_lookup")
return str(user)


@jwt.user_loader_callback_loader
def user_loader_callback(identity):
print("user_loader_callback")
user = mongo.db.users.find_one({
"username": identity
})
if user is None or "username" not in user:
return None
return(user)


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

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: