Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - MODERATE-Project/moderate-platform-api: The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users. · GitHub
Skip to content

Latest commit

History

318 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MODERATE Platform API

This repository contains the HTTP API of the MODERATE platform, serving as the public entry point for developers to interact programmatically with the data assets and services provided by MODERATE.

The API is based on the following main building blocks:

  • FastAPI as the HTTP API framework.
  • SQLModel to define the data models and interact with the database.
  • Casbin to implement the authorization layer.

Authentication is handled by the central MODERATE identity provider (Keycloak). The API is prepared to sit behind MODERATE's API gateway (APISIX) which communicates with Keycloak to issue access tokens and then include them in the Authorization header of the requests forwarded to the API. The API then validates the token and extracts the user's identity from it.

Authorization is based on the list of roles assigned to the user in Keycloak, which are then mapped to permissions in the API using Casbin.

Documentation of the API is based on the OpenAPI specification and is automatically generated by FastAPI.

Development

You can deploy a local development instance of the API that includes APISIX and Keycloak in an effort to reproduce the production environment.

Configuration load order for local development:

  1. Taskfile.yml loads .env.dev first.
  2. Missing values fall back to .env.dev.default.
  3. The API reads MODERATE_API_* variables via moderate_api/config.py (nested fields use __, for example MODERATE_API_S3__BUCKET).

To use MinIO:

task dev-up

To use GCS (or any other S3-compatible service):

ACCESS_KEY="TheAccessKey" SECRET_KEY="TheSecretKey" task dev-up-gcs

Database migrations

Alembic migrations live in migrations/versions/ and are managed through Taskfile.yml.

When you change SQLModel metadata, create a revision and review the generated file before applying it:

task alembic-revision MSG="Describe the schema change"

Apply migrations with MIGRATIONS_SQLALCHEMY_URL, which is Alembic's own DB URL and should use a synchronous SQLAlchemy driver such as postgresql://...:

MIGRATIONS_SQLALCHEMY_URL="postgresql://postgres:postgres@localhost:5433/moderateapi" task alembic-upgrade

Important

The API still bootstraps the base schema on startup via SQLModel.metadata.create_all(). In other words, a fresh database is expected to be initialized by running the container first, and Alembic migrations are used for tracked schema deltas on top of that already-created schema.

This means the migration chain is intentionally state-dependent: revisions may assume the target tables already exist, and should be written defensively so they can handle both cases where the current app bootstrapping has already created the target objects and cases where only the older base schema exists.

Production deploys should therefore run task alembic-upgrade against the production database as an explicit deployment step before or together with the new API release; the container image does not run Alembic automatically on startup.

Create an admin user

You need to create an admin user in Keycloak to be able to log in to the API. Moreover, this user needs to be assigned a specific role. Check the Compose file and .env.dev.default for the URLs and default credentials.

The role name is defined in the moderate_api/config.py file. Please note that this role is a client-level role, and not a realm-level role—the role should be created in the apisix client.

Trust Services

The MODERATE Trust Services are an optional dependency of the platform API. When this dependency is available, the API can use it to check the integrity of datasets via cryptographic proofs stored in the IOTA DLT.

To deploy a development instance of the Trust Services along with the API:

  1. Ensure .env.trust is present (tracked in this repo).
  2. Create .env.trust.local with L2_PRIVATE_KEY.
  3. Run task trust-up (or task dev-up, which calls it).

Environment Variables Reference

API runtime (moderate_api/config.py + moderate_api/__init__.py)

