Search code examples
pythonpython-3.xflutterflaskflask-restful

How to use a Flask Api with Flutter?


I am trying to make a simple app with flutter and using data from a python script as flask restful-api. I made my script and I can get the results with this way: http://127.0.0.1:5000/query?username=username1 as json formatted. The thing I am trying to do exactly is that; when my app started to work a pop-up window will ask username, after username is entered it will go to the main widget of the app and that widget will take data from json in my api page. So for doing this should I use an online api or web server if there is one for python? I looked up the google app engine, but I couldn't even upload my script there. So what's the simpliest way to link my restful-api to my flutter app(and finally apk file) as able to work on any phone? My script code is below, flutter side is still in progress till I figured out how can I work with an api by python in flutter..

from flask import Flask, request, jsonify
import random
import imdb
from trakt.users import User

app = Flask(__name__)

@app.route('/query', methods=['GET', 'POST'])
def query():
    username = request.args['username']
    moviesDB = imdb.IMDb()
    my = User(str(username))
    myline = str(random.choice(my.watchlist_movies))[9:1000]
    print(myline)
    movies = moviesDB.search_movie(str(myline))
    id = movies[0].getID()
    movie = moviesDB.get_movie(id)
    title = movie['title']
    year = str(movie["year"])
    rating = str(movie["rating"])
    runtime = ' '.join(map(str, movie["runtimes"]))
    directStr = ' '.join(map(str, movie["directors"]))
    writerStr = ', '.join(map(str, movie["writers"]))
    actors = ', '.join(map(str, movie["cast"]))
    summary = movie["plot outline"]
    genre = ', '.join(map(str, movie["genres"]))
    posterurl = movie["full-size cover url"]

    return jsonify(movietitle=title,
                   movieyear=year, movierating=rating, moviegenres=genre, movieruntime=runtime,
                   moviedirectors=directStr,
                   moviewriters=writerStr,
                   moviecast=actors,
                   movieplotline=summary,
                   movieposterurl=posterurl)

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

Solution

  • So, the question is really where should you host your python api? If that is the case then the answer is wherever you decide heh. If you are looking for free solutions you can take a look at these two: pythonanywhere and Heroku. Both are free but for Heroku a valid credit card must be provided to get full up-time. That being said if your app is going to generate a decent amount of traffic then I strongly suggest you either rent a VPS or a Dedicated server running Linux (many... many hosting providers out there).