A proof of concept API to explore best-practices and new ideas (Python) - mainly executed via AI conversations.
This repository now includes a production-oriented FastAPI implementation generated from the OpenAPI contract in shared/PilotSharedSource/OpenAPI/PilotApi_v1.yaml.
- Python 3.12+
- FastAPI
- Pydantic v2
- SQLAlchemy 2.0
- Alembic
- SQL Server driver via
mssql+pyodbc - OpenTelemetry (traces, metrics, logs) exported via OTLP
- pytest + FastAPI TestClient
src/pilot_api/config: typed settings, DB engine, logging setupsrc/pilot_api/api: route registration and HTTP handlerssrc/pilot_api/dto: OpenAPI-aligned request and response DTOssrc/pilot_api/mapper: DTO <-> entity mappingsrc/pilot_api/service: business and transaction flowssrc/pilot_api/repository: persistence abstractionssrc/pilot_api/model: SQLAlchemy entities and domain objectssrc/pilot_api/exception: custom errors and global exception handlerssrc/pilot_api/validation: header and request validation helperssrc/pilot_api/security: JWT authentication, role-based authorization, and theSecurityHelperthat centralizes bothalembic: migration configuration and initial schematests: API and service-layer tests
The API exposes the Northwind tables described by the OpenAPI definition (shared/PilotSharedSource/OpenAPI/PilotApi_v1.yaml):
CategoriesCustomersEmployeesOrder DetailsOrdersProductsShippersSuppliers
The remaining Northwind tables (CustomerCustomerDemo, CustomerDemographics, EmployeeTerritories, Region, Territories) are mapped as SQLAlchemy entities for the schema migration only; they have no endpoints.
To avoid unintended schema changes, the application does not execute automatic DDL on startup.
RequestSettings (src/pilot_api/config/request_settings.py) holds the per-request values request_id, correlation_id, and caller_name. RequestContextMiddleware creates one at the start of every request:
correlation_idis read from theX-Correlation-Idrequest header; when the header is missing or blank, a new GUID is generated.request_idis a new GUID assigned by the server to the request; any inboundX-Request-Idheader is ignored.caller_nameis read from the optionalX-Caller-Namerequest header (e.g.PilotAngularUi); when the header is missing or blank it isNoneand logged as-.
Every operation, including /healthcheck and /about, accepts the optional X-Api-Version (max 15 characters), X-Caller-Name (max 100), and X-Correlation-Id (max 40) headers, as declared in the shared OpenAPI definition. A header longer than its maximum is rejected with a 400 ProblemDetails.
The object is available for the life of the request: inject it into an endpoint with RequestSettingsDep (pilot_api.api.dependencies), or call get_current_request_settings() from code without access to the request. Every log line carries the request id, correlation id, and caller name, and every response (including unhandled 500 errors) returns the ids as the X-Correlation-Id and X-Request-Id headers. The caller name is not echoed back.
Log lines are written to the console (JSON when LOG_JSON=true) and, when OpenTelemetry is enabled, exported via OTLP. RequestContextFilter stamps each line with request_id, correlation_id, caller_name, and operation_id, so callers never need to pass them explicitly.
In addition to application messages, the following are always logged at INFO:
- Endpoint start and end (
RequestContextMiddleware):Endpoint started: GET /v1/categories/get-allandEndpoint completed: GET /v1/categories/get-all -> 200 (12.3 ms). Requests rejected before reaching the endpoint (validation, security) are bracketed too. An unhandled exception is logged asEndpoint failed: ...atERROR, followed by the unhandled-error handler's entry with the traceback. - Database call start and end (SQLAlchemy engine events in
src/pilot_api/config/database.py):Database call started: <statement>andDatabase call completed: <statement> (1.2 ms), orDatabase call failed: <statement> (1.2 ms) <ExceptionType>atERROR. Statements are whitespace-collapsed and truncated to 200 characters; they contain only bind placeholders, never parameter values.
-
Create and activate a Python environment.
-
Install dependencies:
python -m pip install -e .[dev]- Create your environment file:
copy .env.example .env- Update
.envwith database attributes:
- SQL Server
APP_NAME=PilotApiPython
APP_VERSION=1.1.2
LOG_LEVEL=INFO
LOG_JSON=true
DB_NAME=NorthWind
DB_CONNECT_TIMEOUT=30
DB_HOST=localhost
DB_PASSWORD=<DevUser password>
DB_PORT=1433
DB_SCHEMA=dbo
DB_USER=DevUser
DB_DRIVER=ODBC Driver 18 for SQL Server
DB_TRUST_SERVER_CERTIFICATE=true
# Optional full override:
# DATABASE_URL=mssql+pyodbc://DevUser:<DevUser password>@localhost:1433/NorthWind?driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes&timeout=30
SECURITY_ACTIVE=true
IDENTITY_PROVIDER_BASE_URL=http://localhost:11141
IDENTITY_PROVIDER_REALM=local-realm
IDENTITY_PROVIDER_CLIENT_ID=local-client
IDENTITY_PROVIDER_AUDIENCE=- PostgreSQL
APP_NAME=PilotApiPython
APP_VERSION=1.1.2
LOG_LEVEL=INFO
LOG_JSON=true
DB_BACKEND=postgresql
DB_NAME=northwind
DB_CONNECT_TIMEOUT=30
DB_HOST=localhost
DB_PASSWORD=<DevUser password>
DB_PORT=5432
DB_SCHEMA=pilot
DB_USER=DevUser
DB_TRUST_SERVER_CERTIFICATE=true
# Optional full override:
# DATABASE_URL=postgresql+psycopg://DevUser:<DevUser password>@localhost:5432/northwind?connect_timeout=30&options=-csearch_path%3Dpilot
SECURITY_ACTIVE=true
IDENTITY_PROVIDER_BASE_URL=http://localhost:11141
IDENTITY_PROVIDER_REALM=local-realm
IDENTITY_PROVIDER_CLIENT_ID=local-client
IDENTITY_PROVIDER_AUDIENCE=- Environment Variable Overrides
Use DB_HOST=local_mssql only when the API process runs inside the same Docker network where that service name exists.
You can also set DATABASE_URL directly to override attribute-based construction.
DB_PASSWORD and DATABASE_URL have no defaults; the application refuses to start unless at least one of them is set. DB_TRUST_SERVER_CERTIFICATE defaults to false — set it to true only for local development against a self-signed certificate (as in the local Docker setup above). Contact details reported by /about (APP_CONTACT_NAME, APP_CONTACT_EMAIL, APP_CONTACT_URL) are omitted unless set. The OpenAPI document's info block is fixed to match the shared definition (see src/pilot_api/api/openapi.py) and does not change with the APP_* settings.
The build/deploy pipeline can supply APP_BUILD_VERSION and APP_DEPLOY_DATE for /about; when unset, buildVersion falls back to APP_VERSION and deployDate to the process start time.
The application listens on port 8000 by default, but this can be overrriden.
The database backend can also be switched with DB_BACKEND:
DB_BACKEND=sqlserveruses the existing SQL Server connection settings.DB_BACKEND=postgresqluses the PostgreSQL connection profile with:- database name:
northwind - host:
localhost - port:
5432 - schema:
pilot - user:
DevUser
- database name:
Example:
$env:DB_BACKEND = "postgresql"Start the FastAPI application with your preferred ASGI server. For example, if you still have Uvicorn installed locally, you can run:
python -m uvicorn pilot_api.main:app --reload --app-dir srcIf you are using a different ASGI host, launch the app through that runtime instead.
The above will use port 8000 by default.
If you would like to specify the host name and port, use the following:
python -m uvicorn pilot_api.main:app --reload --app-dir src --port 53060 --host localhostAPI docs:
- Swagger UI:
http://localhost:53060/docs - ReDoc:
http://localhost:53060/redoc
Create a migration:
python -m alembic revision --autogenerate -m "message"Apply migrations:
python -m alembic upgrade headAll /v1/... domain endpoints require a bearer JWT, validated against a self-hosted OAuth2/OIDC identity provider (issuer + JWKS resolved from IDENTITY_PROVIDER_* settings). The System endpoints (/healthcheck, /about) are not protected.
This is reflected in the generated OpenAPI schema: protected endpoints declare a Bearer requirement, which Swagger UI (/docs) shows as a lock icon per operation, with an Authorize button to set a bearer token for "Try it out" requests; ReDoc (/redoc) shows the same requirement in each operation's details.
Authorization is role-based. The token's subject is looked up in a mock UserRoles table to resolve one of three roles, each permitting a tier of HTTP methods:
| Role | Methods allowed |
|---|---|
read_only_role |
GET, HEAD, OPTIONS, QUERY, TRACE |
read_write_role |
the above, plus PATCH, POST, PUT |
admin_role |
the above, plus DELETE |
Mock users (for local testing): reader_user, working_user, working_admin_user.
SECURITY_ACTIVE controls what happens when authentication or authorization fails:
true(default): the request is rejected (401if the token is missing/invalid,403if the role is insufficient).false: the request still proceeds, but the response carries aWarningheader describing why authentication/authorization did not succeed.
Example: obtain a token from the local dev identity provider, then call a protected endpoint:
curl -X POST "http://localhost:11141/realms/local-realm/protocol/openid-connect/token" \
-d "grant_type=password&client_id=local-client&username=working_user&password=<password>"
curl "http://localhost:53060/v1/categories/get-all" \
-H "Authorization: Bearer <access_token>"The application can export traces, metrics, and logs via OpenTelemetry (OTLP) to a local collector, from which they flow into an LGTM stack (Tempo/Loki/Mimir/Grafana) for viewing.
Controlled by these .env settings:
OTEL_ENABLED=true
OTEL_SERVICE_NAME=PilotApiPython
# "grpc" (port 4317, default) or "http" (port 4318).
OTEL_EXPORTER_OTLP_PROTOCOL=grpc
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
OTEL_ENVIRONMENT=local-devWhen OTEL_ENABLED=false, none of the OTEL SDKs or instrumentation are activated.
- Traces: every HTTP request (via
FastAPIInstrumentor) and every SQLAlchemy query (viaSQLAlchemyInstrumentor), as child spans of the request span. - Metrics: FastAPI/ASGI request duration and count, plus standard OTEL SDK metrics, exported every 60s.
- Logs: every Python
loggingcall is exported via OTLP in addition to the existing console output. Each log record also carriesotelTraceID/otelSpanID(and, natively for OTLP consumers,trace_id/span_id) so a log line can be traced back to the request that produced it. The current request'sRequestSettingsids (see Request Settings) are recorded ascorrelationId/request.Idattributes on the request span and every child span, and asCorrelationId/Request.Idattributes on every OTLP log record emitted during the request. When the caller suppliesX-Caller-Name, it is recorded likewise ascallerName(spans) andCallerName(log records). For logged exceptions, the OTLP handler's standardexception.type/exception.message/exception.stacktraceattributes are supplemented withException.Message(only when the exception has a message but noargs, soexception.messageis absent) andException.InnerException(the formatted__cause__, or__context__when not suppressed).
The collector, plus Tempo (traces), Mimir (metrics), Loki (logs), and Grafana, are started separately via:
C:\Working\Storage\Dev\GitHub\Docker\Otel\Docker-Otel-builder.batThis exposes the OTEL collector on localhost:4317 (OTLP gRPC) and localhost:4318 (OTLP HTTP), and Grafana on http://localhost:3000.
Every signal is tagged with service.name = PilotApiPython (from OTEL_SERVICE_NAME) and deployment.environment = local-dev (from OTEL_ENVIRONMENT). Useful starting queries in Grafana Explore:
| Data source | Query | Notes |
|---|---|---|
| Loki (logs) | {service_name="PilotApiPython"} |
Filter further, e.g. {service_name="PilotApiPython"} |= "error" |
| Loki (logs for one trace) | {service_name="PilotApiPython"} | trace_id="<trace id>" |
Correlate a specific trace's logs; trace_id is populated natively via OTLP |
| Tempo (traces, TraceQL) | {resource.service.name="PilotApiPython"} |
Or pick PilotApiPython from the Service Name dropdown in the Tempo search UI |
| Mimir (metrics, PromQL) | {job="PilotApiPython"} |
job mirrors the OTEL service.name; e.g. http_server_request_duration_seconds_count{job="PilotApiPython"} |
From a trace in Tempo, use the Logs tab on a span (wired up via the tracesToLogsV2 datasource setting) to jump straight to the matching Loki log lines for that trace.
python -m pytestThe test suite uses an isolated in-memory SQLite database with dependency overrides for fast local verification.
This repository includes the shared codebase as a Git submodule at:
shared/PilotSharedSource
Source:
https://github.com/MikeLooper/PilotSharedSource
For a first-time clone, include submodules so shared/PilotSharedSource is ready immediately:
git clone --recurse-submodules <this-repo-url>If you already cloned without submodules, initialize and fetch them:
git submodule update --init --recursiveWhen changes are made in PilotSharedSource, pull the latest tracked branch for this submodule:
git submodule update --remote --merge shared/PilotSharedSourceThen commit the updated submodule pointer in this repository:
git add shared/PilotSharedSource .gitmodules
git commit -m "Update shared submodule"To automatically run this application and launch the API UI, create a .vscode\launch.json file with the following contents:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Pilot API",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"pilot_api.main:app",
"--host",
"0.0.0.0",
"--port",
"53060"
],
"cwd": "${workspaceFolder}",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"serverReadyAction": {
"action": "openExternally",
"pattern": "Uvicorn running on http://\\S+:(\\d+)",
"uriFormat": "http://localhost:%s/docs"
},
"console": "integratedTerminal",
"justMyCode": true
}
]
}