VariableDefaultRequiredImpact
LOG_LEVELINFO (DEBUG in docker-compose-dev.yml)NoGlobal API log verbosity.
MODERATE_API_POSTGRES_URLpostgresql+asyncpg://postgres:postgres@localhost:5432/moderateapi/Yes for DB-backed endpointsDatabase connection string used by the API engine.
MODERATE_API_OPENID_CONFIG_URLhttps://keycloak.moderate.cloud/realms/moderate/.well-known/openid-configurationYes unless token verification is disabledOpenID discovery URL used to fetch JWKS for JWT verification.
MODERATE_API_DISABLE_TOKEN_VERIFICATIONfalseNoIf true, JWT signature verification is skipped (unsafe outside local/dev testing).
MODERATE_API_VERBOSE_ERRORSfalseNoIf true, DB exception details are returned in API responses.
MODERATE_API_MAX_OBJECTS_PER_ASSET100NoUpload limit per asset (POST /asset/{id}/object).
MODERATE_API_VISUALIZATION_MAX_SIZE_MIB10.0NoMax file size before visualization endpoint starts sampling.
MODERATE_API_VISUALIZATION_EXPIRES_IN_SECONDS1800NoPresigned URL TTL used by visualization endpoint.
MODERATE_API_RESPONSE_TOTAL_COUNT_HEADERX-Total-CountNoHeader key used for total count in paginated responses.
MODERATE_API_RABBIT_ROUTER_URLunsetNoRabbitMQ connection URL; if unset, workflow job submission is unavailable.

API nested settings

VariableDefaultRequiredImpact
MODERATE_API_S3__ACCESS_KEYunsetYes for S3-backed endpointsS3/MinIO access key.
MODERATE_API_S3__SECRET_KEYunsetYes for S3-backed endpointsS3/MinIO secret key.
MODERATE_API_S3__ENDPOINT_URLhttps://storage.googleapis.comNoS3-compatible endpoint (MinIO, GCS S3, AWS, etc.).
MODERATE_API_S3__USE_SSLtrueNoEnables HTTPS for S3 client connections.
MODERATE_API_S3__REGIONunsetYes for S3-backed endpointsS3 region passed to client creation.
MODERATE_API_S3__BUCKETunsetYes for S3-backed endpointsBucket used for asset object storage and retrieval.
MODERATE_API_OAUTH_NAMES__API_GW_CLIENT_IDapisixNoPrefix for client-level roles extracted from JWT.
MODERATE_API_OAUTH_NAMES__ROLE_ADMINapi_adminNoAdmin role suffix used for authorization checks.
MODERATE_API_OAUTH_NAMES__ROLE_BASIC_ACCESSapi_basic_accessNoBasic access role suffix required for non-admin users.
MODERATE_API_TRUST_SERVICE__ENDPOINT_URLunsetRequired only for Trust routesBase URL for DID/proof operations in Trust integration endpoints.
MODERATE_API_OPEN_METADATA_SERVICE__ENDPOINT_URLunsetRequired only for metadata profile routesBase URL for OpenMetadata API calls.
MODERATE_API_OPEN_METADATA_SERVICE__BEARER_TOKENunsetRequired only for metadata profile routesBearer token for OpenMetadata requests.
MODERATE_API_DIVA__ENABLEDfalseNoIf true, API uses real DIVA client; otherwise uses mock behavior.
MODERATE_API_DIVA__KAFKA_REST_URLunsetRequired when DIVA enabledKafka REST base URL used to publish validation jobs.
MODERATE_API_DIVA__QUALITY_REPORTER_URLunsetRequired when DIVA enabledQuality Reporter base URL used to fetch validation results.
MODERATE_API_DIVA__BASIC_AUTH_USERunsetNoOptional basic auth user for DIVA endpoints.
MODERATE_API_DIVA__BASIC_AUTH_PASSWORDunsetNoOptional basic auth password for DIVA endpoints.
MODERATE_API_DIVA__INGESTION_TOPICdata-ingestion-triggerNoKafka topic used for validation trigger messages.
MODERATE_API_DIVA__SUPPORTED_EXTENSIONS["csv"]NoAllowed file extensions for validation endpoints.
MODERATE_API_DIVA__REQUEST_TIMEOUT30NoHTTP timeout (seconds) for DIVA requests.
MODERATE_API_DIVA__PRESIGNED_URL_TTL3600NoPresigned URL TTL (seconds) used for DIVA ingestion.
MODERATE_API_DIVA__COMPLETION_TIMEOUT_SECONDS300NoTimeout window after which validation is treated as terminal.

