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.
- Which of those two approaches is preferred or are they equivalently appropriate?
- What is the deviation in field ordering suggesting if anything?
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.
Key Differences
-
Flask-RESTful (
Resource
):- Encourages object-oriented programming.
- Suited for RESTful APIs where resources (entities like “users” or “orders”) map to URL endpoints.
- Easily organizes logic for different HTTP methods (
GET
,POST
,PUT
,DELETE
) using class methods. - Field ordering: Flask-RESTful does not sort JSON keys by default, which is why you observe unsorted fields.
Example:
<code>class UserResource(Resource):def get(self):return {"name": "Alice", "age": 25} # Order preserved.</code><code>class UserResource(Resource): def get(self): return {"name": "Alice", "age": 25} # Order preserved. </code>class UserResource(Resource): def get(self): return {"name": "Alice", "age": 25} # Order preserved.
-
Route-based approach (
@app.route
):- Traditional and simpler to understand for Flask beginners.
- Ideal for small applications or non-RESTful APIs where endpoints are procedural or one-off.
- Field ordering: The
jsonify
function (implicitly used by Flask’s@app.route
) sorts keys alphabetically by default when serializing to JSON.
Example:
<code>@app.route("/user")def user():return {"age": 25, "name": "Alice"} # Alphabetically sorted as {"age": 25, "name": "Alice"}.</code><code>@app.route("/user") def user(): return {"age": 25, "name": "Alice"} # Alphabetically sorted as {"age": 25, "name": "Alice"}. </code>@app.route("/user") def user(): return {"age": 25, "name": "Alice"} # Alphabetically sorted as {"age": 25, "name": "Alice"}.
Best Practices
-
When to Use Flask-RESTful:
- Your application requires RESTful design principles.
- You have multiple resources and endpoints that need organization.
- You plan to expand the API or work in a team, and a class-based approach aids readability and maintainability.
-
When to Use Route-based:
- The application is small, and adding Flask-RESTful is overkill.
- Endpoints are limited in number and don’t require complex organization.
- You prefer simplicity over the additional abstraction provided by Flask-RESTful.
Your Case
Since both methods lead to the same result and the only difference is the field ordering:
- If you are building a RESTful API (e.g., for Azure integration or larger projects), stick with Flask-RESTful for its structure and scalability.
- If this is a small utility or one-off endpoint, the route-based approach is perfectly fine.
About Field Ordering
The deviation in field ordering is due to:
- Flask-RESTful uses Python’s
json
library directly, which preserves insertion order for dictionaries. - Route-based approach uses Flask’s
jsonify
, which appliessort_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"}
Recommendation
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.
Hamedgh2k04 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2