Alireza
Alireza

Reputation: 6868

How to define a base route in Flask API routing system

In some frameworks like slim php framework you can define base route that is the same in all routes like /api/v1.

So in slim we can group route to not put /api/v1 in every route:

$app->group('/api/v1', function () use ($app) {

        // Get book with ID
        $app->get('/books/:id', function ($id) {

        });

        // Update book with ID
        $app->put('/books/:id', function ($id) {

        });

        // Delete book with ID
        $app->delete('/books/:id', function ($id) {

        });

});

But in Flask I couldn't find an easy way to group routes. What if I have to write /api/v1 in every resource I call? Is there a way to group them?

In python I should use something like below:

class TaskListAPI(Resource):
    def get(self):
        pass

    def post(self):
        pass

class TaskAPI(Resource):
    def get(self, id):
        pass

    def put(self, id):
        pass

    def delete(self, id):
        pass

api.add_resource(TaskListAPI, '/api/v1/tasks', endpoint = 'tasks')
api.add_resource(TaskAPI, '/api/v1/tasks/<int:id>', endpoint = 'task')

Upvotes: 1

Views: 1864

Answers (2)

While Blueprints are great, it looks like you are looking for a more specific extension, to suit your desire to build an API that easily differs between HTTP methods.

You might want to have a look at Flask-Classy, which is a flask extension, that does just that. You can create a class per resource (just as you describe on your pseudocode) and differ on the http methods:

from flask_classy import FlaskView


class TaskView(FlaskView):
    def index(self):
        """Return a list of all tasks."""
        pass

    def get(self, id):
        """Get a specific task."""
        pass

    def delete(self, id):
        """Delete the task."""
        pass

TaskView.register(app)

Additionally Flask-Classy supports a lot of ways to customize the endpoints, if you have special cases.

Upvotes: 2

Matt Healy
Matt Healy

Reputation: 18531

I think you are looking for Blueprints. Blueprints are a great way to separate your app in to several smaller sections - for example, you might have a "main" blueprint for your web app, an "admin" blueprint for the admin interface and an "api" blueprint for your RESTful API.

Upvotes: 2

Related Questions