Local dev stack (.env.dev.default, Taskfile.yml, docker-compose-dev.yml)

VariableDefaultImpact
KEYCLOAK_ADMIN_USERadminBootstrap Keycloak admin account.
KEYCLOAK_ADMIN_PASSWORDadminBootstrap Keycloak admin password.
KEYCLOAK_POSTGRES_DBNAMEkeycloakDB name used by Keycloak container (same postgres server as API dev stack).
POSTGRES_USERpostgresDev PostgreSQL user (also used in API DB URL composition).
POSTGRES_PASSWORDpostgresDev PostgreSQL password.
MINIO_ROOT_USERminioMinIO root user and default S3 access key for local storage.
MINIO_ROOT_PASSWORDminio123MinIO root password and default S3 secret key for local storage.
MINIO_REGIONeu-central-1MinIO region and default API S3 region.
MINIO_BUCKET_NAMEmoderateBucket created by minio_setup and used by API uploads.
RABBITMQ_DEFAULT_USERguestDev RabbitMQ username.
RABBITMQ_DEFAULT_PASSguestDev RabbitMQ password.
TRUST_MONGO_ROOT_USERrootMongo root user for local Trust stack.
TRUST_MONGO_ROOT_PASSrootpasswordMongo root password for local Trust stack.
DEV_KEYCLOAK_PORT8989 (Task default)Host port exposed for local Keycloak.
DEV_POSTGRES_PORT5433 (Task default)Host port exposed for local PostgreSQL.
DEV_RABBIT_PORT5672 (Compose fallback)Host port exposed for RabbitMQ AMQP.
DEV_RABBIT_MANAGEMENT_PORT15672 (Compose fallback)Host port exposed for RabbitMQ management UI.
KC_HOSTNAME_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Keycloak frontend URL override to avoid token-introspection hostname mismatches.
ACTIONS_MINIO_IMAGE_LOCALminio-gh-actionsImage tag used by task push-minio-image.
ACTIONS_MINIO_IMAGE_REMOTEagmangas/minio-gh-actionsRemote image name for GitHub Actions MinIO image.
ACTIONS_MINIO_IMAGE_REMOTE_TAGlatestRemote image tag for GitHub Actions MinIO image.
COMPOSE_PROJECT_NAMEmoderateapiDocker Compose project prefix for the dev stack (container/network naming).

Compose also defines container-specific aliases derived from the variables above:

  • KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASS, KC_DB_USERNAME, KC_DB_PASSWORD, KC_DB_URL_DATABASE (Keycloak container internals)
  • MINIO_USER, MINIO_PASS, MINIO_URL, BUCKET_NAME (used by minio_setup container script)
  • MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD (Trust Mongo bootstrap names)

Trust service runtime (.env.trust + .env.trust.local)

These variables are consumed by the Trust service container (not by FastAPI directly):

Variable groupVariablesImpact
Runtime + bindingRUST_LOG, RUST_BACKTRACE, ADDR_D, ADDR_L, PORT, LOG_FILE_NAMELog level, backtrace behavior, and service bind settings.
IOTA L1 endpointsNODE_URL, FAUCET_URL, EXPLORER_URLL1 node/faucet/explorer integration for DID/proof operations.
IOTA L2 endpointsRPC_PROVIDER, CHAIN_ID, ASSET_FACTORY_ADDR, L2_PRIVATE_KEYL2 transaction execution and signing configuration.
Wallet/key storageSTRONGHOLD_PASSWORD, MNEMONIC, WALLET_DB_PATH, STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_SNAPSHOT_PATH, KEY_STORAGE_STRONGHOLD_PASSWORD, KEY_STORAGE_MNEMONICWallet/identity key material and storage paths.
Trust compose wiringMONGO_PORT, TRUST_PORT, MONGO_DATABASE, IPFS_PORT, TRUST_MONGO_ROOT_USER, TRUST_MONGO_ROOT_PASSLocal Trust stack ports, Mongo DB name, and credentials.

