Hosting flask API

Question:

Please forgive me if some of my terminology is off here, I’m new to all of this.

I have built a python-flask API that GETs data from my PostgreSQL database. I have tried to get my API hosted on Heroku but I think it is unsuccessful because my API is using my postgres username and password to connect to localhost. Will I need to get my database hosted first before I can host my API on Heroku.

Thanks

app.py

import pandas as pd
import psycopg2
import sqlalchemy
from sqlalchemy import create_engine
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
from fuzzywuzzy import fuzz

# Postgres username, password, and database name
username = 'postgres'
password = 'XXXXXXXXXX' # postgres password
host = 'localhost'
port = '5432'
database = 'test'

# string that contains necessary postgres login info
postgres_str = ('postgresql://{username}:{password}@{ipaddress}:{port}/{database}'
                .format(username=username,
                        password=password,
                        ipaddress=host,
                        port=port,
                        database=database
                        ))
               
# create the connection
conn = create_engine(postgres_str)

app = Flask(__name__)
CORS(app=app)

@app.route('/bamboo/<product>', methods=['GET'])
def getProducts(product):

    # GET request
    if request.method == 'GET':
        
        query = """select a.*, b.logo
                   from products a
                   left join companies b on a.company_name = b.company_name
                   where CAST(product_price as int) != 0
                   """
        
        df = pd.read_sql_query(query, conn)

        final_results = df.to_json(orient='records')

        return final_results  # serialize and use JSON headers


if __name__ == '__main__':
    # run!
    app.run()
Asked By: Richard Palmer

||

Answers:

Yes. You need to host the database first. You can use Heroku CLI for that.

So first go into your terminal and login into your Heroku account using the following command and press Enter, and you will see a successful logged in message with your account name.

$ heroku login

Now create a Database for your app using the following command,

$ heroku addons:create heroku-postgresql:hobby-dev --app app_name

Now after your Database has been created, get the URL of your Database using the following command,

$ heroku config --app app_name

Please refer this and this for more info.

Answered By: Nishan