Skip to content

Add new route

Adding a new route

Laputa uses Flask and flask-restful to define HTTP route handlers.

The laputa.api.server module exposes a create_app factory function that is responsible for creating the Flask WSGI application, following the app factory pattern. In concrete terms, this factory:

  • instantiates the flask application,
  • instantiates the flask-restful api object,
  • registers instance and smallapp routes,
  • registers a pre-request hook that will set up the application context on flask's global g object (e.g. database manager, config, small app),
  • registers a post-request hook that will configure custom headers, mostly to handle CORS response headers in the context of an embed request but also general cache control headers for JSON responses.

Routing itself is done in the laputa.api.routes module inside two distinct functions: register_instance_resources for "global" instance routes and register_smallapp_resources for "local" smallapp ones. In these functions, you have access to the Flask-RESTful API object and just have to follow its official API, that is:

  • create a Resource subclass,
  • implement HTTP methods that you want to handle,
  • bind the route definition to your Resource subclass.

Resource classes generally live in the laputa.api.resources subpackage, you should create a new module (or modify an existing one) in this subpackage for your new resource class.

Creating a dummy hello route

Let's assume that we want to create an hello route that simply returns the {"message": "hello"} payload. The route should also accept an optional recipient and say her / his name if specified.

Create the resource

We'll create a new laputa.api.resources.hello python module with the following code:

from flask_restful import Resource

class Hello(Resource):
    """Handle /hello/<recipient> routes
    """
    def get(self, recipient: str = None):
        if recipient:
            message = f'Hello {recipient}'
        else:
            message = 'Hello'
        return {'message': message}

Bind the route

Routes are defined in the laputa.api.routes module. Since it's a global instance route, we'll update the register_instance_resources function:

# [...]
from .resources.hello import Hello
# [...]

def register_instance_resources(api: Api):
    # [...]
    api.add_resource(Hello, '/hello', '/hello/<string:recipient>')
    # [...]