Tests and CI

VariableDefault/usageImpact
TESTS_POSTGRES_URLset by Task/CITests DB URL (used directly by tests/db.py and mapped into MODERATE_API_POSTGRES_URL during tests).
TESTS_MINIO_ROOT_USER / TESTS_MINIO_ROOT_PASSWORDset by Task/CITest S3 credentials.
TESTS_MINIO_ENDPOINT_URL / TESTS_MINIO_USE_SSL / TESTS_MINIO_REGIONset by Task/CITest S3 endpoint/SSL/region.
TESTS_MINIO_BUCKETset in CI, optional locallyBucket name used by tests when building API env.
TESTS_MINIO_BUCKET_NAMEset by Task/ComposeBucket name for test MinIO container setup (different surface from TESTS_MINIO_BUCKET).
TESTS_RABBIT_URLset by Task/CIRabbitMQ URL mapped to MODERATE_API_RABBIT_ROUTER_URL in tests.
TESTS_POSTGRES_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT, TESTS_MINIO_PUBLIC_PORT_CONSOLE, TESTS_RABBIT_PUBLIC_PORT, TESTS_RABBIT_PUBLIC_PORT_MANAGEMENTset by Task/ComposeHost port mappings for test dependency containers.
TESTS_POSTGRES_USER, TESTS_POSTGRES_PASSWORD, TESTS_POSTGRES_DB, TESTS_RABBIT_DEFAULT_USER, TESTS_RABBIT_DEFAULT_PASSset by Task/ComposeContainer bootstrap credentials for test dependencies.
MIGRATIONS_SQLALCHEMY_URLno defaultOptional override for Alembic DB URL (task alembic-upgrade).
PYTEST_VERSIONprovided by pytest runtimeInternal switch used to skip trigram index creation in tests.

UI and utility scripts

VariableDefaultImpact
MODERATE_API_URLhttps://api.gw.moderate.cloud in UI Docker image, http://localhost:8000 in fixtures scriptAPI base URL for UI reverse proxy and fixtures script API calls.
VITE_PROXY_API_TARGEThttp://localhost:8000Vite dev server proxy target for /api and /notebook-*.
VITE_KEYCLOAK_URLproduction .env.production points to cloud KeycloakKeycloak base URL used by UI auth client.
VITE_KEYCLOAK_CLIENT_IDuiKeycloak client ID used by UI.
VITE_KEYCLOAK_REALMmoderateKeycloak realm used by UI.
KEYCLOAK_URLhttp://localhost:${DEV_KEYCLOAK_PORT}Fixtures script Keycloak endpoint.
MODERATE_REALMmoderateFixtures script realm.
APISIX_CLIENT_ID / APISIX_CLIENT_SECRETapisixFixtures script OAuth client credentials.
KEYCLOAK_USERNAME / KEYCLOAK_PASSWORDunsetRequired credentials for fixtures creation (task fixtures-create).

Practical notes

  1. Keep secrets out of VCS: use .env.dev and .env.trust.local for local overrides.
  2. If auth fails unexpectedly in dev, check MODERATE_API_OPENID_CONFIG_URL and KC_HOSTNAME_URL first.
  3. If uploads/visualization fail, verify the full MODERATE_API_S3__* set and bucket existence.
  4. If workflow job creation fails with "Message broker connection not available", set MODERATE_API_RABBIT_ROUTER_URL.

About

The central REST API and web user interface of the MODERATE platform, providing programmatic access to datasets, user management, and data quality services. Built with FastAPI and React, it serves as the primary integration point for external developers and end-users.

Topics

Resources

Stars

1 star

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages