A GET-Only Door for External Data
A read-only API gateway for external data: env-JSON allowlist, Redis cache, static error bodies, and 20 offline tests behind one GET-only door.
TL;DR
Rather than expose upstream API credentials in the browser, the author built a small FastAPI read-only gateway for KotaPortal's feeds. It allows GET only via per-source allowlists, caches JSON in Redis with clamped TTLs, and hides upstream errors. All 20 tests run offline; the one gap is a missing Allow header on 405 responses.
The weather and event feeds on KotaPortal's public pages come from an external API. My first guess was to call that API straight from the frontend. It died at the token question: the browser would have to hold the upstream credential, and whatever a page can read, anyone with devtools can read. The door had to stay shut to writes as well; a proxy that forwards POST hands every caller the upstream's full power.
So I built a read-door instead: GET only, an allowlist per source, a cache in front, and error bodies that reveal nothing. In practice it is a small read-only API gateway, one FastAPI service of 546 lines including a 223-line test file with 20 offline tests.
The read-door contract
Everything the gateway knows fits in one environment variable. GATEWAY_SOURCES is a JSON object: each source names a base_url, a list of prefixes where a trailing star is a wildcard, a ttl clamped between 60 and 3600 seconds with 300 as the default, and an optional auth block naming the header and the environment variable that holds the credential. The credential value itself is only ever read server-side. A source whose auth environment variable is empty gets disabled with a warning instead of failing the whole process.
# gateway/config.py
def load_sources(raw: str) -> dict:
out = {}
for name, spec in json.loads(raw).items():
ttl = min(max(int(spec.get("ttl", 300)), 60), 3600)
out[name] = {
"base_url": spec["base_url"],
"prefixes": spec.get("prefixes", []),
"ttl": ttl,
"auth_env": spec.get("auth", {}).get("env"),
}
return out
About twenty lines of PHP close the same question from another codebase, the trailing-* rule without a regex engine.
<?php
// src/Allowlist.php
final class Allowlist
{
// Exact path or prefix rules; "cuaca*" allows every /cuaca/* path.
private array $rules = [
'/cuaca/jakarta',
'/cuaca*',
'/acara*',
];
public function allows(string $path): bool
{
foreach ($this->rules as $rule) {
if (str_ends_with($rule, '*')) {
if (str_starts_with($path, rtrim($rule, '*'))) {
return true;
}
} elseif ($path === $rule || str_starts_with($path, $rule . '/')) {
return true;
}
}
return false;
}
}
There is no passthrough mode. A request arrives as /gw/{source}/{path}; the source must exist and the path must pass its allowlist before any network call happens. Exact rules match a path or its children; trailing-* rules are plain prefix matches. The gateway answers GET and nothing else. POST, PUT, PATCH, DELETE, and OPTIONS land on a 405 with static Indonesian JSON bodies. RFC 9110 defines 405 as a known method that the target resource does not support [6].
Cache keys are built as gw:{source}:/{path}?{sorted-query}, so parameter order never duplicates entries. Only 200 responses with JSON bodies under 2 MB are cached; every response carries X-Cache HIT or MISS plus X-Cache-TTL. Redis failures degrade to misses, so reads survive a cache outage.
Redis itself runs cache-only: persistence flags off, a 64 megabyte memory ceiling, and the allkeys-lru eviction policy. That is safe because every entry is a disposable copy of upstream data [5]. Upstream calls go through httpx with a 5 second connect timeout and a 10 second read timeout [2]. Client cookie and authorization headers are never forwarded, redirects are off, and non-200, non-JSON, or oversized responses become upstream errors. Because the error bodies are static, nothing from the upstream is reflected back to callers.
Offline verification and one honest gap
fakeredis is an in-memory drop-in replacement for redis-py [4], and httpx accepts a custom transport, so the test client calls the app directly through ASGITransport while MockTransport fakes the upstream services [3]. All 20 tests run offline. Two of them pin the failure modes I care about: a stopped Redis and an oversized upstream body. Nothing in the suite touches the network.
The MISS-then-HIT path is proven through response headers rather than by peeking into the cache. POST probes stay 405. Above 60 requests per minute per source, the sliding window answers 429; the counter is per source, so one noisy path cannot lock out the other feed. With Redis stopped, every read still works as a miss.
One honest gap came out of cross-checking the code against RFC 9110: the 405 handler omits the Allow header, which the RFC marks as a MUST [6][1]. The fix is one line: Allow: GET, HEAD. Until that line lands, the gateway answers 405 correctly but incompletely.
Sources
[1] MDN Allow header, developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Allow
[2] HTTPX Timeouts, www.python-httpx.org/advanced/timeouts
[3] HTTPX Transports, www.python-httpx.org/advanced/transports
[4] fakeredis PyPI, pypi.org/project/fakeredis
[5] Redis key eviction, redis.io/docs/latest/develop/reference/eviction
[6] RFC 9110 HTTP Semantics, www.rfc-editor.org/rfc/rfc9110.txt