API Reference

The create_app function is the main entrypoint for creating flask_ligand Flask APIs. (See the for Quickstart Guide for a full example of usage)


flask_ligand.create_app(flask_app_name, flask_env, api_title, api_version, openapi_client_name, **kwargs)[source]

Create Flask application.

Parameters:
  • flask_app_name (str) – This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more. So it’s important what you provide one. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package.

  • flask_env (str) –

    Specify the environment to use when launching the flask app. Available environments:

    prod: Configured for use in a production environment.

    stage: Configured for use in a development/staging environment.

    local: Configured for use with a local Flask server.

    testing: Configured for use in unit testing.

  • api_title (str) – The title (name) of the API to display in the OpenAPI documentation.

  • api_version (str) – The semantic version for the OpenAPI client.

  • openapi_client_name (str) – The package name to use for generated OpenAPI clients.

  • kwargs (Any) – Additional settings to add to the configuration object or overrides for unprotected settings.

Return type:

Tuple[Flask, Api]

Returns:

A tuple with a fully configured Flask application and an Api ready to register additional Blueprints.

Raises:

RuntimeError – Attempted to override a protected setting, specified an additional setting that was not all uppercase or the specified environment is invalid.

Extensions

The flask_ligand.extensions module provides extensions (overrides) to flask-sqlalchemy, marshmallow-sqlalchemy, flask-smorest, SQLAlchemy and flask-jwt-extended classes and functions used to construct Flask REST applications.

Api

flask_ligand.extensions.api.abort(http_status, message=None)[source]

Raise a HTTPException for the given http_status. Attach any keyword arguments to the exception for later processing.

Parameters:
  • http_status (HTTPStatus) – A valid HTTPStatus enum which will be used for reporting the HTTP response status and code.

  • message (Optional[str]) – Custom message to return within the body or a default HTTP status message will be returned instead.

Return type:

None


class flask_ligand.extensions.api.Blueprint(*args, **kwargs)[source]

Blueprint override example. See comments below on how to create a custom converter for your schemas.


class flask_ligand.extensions.api.Api(app=None, *, spec_kwargs=None)[source]

Extension of the flask_smorest.Api main class which provides helpers to build a REST API using Flask.

Using this extension will automatically enable an “Authorize” button to the SwaggerUI docs.

Parameters:
  • app (Optional[Flask]) – Flask application

  • spec_kwargs (Optional[dict[str, Any]]) – kwargs to pass to internal APISpec instance. The spec_kwargs dictionary is passed as kwargs to the internal APISpec instance. flask-smorest adds a few parameters to the original parameters documented in apispec.APISpec


class flask_ligand.extensions.api.Schema(*, only=None, exclude=(), many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None)[source]

Extend Schema to automatically exclude unknown fields and enforce ordering of fields in the SwaggerUI documentation.

Parameters:
  • only (types.StrSequenceOrSet | None) –

  • exclude (types.StrSequenceOrSet) –

  • many (bool) –

  • context (dict | None) –

  • load_only (types.StrSequenceOrSet) –

  • dump_only (types.StrSequenceOrSet) –

  • partial (bool | types.StrSequenceOrSet) –

  • unknown (str | None) –


class flask_ligand.extensions.api.AutoSchema(*args, **kwargs)[source]

Extend SQLAlchemyAutoSchema to include the foreign key, automatically raise an exception when unknown fields are specified, enforce ordering of fields in the SwaggerUI and enforce the use of ISO-8601 for datetime fields. documentation.


class flask_ligand.extensions.api.SQLCursorPage(collection, page_params)[source]

SQL cursor pager used for paginated endpoints.


class flask_ligand.extensions.api.BaseQuery(entities, session=None)[source]

Enable customized REST JSON error messages for ‘get_or_404’ and ‘first_or_404’ methods for BaseQuery.

first_or_404(description=None)[source]

Like ‘first’ but aborts with 404 if not found instead of returning None.

Parameters:

description (Optional[str]) – Override default 404 status code message with a custom message instead.

Return type:

Any

get_or_404(ident, description=None)[source]

Like get but aborts with 404 if not found instead of returning None.

