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.

    cli: Configured for use in a production environment without initializing extensions. (Use for CI/CD)

  • 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.

Raises:

werkzeug.exceptions.HTTPException – An exception containing the HTTP status code and custom message if supplied.

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.Query(entities, session=None)[source]

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

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

Integrates SQLAlchemy with Flask. This handles setting up one or more engines, associating tables and models with specific engines, and cleaning up connections and sessions after each request.

Only the engine configuration is specific to each application, other things like the model, table, metadata, and session are shared for all applications using that extension instance. Call init_app() to configure the extension on an application.

After creating the extension, create model classes by subclassing Model, and table classes with Table. These can be accessed before init_app() is called, making it possible to define the models separately from the application.

Accessing session and engine requires an active Flask application context. This includes methods like create_all() which use the engine.

This class also provides access to names in SQLAlchemy’s sqlalchemy and sqlalchemy.orm modules. For example, you can use db.Column and db.relationship instead of importing sqlalchemy.Column and sqlalchemy.orm.relationship. This can be convenient when defining models.

Parameters:
  • app – Call init_app() on this Flask application now.

  • metadata – Use this as the default sqlalchemy.schema.MetaData. Useful for setting a naming convention.

  • session_options – Arguments used by session to create each session instance. A scopefunc key will be passed to the scoped session, not the session instance. See sqlalchemy.orm.sessionmaker for a list of arguments.

  • query_class – Use this as the default query class for models and dynamic relationships. The query interface is considered legacy in SQLAlchemy.

  • model_class – Use this as the model base class when creating the declarative model class Model. Can also be a fully created declarative model class for further customization.

  • engine_options – Default arguments used when creating every engine. These are lower precedence than application config. See sqlalchemy.create_engine() for a list of arguments.

  • add_models_to_shell – Add the db instance and all model classes to flask shell.

Changed in version 3.0: An active Flask application context is always required to access session and engine.

Changed in version 3.0: Separate metadata are used for each bind key.

Changed in version 3.0: The engine_options parameter is applied as defaults before per-engine configuration.

Changed in version 3.0: The session class can be customized in session_options.

Changed in version 3.0: Added the add_models_to_shell parameter.

Changed in version 3.0: Engines are created when calling init_app rather than the first time they are accessed.

Changed in version 3.0: All parameters except app are keyword-only.

Changed in version 3.0: The extension instance is stored directly as app.extensions["sqlalchemy"].

Changed in version 3.0: Setup methods are renamed with a leading underscore. They are considered internal interfaces which may change at any time.

Changed in version 3.0: Removed the use_native_unicode parameter and config.

Changed in version 3.0: The COMMIT_ON_TEARDOWN configuration is deprecated and will be removed in Flask-SQLAlchemy 3.1. Call db.session.commit() directly instead.

Changed in version 2.4: Added the engine_options parameter.

Changed in version 2.1: Added the metadata, query_class, and model_class parameters.

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

Changed in version 0.16: scopefunc is accepted in session_options.

Changed in version 0.10: Added the session_options parameter.


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.

    cli: Configured for use in a production environment without initializing extensions. (Use for CI/CD)

  • 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.views.openapi 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