Can’t decide between resource or route based invokation

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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()
</code>
<code>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() </code>
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.

  1. Which of those two approaches is preferred or are they equivalently appropriate?
  2. 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

  1. 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:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <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.
    
  2. 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:

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    <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

  1. 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.
  2. 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:

  1. If you are building a RESTful API (e.g., for Azure integration or larger projects), stick with Flask-RESTful for its structure and scalability.
  2. 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 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from flask import jsonify
@app.route("/compute-route", methods=["GET"])
def execute():
return jsonify(compute(request.args.to_dict())), 200, {"Content-Type": "application/json"}
</code>
<code>from flask import jsonify @app.route("/compute-route", methods=["GET"]) def execute(): return jsonify(compute(request.args.to_dict())), 200, {"Content-Type": "application/json"} </code>
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.

New contributor

Hamedgh2k04 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật