REST API Query Parameter GET Request using Python Flask and PostgreSQL Database

Subscribe: https://www.youtube.com/c/Cairocoders/featured

Source Code

app.py


#app.py
from flask import Flask, jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash
 
import psycopg2 #pip install psycopg2 
import psycopg2.extras
 
app = Flask(__name__)
 
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
     
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)  
 
@app.route('/')
def home():
    passhash = generate_password_hash('cairocoders')
    print(passhash)
    return passhash
 
@app.route('/user') 
def get_user():
    try:
        id = request.args.get('id')
        if id:
            cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
            cursor.execute("SELECT * FROM useraccount WHERE id=%s", id)
            row = cursor.fetchone()
            resp = jsonify(row)
            resp.status_code = 200
            return resp
        else:
            resp = jsonify('User "id" not found in query string')
            resp.status_code = 500
            return resp
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()
 
if __name__ == "__main__":
    app.run()

#python #flask #postgresql

REST API Query Parameter GET Request using Python Flask and PostgreSQL Database
2.55 GEEK