Class-Based Approach for Decorators in Open Source

Class-Based Approach for Decorators in Open Source

Introduction

I discovered this cool approach of decorators from the open source community that shows a practical class-based approach for using decorators in FastAPI applications.

Found this in the the fastapi-class repository which simplifies the management of API routes through the power of Python classes.

Let's dive into it.

Exploring the Class-Based Decorator

The class-based decorator @View in the fastapi-class project is a perfect example of Python's flexibility and dynamic nature. It uses classes to streamline the setup and management of API routes, reducing boilerplate and improving code clarity.

Let's check a simplified example to understand how this actually works:

from fastapi import FastAPI, APIRouter
from fastapi_class import View

# Define the class-based view decorator for FastAPI
def View(
    router: FastAPI | APIRouter,  # Router instance from FastAPI
    *,
    path: str = "/",  # Default path for the API route
    default_status_code: int = 200,  # Default HTTP status code
    name_parser: Callable[[object, str], str] = lambda cls, method: f"{method.capitalize()} {cls.__name__}"
):
    def decorator(cls):
        instance = cls()
        for method_name in dir(instance):
            if callable(getattr(instance, method_name)):
                method = getattr(instance, method_name)
                route_name = name_parser(cls, method_name)  # Generate a name for the route
                # Add route to the router
                router.add_api_route(path, method, methods=[method_name.upper()], name=route_name)
        return cls
    return decorator

# Creating an instance of FastAPI
app = FastAPI()

# Apply the class-based decorator to a class defining API endpoints
@View(app)  # 'app' it's an argument to the '@View' decorator
class MyView:
    # Each method in this class becomes an API route
    async def get(self):
        return {"message": "Hello, World!"}

This design uses class-based concepts, because it decorates whole classes (MyView in the example). The @View function is essentially a factory for creating decorators customized to specific routing needs in a FastAPI application.

Why This Approach

  • Reduce Repetition: By using this class-based decorator, we eliminate the need to repeatedly set up individual routes. Everything is nicely packaged within a class.

  • Improved Readability: This approach makes the code more intuitive and easier to maintain, especially as the application grows.

  • Flexible and Dynamic: It dynamically generates routes based on the methods defined in the class, offering flexibility and reducing errors.

Conclusion

That's why I'm such a big fan of open source, always learning.

Exploring open source projects like this not only improves your coding skills but also makes you come up with innovative solutions for your own challenges.