Flask
Web-Service
A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.
What's an API?
An API is a set of definitions and protocols for building and integrating application software. It’s sometimes referred to as a contract between an information provider and an information user—establishing the content required from the consumer (the call) and the content required by the producer (the response). For example, the API design for a weather service could specify that the user supplies a zip code and that the producer replies with a 2-part answer, the first being the high temperature, and the second being low.
REST
REST is a set of architectural constraints, not a protocol or a standard. API developers can implement REST in a variety of ways.
When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text. JSON is the most generally popular file format to use because, despite its name, it’s language-agnostic, as well as readable by both humans and machines.
Something else to keep in mind: Headers and parameters are also important in the HTTP methods of a RESTful API HTTP request, as they contain important identifier information as to the request's metadata, authorization, uniform resource identifier (URI), caching, cookies, and more. There are request headers and response headers, each with their own HTTP connection information and status codes.
In order for an API to be considered RESTful, it has to conform to these criteria:
A client-server architecture made up of clients, servers, and resources, with requests managed through HTTP.
Stateless client-server communication, meaning no client information is stored between get requests and each request is separate and unconnected.
Cacheable data that streamlines client-server interactions.
What is Web Framework?
Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc.
What is Flask?
Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.
Prerequisite
Python 2.6 or higher is usually required for the installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7.
Install Flask
pip install Flask
Application
In order to test Flask installation, type the following code in the editor as Hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World’
if __name__ == '__main__':
app.run()pyth
the run() method of Flask class runs the application on the local development server.
app.run(host, port, debug)
All parameters are optional:
host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have the server available externally
port
default 5000
debug
Defaults to false. If set to true, provides a debug information
The above given Python script is executed from Python shell.
Python app.py
A message in Python shell informs you that
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it.
Request in Flask
To gain access to the request object in Flask, you will need to import it from the Flask library:
from flask import request
Import Flask and the request object. And also establish routes for query-example
, form-example
, and json-example
:
# import main Flask class and request object
from flask import Flask, request
# create the Flask app
app = Flask(__name__)
@app.route('/query-example')
def query_example():
return 'Query String Example'
@app.route('/form-example')
def form_example():
return 'Form Data Example'
@app.route('/json-example')
def json_example():
return 'JSON Object Example'
if __name__ == '__main__':
# run app in debug mode on port 5000
app.run(debug=True, port=5000)
Using Query Arguments
Let’s read the language
key and display it as output.
Modify the query-example
route in app.py
with the following code:
@app.route('/query-example')
def query_example():
# if key doesn't exist, returns None
language = request.args.get('language')
return '''<h1>The language value is: {}</h1>'''.format(language)pyth
Then, run the app and navigate to the URL:
http://127.0.0.1:5000/query-example?language=Python
And if you want more, continue adding ampersands and key-value pairs.
@app.route('/query-example')
def query_example():
# if key doesn't exist, returns None
language = request.args.get('language')
# if key doesn't exist, returns a 400, bad request error
framework = request.args['framework']
# if key doesn't exist, returns None
website = request.args.get('website')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>
<h1>The website value is: {}'''.format(language, framework, website)
Then, run the app and navigate to the URL:
http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=DigitalOcean
GET and POST Request
the HTTP protocol is the foundation of data communication on the world wide web. Different methods of data retrieval from specified URLs are defined in this protocol.
The following table summarizes different HTTP methods:
GET
Sends data in unencrypted form to the server. Most common method.
POST
Used to send HTML form data to server. Data received by POST method is not cached by server.
By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator.
Modify the form-example
route in app.py
with the following code:
# allow both GET and POST requests
@app.route('/form-example', methods=['GET', 'POST'])
def form_example():
# handle the POST request
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return 'POST'
# otherwise handle the GET request
return ' GET'
Then, run the app and navigate to the URL:
http://127.0.0.1:5000/form-example
use https://insomnia.rest/ to test your requests fisrt

Using JSON Data
JSON data is normally constructed by a process that calls the route.
An example JSON object looks like this:
{
"language" : "Python",
"framework" : "Flask",
"website" : "Scotch",
"version_info" : {
"python" : "3.9.0",
"flask" : "1.1.2"
},
"examples" : ["query", "form", "json"],
"boolean_test" : true
}
This structure can allow for much more complicated data to be passed as opposed to query strings and form data. In the example, you see nested JSON objects and an array of items. Flask can handle this format of data.
Modify the form-example
route in app.py
to accept POST requests and ignore other requests like GET:
@app.route('/json-example', methods=['POST'])
def json_example():
return 'JSON Object Example'
Now let’s work on the code to read the incoming JSON data.
First, let’s assign everything from the JSON object into a variable using request.get_json()
.
request.get_json()
converts the JSON object into Python data. Let’s assign the incoming request data to variables and return them by making the following changes to the json-example
route:
# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
language = request_data['language']
framework = request_data['framework']
# two keys are needed because of the nested object
python_version = request_data['version_info']['python']
# an index is needed because of the array
example = request_data['examples'][0]
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language, framework,
python_version, example, boolean_test)
Note how you access elements that aren’t at the top level. ['version']['python']
is used because you are entering a nested object. And ['examples'][0]
is used to access the 0th index in the examples array.
If the JSON object sent with the request doesn’t have a key that is accessed in your view function, then the request will fail. If you don’t want it to fail when a key doesn’t exist, you’ll have to check if the key exists before trying to access it.
# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
boolean_test = None
if request_data:
if 'language' in request_data:
language = request_data['language']
if 'framework' in request_data:
framework = request_data['framework']
if 'version_info' in request_data:
if 'python' in request_data['version_info']:
python_version = request_data['version_info']['python']
if 'examples' in request_data:
if (type(request_data['examples']) == list) and (len(request_data['examples']) > 0):
example = request_data['examples'][0]
if 'boolean_test' in request_data:
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language,
framework, python_version, example, boolean_test)
Run the app and submit the example JSON request using Postman. In the response, you will get the following output:
OutputThe language value is: Python
The framework value is: Flask
The Python version is: 3.9
The item at index 0 in the example list is: query
The boolean value is: false
Resources:
Last updated
Was this helpful?