Parameters:
  • ident (object) – A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed.

  • description (Optional[str]) – Override default 404 status code message with a custom message instead.

Return type:

Any


Database

flask_ligand.extensions.database.DB

This class is used to control the SQLAlchemy integration to one or more Flask applications. Depending on how you initialize the object it is usable right away or will attach as needed to a Flask application.

There are two usage modes which work very similarly. One is binding the instance to a very specific Flask application:

app = Flask(__name__)
db = SQLAlchemy(app)

The second possibility is to create the object once and configure the application later to support it:

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

The difference between the two is that in the first case methods like create_all() and drop_all() will work all the time but in the second case a flask.Flask.app_context() has to exist.

By default Flask-SQLAlchemy will apply some backend-specific settings to improve your experience with them.

As of SQLAlchemy 0.6 SQLAlchemy will probe the library for native unicode support. If it detects unicode it will let the library handle that, otherwise do that itself. Sometimes this detection can fail in which case you might want to set use_native_unicode (or the SQLALCHEMY_NATIVE_UNICODE configuration key) to False. Note that the configuration key overrides the value you pass to the constructor. Direct support for use_native_unicode and SQLALCHEMY_NATIVE_UNICODE are deprecated as of v2.4 and will be removed in v3.0. engine_options and SQLALCHEMY_ENGINE_OPTIONS may be used instead.

This class also provides access to all the SQLAlchemy functions and classes from the sqlalchemy and sqlalchemy.orm modules. So you can declare models like this:

class User(db.Model):
    username = db.Column(db.String(80), unique=True)
    pw_hash = db.Column(db.String(80))

You can still use sqlalchemy and sqlalchemy.orm directly, but note that Flask-SQLAlchemy customizations are available only through an instance of this SQLAlchemy class. Query classes default to BaseQuery for db.Query, db.Model.query_class, and the default query_class for db.relationship and db.backref. If you use these interfaces through sqlalchemy and sqlalchemy.orm directly, the default query class will be that of sqlalchemy.

Check types carefully

Don’t perform type or isinstance checks against db.Table, which emulates Table behavior but is not a class. db.Table exposes the Table interface, but is a function which allows omission of metadata.

The session_options parameter, if provided, is a dict of parameters to be passed to the session constructor. See Session for the standard options.

The engine_options parameter, if provided, is a dict of parameters to be passed to create engine. See create_engine() for the standard options. The values given here will be merged with and override anything set in the 'SQLALCHEMY_ENGINE_OPTIONS' config variable or othewise set by this library.

New in version 0.10: The session_options parameter was added.

New in version 0.16: scopefunc is now accepted on session_options. It allows specifying a custom function which will define the SQLAlchemy session’s scoping.

New in version 2.1: The metadata parameter was added. This allows for setting custom naming conventions among other, non-trivial things.

The query_class parameter was added, to allow customisation of the query class, in place of the default of BaseQuery.

The model_class parameter was added, which allows a custom model class to be used in place of Model.

Changed in version 2.1: Utilise the same query class across session, Model.query and Query.

New in version 2.4: The engine_options parameter was added.

Changed in version 2.4: The use_native_unicode parameter was deprecated.

Changed in version 2.4.3: COMMIT_ON_TEARDOWN is deprecated and will be removed in version 3.1. Call db.session.commit() directly instead.


Authentication (JWT)

class flask_ligand.extensions.jwt.User(id, roles)[source]

A simple class representing pertinent user information.

Parameters:
  • id (str) – The UUID of the user.

  • roles (list[str]) – A list of roles that the user has been assigned.


flask_ligand.extensions.jwt.jwt_role_required(role)[source]

A decorator for restricting access to an endpoint based on role membership.

Note: This decorator style was chosen because of: https://stackoverflow.com/a/42581103

Parameters:

role (str) – The role membership required by the user in order to access this endpoint.


Default Settings

The flask_ligand.default_settings module defines default settings for the prod, stage, local, and testing environments.

class flask_ligand.default_settings.ProdConfig(api_title, api_version, openapi_client_name, **kwargs)[source]

Configuration for production environments.

