Due to immense noob'ity regarding Python in general and Flask in particular, I'm fundamentally confused regarding the conventions, best practices and common know-how. I try to follow the examples provided by Microsoft (as we're working with Azure) and I start to suspect they might be... Microsoft'ish (i.e. "it works but...").
Based on various examples, I've created two endpoints, carrying the same computation, resulting in equivalent payloads (not the same structure, though!) and I can't figure out which is the recommended approach. One is using resourcing (coupled with a route), while the other is explicitly routing.
from flask import Flask
from flask_restful import Api, Resource, request
from logic import compute
app = Flask(__name__)
api = Api(app)
class computer (Resource):
def get(self):
return compute(request.args.to_dict())
api.add_resource(computer, "/compute-resource")
@app.route("/compute-route", methods=["GET"])
def execute():
return compute(request.args.to_dict())
if __name__ == "__main__":
app.run()
The only (weirdly unexpected) I noticed in the output is that the latter seems to sort the fields of returned JSON alphabetically while the first one doesn't it.
Your question touches on a common dilemma when designing Flask APIs: whether to use Flask-RESTful's Resource
-based approach or Flask's route-based approach. Both are valid and have their place, depending on your use case and preferences.
Flask-RESTful (Resource
):
GET
, POST
, PUT
, DELETE
) using class methods.Example:
class UserResource(Resource):
def get(self):
return {"name": "Alice", "age": 25} # Order preserved.
Route-based approach (@app.route
):
jsonify
function (implicitly used by Flask's @app.route
) sorts keys alphabetically by default when serializing to JSON.Example:
@app.route("/user")
def user():
return {"age": 25, "name": "Alice"} # Alphabetically sorted as {"age": 25, "name": "Alice"}.
When to Use Flask-RESTful:
When to Use Route-based:
Since both methods lead to the same result and the only difference is the field ordering:
The deviation in field ordering is due to:
json
library directly, which preserves insertion order for dictionaries.jsonify
, which applies sort_keys=True
by default when dumping JSON.If you want to control field ordering in the route-based approach, you can disable sorting like this:
from flask import jsonify
@app.route("/compute-route", methods=["GET"])
def execute():
return jsonify(compute(request.args.to_dict())), 200, {"Content-Type": "application/json"}
For maintainability and scalability, especially when working with Azure or similar platforms, adopt Flask-RESTful with Resource
. It aligns with REST API standards and keeps your code organized as the project grows.