ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(api): add typed endpoint contracts and envelopes
Juan Denis3c25680351dc
diff --git a/backend/app/api/contracts.py b/backend/app/api/contracts.pynew file mode 100644index 00000000..938bb3ba--- /dev/null+++ b/backend/app/api/contracts.py@@ -0,0 +1,120 @@+"""Typed request validation and OpenAPI metadata for API endpoints.++The route is still an ordinary Flask function. This module owns only the HTTP+boundary: it loads query/JSON input through a Marshmallow schema, raises the+shared application ``ValidationError`` on bad input, and records enough+metadata for ``OpenAPIService`` to document the real contract.++Usage::++ @blueprint.route('', methods=['POST'])+ @auth_required()+ @api_contract(body=CreateWidgetSchema, responses={201: WidgetEnvelopeSchema})+ def create_widget(body):+ return data_response(widget_service.create(body), status=201)++Decorators that use ``functools.wraps`` (including ServerKit's authentication+decorators) preserve ``__api_contract__`` when they wrap this one.+"""++from dataclasses import dataclass+from functools import wraps+from typing import Mapping++from flask import request+from marshmallow import RAISE, Schema, ValidationError as SchemaValidationError++from app.exceptions import ValidationError+++class ApiSchema(Schema):+ """Strict base schema for an HTTP request or response contract."""++ class Meta:+ unknown = RAISE+++@dataclass(frozen=True)+class ResponseContract:+ """One documented response body."""++ schema: type[Schema]+ description: str = 'Success'+++@dataclass(frozen=True)+class EndpointContract:+ """Metadata attached to a validated Flask view."""++ query: type[Schema] | None+ body: type[Schema] | None+ responses: Mapping[int, ResponseContract]+++def _schema_type(schema):+ if schema is None:+ return None+ if isinstance(schema, type) and issubclass(schema, Schema):+ return schema+ raise TypeError('API contracts require a marshmallow Schema class')+++def _response_contracts(responses):+ normalized = {}+ for status, value in (responses or {}).items():+ if isinstance(value, ResponseContract):+ normalized[int(status)] = value+ else:+ normalized[int(status)] = ResponseContract(_schema_type(value))+ return normalized+++def _load(schema_type, raw, *, location):+ try:+ return schema_type().load(raw)+ except SchemaValidationError as exc:+ label = 'query parameters' if location == 'query' else 'JSON body'+ raise ValidationError(+ f'Invalid {label}',+ code=f'invalid_{location}',+ details={'fields': exc.messages},+ ) from exc+++def api_contract(*, query=None, body=None, responses=None):+ """Validate endpoint input and publish its machine-readable contract.++ Validated values are passed as the ``query`` and/or ``body`` keyword+ arguments. Request schemas are instantiated per call so custom schema+ state cannot leak between concurrent requests.+ """++ query_type = _schema_type(query)+ body_type = _schema_type(body)+ contract = EndpointContract(+ query=query_type,+ body=body_type,+ responses=_response_contracts(responses),+ )++ def decorate(view):+ @wraps(view)+ def validated_view(*args, **kwargs):+ if query_type is not None:+ raw_query = request.args.to_dict(flat=True)+ kwargs['query'] = _load(query_type, raw_query, location='query')++ if body_type is not None:+ raw_body = request.get_json(silent=True)+ kwargs['body'] = _load(+ body_type,+ {} if raw_body is None else raw_body,+ location='body',+ )++ return view(*args, **kwargs)++ validated_view.__api_contract__ = contract+ return validated_view++ return decoratediff --git a/backend/app/api/responses.py b/backend/app/api/responses.pynew file mode 100644index 00000000..1ddb0533--- /dev/null+++ b/backend/app/api/responses.py@@ -0,0 +1,31 @@+"""Canonical JSON response envelopes for newly converged API endpoints."""++from flask import jsonify+++def data_response(data, *, status=200, message=None, meta=None, legacy=None):+ """Return a stable ``data`` envelope with optional compatibility fields.++ ``legacy`` is deliberately explicit. It supports additive migrations of+ public endpoints without making old top-level names the default for new+ code. Every use should have a consumer-removal condition in its domain.+ """++ payload = {'data': data}+ if meta is not None:+ payload['meta'] = meta+ if message:+ payload['message'] = message+ if legacy:+ payload.update(legacy)+ return jsonify(payload), status+++def list_response(items, *, total=None, status=200, meta=None, legacy_key=None):+ """Return the canonical list envelope and paging metadata."""++ rows = list(items)+ list_meta = dict(meta or {})+ list_meta.setdefault('total', len(rows) if total is None else total)+ legacy = {legacy_key: rows} if legacy_key else None+ return data_response(rows, status=status, meta=list_meta, legacy=legacy)diff --git a/backend/app/api/schemas/__init__.py b/backend/app/api/schemas/__init__.pynew file mode 100644index 00000000..8e2a49b6--- /dev/null+++ b/backend/app/api/schemas/__init__.py@@ -0,0 +1 @@+"""Feature-specific request and response schemas for the public API."""diff --git a/backend/app/api/schemas/search.py b/backend/app/api/schemas/search.pynew file mode 100644index 00000000..851d38c8--- /dev/null+++ b/backend/app/api/schemas/search.py@@ -0,0 +1,36 @@+"""Contracts for the unified entity search endpoint."""++from marshmallow import fields, post_load++from app.api.contracts import ApiSchema+++class SearchQuerySchema(ApiSchema):+ q = fields.String(load_default='')+ workspace_id = fields.String(load_default=None, allow_none=True)++ @post_load+ def normalize(self, data, **_kwargs):+ data['q'] = data['q'].strip()+ if data.get('workspace_id') is not None:+ data['workspace_id'] = data['workspace_id'].strip() or None+ return data+++class SearchResultSchema(ApiSchema):+ type = fields.String(required=True)+ label = fields.String(required=True)+ sublabel = fields.String(required=True)+ path = fields.String(required=True)+++class ListMetaSchema(ApiSchema):+ total = fields.Integer(required=True)+++class SearchResponseSchema(ApiSchema):+ data = fields.List(fields.Nested(SearchResultSchema), required=True)+ meta = fields.Nested(ListMetaSchema, required=True)+ # Additive compatibility field. Remove after external clients have migrated+ # to ``data`` and the frontend compatibility adapter is no longer needed.+ results = fields.List(fields.Nested(SearchResultSchema), required=True)diff --git a/backend/app/api/search.py b/backend/app/api/search.pyindex e2b03fc9..1847b1c6 100644--- a/backend/app/api/search.py+++ b/backend/app/api/search.py@@ -5,9 +5,12 @@ core entity types (services, servers, domains, databases, WordPress sites, cronjobs, extensions, vaults). Business logic lives in SearchService; this blueprintjust validates the term, resolves the user, and shapes the JSON."""-from flask import Blueprint, request, jsonify+from flask import Blueprint, requestfrom flask_jwt_extended import jwt_required, get_jwt_identity+from app.api.contracts import api_contract+from app.api.responses import list_response+from app.api.schemas.search import SearchQuerySchema, SearchResponseSchemafrom app.models.user import Userfrom app.services.search_service import SearchService@@ -16,13 +19,14 @@ search_bp = Blueprint('search', __name__)@search_bp.route('', methods=['GET'])@jwt_required()-def search():- """Search entities by name. ?q=<term> (>= 2 chars). Returns {'results': [...]}."""- q = request.args.get('q', '').strip()+@api_contract(query=SearchQuerySchema, responses={200: SearchResponseSchema})+def search(query):+ """Search entities by name. ``q`` terms shorter than two chars return none."""+ q = query['q']if len(q) < 2:- return jsonify({'results': []}), 200+ return list_response([], legacy_key='results')user = User.query.get(get_jwt_identity())- workspace = request.headers.get('X-Workspace-Id') or request.args.get('workspace_id')+ workspace = request.headers.get('X-Workspace-Id') or query['workspace_id']rows = SearchService.search(user, q, workspace)- return jsonify({'results': rows}), 200+ return list_response(rows, legacy_key='results')diff --git a/backend/app/services/openapi_service.py b/backend/app/services/openapi_service.pyindex a4362a12..438834af 100644--- a/backend/app/services/openapi_service.py+++ b/backend/app/services/openapi_service.py@@ -1,5 +1,8 @@"""Service for generating OpenAPI 3.0 specification."""import re++from apispec import APISpec+from apispec.ext.marshmallow import MarshmallowPluginfrom flask import current_app@@ -89,11 +92,19 @@ class OpenAPIService:'schemas': {'Error': {'type': 'object',+ 'required': ['error', 'status', 'code', 'request_id'],'properties': {'error': {'type': 'string','description': 'Error message',},+ 'status': {'type': 'integer'},+ 'code': {'type': 'string'},+ 'details': {+ 'type': 'object',+ 'additionalProperties': True,+ },+ 'request_id': {'type': 'string'},},},'Message': {@@ -144,6 +155,39 @@ class OpenAPIService:# Collect tags and paths from registered routestags_seen = set()paths = {}+ marshmallow_plugin = MarshmallowPlugin()+ schema_spec = APISpec(+ title='ServerKit endpoint schemas',+ version='1.0.0',+ openapi_version='3.0.3',+ plugins=[marshmallow_plugin],+ )++ def schema_ref(schema_type):+ """Register a Marshmallow schema once and return its OpenAPI ref."""+ name = schema_type.__name__+ # The Marshmallow plugin registers nested schemas recursively, so+ # consult the component registry itself rather than a parallel set.+ if name not in schema_spec.components.schemas:+ schema_spec.components.schema(name, schema=schema_type)+ generated = schema_spec.to_dict().get('components', {}).get('schemas', {})+ spec['components']['schemas'].update(generated)+ return {'$ref': f'#/components/schemas/{name}'}++ def query_parameters(schema_type):+ """Expand a query-object schema into ordinary OpenAPI parameters."""+ schema_ref(schema_type)+ document = spec['components']['schemas'][schema_type.__name__]+ required = set(document.get('required', ()))+ return [+ {+ 'name': name,+ 'in': 'query',+ 'required': name in required,+ 'schema': field_schema,+ }+ for name, field_schema in document.get('properties', {}).items()+ ]for rule in app.url_map.iter_rules():# Only include API routes@@ -169,6 +213,7 @@ class OpenAPIService:# Get view function docstringview_func = app.view_functions.get(rule.endpoint)+ contract = getattr(view_func, '__api_contract__', None)description = ''if view_func and view_func.__doc__:description = view_func.__doc__.strip()@@ -197,6 +242,18 @@ class OpenAPIService:},}+ if contract and contract.responses:+ operation['responses'].pop('200', None)+ for status, response_contract in contract.responses.items():+ operation['responses'][str(status)] = {+ 'description': response_contract.description,+ 'content': {+ 'application/json': {+ 'schema': schema_ref(response_contract.schema),+ },+ },+ }+# Add path parametersparams = re.findall(r'\{(\w+)\}', path)if params:@@ -209,8 +266,22 @@ class OpenAPIService:'schema': {'type': 'integer' if param.endswith('_id') or param == 'id' else 'string'},})+ if contract and contract.query:+ operation.setdefault('parameters', []).extend(+ query_parameters(contract.query)+ )+# Add request body for POST/PUT/PATCH- if method in ('post', 'put', 'patch'):+ if contract and contract.body:+ operation['requestBody'] = {+ 'required': True,+ 'content': {+ 'application/json': {+ 'schema': schema_ref(contract.body),+ },+ },+ }+ elif method in ('post', 'put', 'patch'):operation['requestBody'] = {'content': {'application/json': {diff --git a/backend/requirements.txt b/backend/requirements.txtindex 88c66ddd..196f95e1 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -83,10 +83,11 @@ tzlocal>=5.0# OpenAPI documentationapispec==6.4.0apispec-webframeworks==1.2.0+marshmallow==3.26.1# AI assistant (core primitive — powered by Prompture)# Multi-provider LLM orchestration: Conversation, ToolRegistry, ask_live streaming,# ProviderEnvironment, guardrails. Provider SDKs (openai/anthropic/...) are optional# extras installed per the configured provider; the base package is provider-agnostic.# Installed from the Prompture repo (pip install -e path/to/prompture) until published.-prompture>=1.4\ No newline at end of file+prompture>=1.4diff --git a/backend/tests/test_api_contracts.py b/backend/tests/test_api_contracts.pynew file mode 100644index 00000000..663e8105--- /dev/null+++ b/backend/tests/test_api_contracts.py@@ -0,0 +1,105 @@+"""Unit tests for the typed endpoint-contract and response-envelope boundary."""++import pytest+from flask import Flask+from marshmallow import fields++from app.api.contracts import ApiSchema, api_contract+from app.api.responses import data_response, list_response+from app.exceptions import ValidationError+from app.services.openapi_service import OpenAPIService+++class ExampleQuery(ApiSchema):+ limit = fields.Integer(required=True)+++class ExampleBody(ApiSchema):+ name = fields.String(required=True)+++class ExampleResponse(ApiSchema):+ data = fields.Nested(ExampleBody, required=True)+++def test_contract_loads_typed_query_and_json_body():+ app = Flask(__name__)++ @api_contract(query=ExampleQuery, body=ExampleBody)+ def endpoint(query, body):+ return query, body++ with app.test_request_context('/?limit=3', method='POST', json={'name': 'demo'}):+ query, body = endpoint()++ assert query == {'limit': 3}+ assert body == {'name': 'demo'}+++def test_contract_raises_shared_typed_validation_error():+ app = Flask(__name__)++ @api_contract(query=ExampleQuery)+ def endpoint(query):+ return query++ with app.test_request_context('/?limit=nope'):+ with pytest.raises(ValidationError) as raised:+ endpoint()++ assert raised.value.code == 'invalid_query'+ assert raised.value.details == {+ 'fields': {'limit': ['Not a valid integer.']},+ }+++def test_response_helpers_emit_one_canonical_shape():+ app = Flask(__name__)+ with app.app_context():+ response, status = data_response({'id': 1}, status=201, message='Created')+ assert status == 201+ assert response.get_json() == {+ 'data': {'id': 1},+ 'message': 'Created',+ }++ response, status = list_response(+ [{'id': 1}], total=4, meta={'skip': 0}, legacy_key='items',+ )+ assert status == 200+ assert response.get_json() == {+ 'data': [{'id': 1}],+ 'meta': {'skip': 0, 'total': 4},+ 'items': [{'id': 1}],+ }+++def test_openapi_uses_endpoint_contract_instead_of_generic_objects():+ app = Flask(__name__)++ @app.post('/api/v1/examples')+ @api_contract(+ query=ExampleQuery,+ body=ExampleBody,+ responses={201: ExampleResponse},+ )+ def endpoint(query, body):+ return {'data': body}, 201++ with app.app_context():+ spec = OpenAPIService.generate_spec()++ operation = spec['paths']['/examples']['post']+ assert operation['requestBody']['content']['application/json']['schema'] == {+ '$ref': '#/components/schemas/ExampleBody',+ }+ assert operation['responses']['201']['content']['application/json']['schema'] == {+ '$ref': '#/components/schemas/ExampleResponse',+ }+ assert operation['parameters'] == [{+ 'name': 'limit',+ 'in': 'query',+ 'required': True,+ 'schema': {'type': 'integer'},+ }]+ assert spec['components']['schemas']['ExampleBody']['required'] == ['name']diff --git a/backend/tests/test_search.py b/backend/tests/test_search.pyindex 58f5da1c..1343c887 100644--- a/backend/tests/test_search.py+++ b/backend/tests/test_search.py@@ -48,10 +48,12 @@ def personas(app):def test_shape(client, personas):- """Response has a results list and each row carries type/label/sublabel/path."""+ """Response has a canonical list envelope plus the compatibility field."""r = client.get('/api/v1/search?q=SecretProject', headers=personas.owner)assert r.status_code == 200body = r.get_json()+ assert body['data'] == body['results']+ assert body['meta']['total'] == len(body['data'])assert 'results' in body and isinstance(body['results'], list)assert len(body['results']) >= 1for row in body['results']:@@ -66,12 +68,28 @@ def test_min_length_returns_empty(client, personas):"""A term shorter than 2 chars returns an empty result set (200)."""r = client.get('/api/v1/search?q=a', headers=personas.owner)assert r.status_code == 200- assert r.get_json() == {'results': []}+ assert r.get_json() == {'data': [], 'meta': {'total': 0}, 'results': []}# Missing q behaves the same.r2 = client.get('/api/v1/search', headers=personas.owner)assert r2.status_code == 200- assert r2.get_json() == {'results': []}+ assert r2.get_json() == {'data': [], 'meta': {'total': 0}, 'results': []}+++def test_unknown_query_parameter_uses_typed_validation_error(client, personas):+ response = client.get(+ '/api/v1/search?q=valid&surprise=true',+ headers={**personas.owner, 'X-Request-ID': 'search-query-contract'},+ )++ assert response.status_code == 400+ assert response.get_json() == {+ 'error': 'Invalid query parameters',+ 'status': 400,+ 'code': 'invalid_query',+ 'details': {'fields': {'surprise': ['Unknown field.']}},+ 'request_id': 'search-query-contract',+ }def test_per_type_cap(client, personas):diff --git a/frontend/src/services/api/search.js b/frontend/src/services/api/search.jsindex d74a3def..5a1d6337 100644--- a/frontend/src/services/api/search.js+++ b/frontend/src/services/api/search.js@@ -1,4 +1,10 @@// Unified entity omnisearch (plan 41, Phase 4).export async function search(q) {- return this.request(`/search?q=${encodeURIComponent(q)}`);+ const response = await this.request(`/search?q=${encodeURIComponent(q)}`);+ return {+ ...response,+ // The backend keeps `results` during the public API migration. Prefer+ // the canonical envelope here so the browser exercises the new path.+ results: response?.data ?? response?.results ?? [],+ };}