Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Routing via decorators with Flask-RESTful

Posted by Gil Shotan on 2015-02-24 @ 17:56 and filed in Decorators

from flask import Flask
from flask.ext import restful
import types

app = Flask(__name__) 
api = restful.Api(app)


def api_route(self, *args, **kwargs):
    def wrapper(cls):
        self.add_resource(cls, *args, **kwargs)
        return cls
    return wrapper

api.route = types.MethodType(api_route, api)

Now you can use the api object for routing just like you use the regular flask object

from flask.ext import restful
from yourapplication import api

@api.route('/users/{username}')
class User(restful.Resource):
   
    def get(self, username):
        return {'username': username}

This snippet by Gil Shotan can be used freely for anything you like. Consider it public domain.