Parameters:
  • api_title (str) – The title (name) of the API to display in the OpenAPI documentation.

  • api_version (str) – The semantic version for the OpenAPI client.

  • openapi_client_name (str) – The package name to use for generated OpenAPI clients.

  • kwargs (dict[str, Any]) – Additional settings to add to the configuration.

Raises:

RuntimeError – Attempted to override a protected setting or specified an additional setting that was not all uppercase.


class flask_ligand.default_settings.StagingConfig(api_title, api_version, openapi_client_name, **kwargs)[source]

Configuration for development/staging environments.

Parameters:
  • api_title (str) – The title (name) of the API to display in the OpenAPI documentation.

  • api_version (str) – The semantic version for the OpenAPI client.

  • openapi_client_name (str) – The package name to use for generated OpenAPI clients.

  • kwargs (dict[str, Any]) – Additional settings to add to the configuration.

Raises:

RuntimeError – Attempted to override a protected setting or specified an additional setting that was not all uppercase.


class flask_ligand.default_settings.FlaskLocalConfig(api_title, api_version, openapi_client_name, **kwargs)[source]

Configuration used for running a local Flask server.

Parameters:
  • api_title (str) – The title (name) of the API to display in the OpenAPI documentation.

  • api_version (str) – The semantic version for the OpenAPI client.

  • openapi_client_name (str) – The package name to use for generated OpenAPI clients.

  • kwargs (dict[str, Any]) – Additional settings to add to the configuration.

Raises:

RuntimeError – Attempted to override a protected setting or specified an additional setting that was not all uppercase.


class flask_ligand.default_settings.TestingConfig(api_title, api_version, openapi_client_name, **kwargs)[source]

Configuration used for unit testing.

Parameters:
  • api_title (str) – The title (name) of the API to display in the OpenAPI documentation.

  • api_version (str) – The semantic version for the OpenAPI client.

  • openapi_client_name (str) – The package name to use for generated OpenAPI clients.

  • kwargs (dict[str, Any]) – Additional settings to add to the configuration.

Raises:

RuntimeError – Attempted to override a protected setting or specified an additional setting that was not all uppercase.


flask_ligand.default_settings.flask_environment_configurator(app, environment, api_title, api_version, openapi_client_name, **kwargs)[source]

Update a Flask app configuration for a given environment with optional setting overrides.

Parameters:
  • app (Flask) – The root Flask app to configure with the given extension.

  • environment (str) –

    The target environment to create a Flask configuration object for. Available environments:

    prod: Configured for use in a production environment.

    stage: Configured for use in a development/staging environment.

    local: Configured for use with a local Flask server.

    testing: Configured for use in unit testing.

  • api_title (str) – The title (name) of the API to display in the OpenAPI documentation.

  • api_version (str) – The semantic version for the OpenAPI client.

  • openapi_client_name (str) – The package name to use for generated OpenAPI clients.

  • kwargs (Any) – Additional settings to add to the configuration object or overrides for unprotected settings.

Raises:

RuntimeError – Attempted to override a protected setting, specified an additional setting that was not all uppercase or the specified environment is invalid.

Return type:

None


Views

The flask_ligand.default_settings module contains built-in endpoints (a.k.a. Flask View) for generating OpenAPI clients for TypeScript and Python. Also, a global variable is provided that will add an “Authorize” button to the SwaggerUI documentation.

class flask_ligand.views.openapi.OpenApiTypescriptAxios[source]
get(args)[source]

Generate a ‘typescript-axios’ OpenAPI client for this service.

NOTE: The link provided is only good for one download before it expires!

See for more details: https://openapi-generator.tech/docs/generators

Return type:

Any

Parameters:

args (Mapping[str, Any]) –


class flask_ligand.views.openapi.OpenApiPython[source]
get(args)[source]

Generate a ‘python’ OpenAPI client for this service.

NOTE: The link provided is only good for one download before it expires!

See for more details: https://openapi-generator.tech/docs/generators

Return type:

Any

Parameters:

args (Mapping[str, Any]) –


flask_ligand.views.common.openapi_doc.BEARER_AUTH: Any

Enable bearer authentication for Swagger-UI docs