Skip to content

About

A proof of concept API to explore best-practices and new ideas (Python). Primarily built using AI directives.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

PilotApiPython

A proof of concept API to explore best-practices and new ideas (Python) - mainly executed via AI conversations.

Generated Python API

This repository now includes a production-oriented FastAPI implementation generated from the OpenAPI contract in shared/PilotSharedSource/OpenAPI/PilotApi_v1.yaml.

Stack

  • 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

Project Structure

  • src/pilot_api/config: typed settings, DB engine, logging setup
  • src/pilot_api/api: route registration and HTTP handlers
  • src/pilot_api/dto: OpenAPI-aligned request and response DTOs
  • src/pilot_api/mapper: DTO <-> entity mapping
  • src/pilot_api/service: business and transaction flows
  • src/pilot_api/repository: persistence abstractions
  • src/pilot_api/model: SQLAlchemy entities and domain objects
  • src/pilot_api/exception: custom errors and global exception handlers
  • src/pilot_api/validation: header and request validation helpers
  • src/pilot_api/security: JWT authentication, role-based authorization, and the SecurityHelper that centralizes both
  • alembic: migration configuration and initial schema
  • tests: API and service-layer tests

Northwind Coverage

The API exposes the Northwind tables described by the OpenAPI definition (shared/PilotSharedSource/OpenAPI/PilotApi_v1.yaml):

  • Categories
  • Customers
  • Employees
  • Order Details
  • Orders
  • Products
  • Shippers
  • Suppliers

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.

Request Settings

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_id is read from the X-Correlation-Id request header; when the header is missing or blank, a new GUID is generated.
  • request_id is a new GUID assigned by the server to the request; any inbound X-Request-Id header is ignored.
  • caller_name is read from the optional X-Caller-Name request header (e.g. PilotAngularUi); when the header is missing or blank it is None and 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.

Logging

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-all and Endpoint 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 as Endpoint failed: ... at ERROR, 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> and Database call completed: <statement> (1.2 ms), or Database call failed: <statement> (1.2 ms) <ExceptionType> at ERROR. Statements are whitespace-collapsed and truncated to 200 characters; they contain only bind placeholders, never parameter values.

Setup

  1. Create and activate a Python environment.

  2. Install dependencies:

python -m pip install -e .[dev]
  1. Create your environment file:
copy .env.example .env
  1. Update .env with 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=
  1. 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=sqlserver uses the existing SQL Server connection settings.
  • DB_BACKEND=postgresql uses the PostgreSQL connection profile with:
    • database name: northwind
    • host: localhost
    • port: 5432
    • schema: pilot
    • user: DevUser

Example:

$env:DB_BACKEND = "postgresql"

Run

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 src

If 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 localhost

API docs:

  • Swagger UI: http://localhost:53060/docs
  • ReDoc: http://localhost:53060/redoc

Migrations

Create a migration:

python -m alembic revision --autogenerate -m "message"

Apply migrations:

python -m alembic upgrade head

Security

All /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 (401 if the token is missing/invalid, 403 if the role is insufficient).
  • false: the request still proceeds, but the response carries a Warning header 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>"

Observability (OpenTelemetry)

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-dev

When OTEL_ENABLED=false, none of the OTEL SDKs or instrumentation are activated.

What gets instrumented

  • Traces: every HTTP request (via FastAPIInstrumentor) and every SQLAlchemy query (via SQLAlchemyInstrumentor), 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 logging call is exported via OTLP in addition to the existing console output. Each log record also carries otelTraceID/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's RequestSettings ids (see Request Settings) are recorded as correlationId/request.Id attributes on the request span and every child span, and as CorrelationId/Request.Id attributes on every OTLP log record emitted during the request. When the caller supplies X-Caller-Name, it is recorded likewise as callerName (spans) and CallerName (log records). For logged exceptions, the OTLP handler's standard exception.type/exception.message/exception.stacktrace attributes are supplemented with Exception.Message (only when the exception has a message but no args, so exception.message is absent) and Exception.InnerException (the formatted __cause__, or __context__ when not suppressed).

Running the local OTEL collector

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

This exposes the OTEL collector on localhost:4317 (OTLP gRPC) and localhost:4318 (OTLP HTTP), and Grafana on http://localhost:3000.

Finding this service's data in Grafana

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.

Test

python -m pytest

The test suite uses an isolated in-memory SQLite database with dependency overrides for fast local verification.

Shared SubModule

This repository includes the shared codebase as a Git submodule at:

  • shared/PilotSharedSource

Source:

  • https://github.com/MikeLooper/PilotSharedSource

Clone With SubModules

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 --recursive

Update The Shared SubModule

When changes are made in PilotSharedSource, pull the latest tracked branch for this submodule:

git submodule update --remote --merge shared/PilotSharedSource

Then commit the updated submodule pointer in this repository:

git add shared/PilotSharedSource .gitmodules
git commit -m "Update shared submodule"

Development

VS Code

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
        }
    ]
}

About

A proof of concept API to explore best-practices and new ideas (Python). Primarily built using AI directives.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages