Flask Routes
@app.route extensibility
Basic:
Just includes path
@app.route("/hello")
def get_greeting():
return jsonify({'message':'Hello World!'})
Extended:
- Variable Rules in the path
Example endpoint: http://www.example.com/entrees/1
<variable_name> within the path
@app.route('/entrees/<int:entree_id>')
Specify the type of the variable using the converter syntax
<converter:variable_name>
Passed as parameter to function as keyword argument variable_name
@app.route('/entrees/<int:entree_id>')
def retrieve_entree(entree_id):
return 'Entree %d' % entree_id
- HTTP Methods
- @app.route by default only responds to GET methods
- Method parameter to pass a list of HTTP method strings
@app.route('/hello', methods=['GET','POST'])
def greeting():
if request.method == 'POST':
return create_greeting()
else:
return send_greeting()
The GET request can be handling huge sets of data all at once.
- Sending huge sets of data all at once is bad for speed
- Instead, paginate your data using query parameters and request arguments.
@app.route
decorator can handle Variable Rules and multiple HTTP methods
- Variable Rules
Followcollection/item/collection
. In order to handle that variable item. In order to handle that variability in Flask, you add a<variable_name>
within the path argument of the@app.route
decorator, which is then passed to the function as a keyword argument variable_name.
You can also specify the type of argument by using <converter:variable_name>
syntax.
@app.route('/entrees/<int:entree_id>')
def retrieve_entree(entree_id):
return 'Entree %d' % entree_id
- HTTP Methods
By default, the@app.route
decorator answers only get requests. In order to enable more request types, pass the method parameter to the decorate including a list of string methods.
@app.route('/hello', methods=['GET', 'POST'])
def greeting():
if request.method == 'POST':
return create_greeting()
else:
return send_greeting()
OPTIONS requests are automatically implemented and HEAD is also automatically implemented if GET is present.
Pagination in Flask
Handling large sets of data
Query Parameter Conventions
- A question mark precedes the query parameters
www.example.com/entrees?page=1
- Parameters are in key-value pairs with an equal sign in between the key and value
www.example.com/entrees?page=1
- Sets of parameters are separated by an ampersand
www.example.com/entrees?page=1&allergens=peanut
Request Argument Example
- Access the request object argument dictionary
- Get the value for the expected parameter key or default value
@app.route('/entrees', methods=['GET'])
def get_entrees():
page = request.args.get('page', 1, type=int)