pythonflaskflask-restful

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.

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?

Solution

  • 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:

      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:

      @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:

    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.