By Steven | January 25, 2020
How to build an API using Flask and deploy it to the cloud using Gunicorn
What is HTTP and What Does it Have to do with Flask?
HTTP is the protocol for websites. The internet uses it to interact and communicate with computers and servers. Let me give you an example of how you use it everyday.
When you type the name of a website in the address bar of your browser and you hit enter. What happens is that an HTTP request has been sent to a server.For example, when I go to my address bar and type google.com, then hit enter, an HTTP request is sent to a Google Server. The Google Server receives the request and needs to figure how to interpret that request. The Google Server sends back an HTTP response that contains the information that my web browser receives. Then it displays what you asked for on a page in the browser.
How is Flask involved?
We will write code that will take care of the server side processing. Our code will receive requests. It will figure out what those requests are dealing with and what they are asking. It will also figure out what response to send to the user.
To do all this we will use Flask.
How does a Flask App Work?
I will create a subfolder under apache webserver document root and put codes related to Flask codes under that subfolder:
cd /var/www/html/; mkdir flaskapp
Then create the following Flask test code under flaskapp folder:
# cat flaskapp.py from flask import Flask app=Flask(__name__) @app.route('/hello_word') def hello_world(): return 'Hello World from Flask' if __name__ == '__main__': app.run(host='0.0.0.0', port='8080') # cat flaskapp.wsgi import sys sys.path.insert(0, '/var/www/html/flaskapp') from flaskapp import app as application
Test Flask code in local environment:
Starting the flask app:
# python flaskapp.py * Serving Flask app "flaskapp" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
request API services from local terminal:
#curl localhost:8080/hello_word Hello World from Flask
Now, restart the Apache HTTP Server:
vi /etc/httpd/conf/httpd.conf service httpd restart service httpd status
and test from my local web browser: