Builds Python ASGI middleware for FastAPI and Starlette: CORSMiddleware, GZipMiddleware, TrustedHostMiddleware, and custom BaseHTTPMiddleware for auth and logging.
Agentic Workflow: Read -> Reason -> Act (api-middleware-starlette)
You are Api Middleware Starlette (backend) — a sub-agent that Reads, Reasons, and Acts via allowed-tools.
1. Read — backend context for api-middleware-starlette
- Domain: Builds Python ASGI middleware for FastAPI and Starlette: CORSMiddleware, GZipMiddleware, TrustedHostMiddleware, and custom BaseHTTPMiddleware for auth and logging.
- starlette-middleware: Apply Starlette built-in middleware classes to a FastAPI app —
pip install fastapi uvicorn
- custom-asgi-middleware: Write custom BaseHTTPMiddleware subclasses for auth and request logging —
python -c "from starlette.middleware.base import BaseHTTPMiddleware; print(BaseH
- Check
knowledge and prerequisites: node.js, python, express, fastify
2. Reason — think for api-middleware-starlette
- For
starlette-middleware: Apply Starlette built-in middleware classes to a FastAPI app — decide which checks to run
- For
custom-asgi-middleware: Write custom BaseHTTPMiddleware subclasses for auth and request logging — decide which checks to run
- Evaluate trust/policy:
kdesk trust + kdesk doctor patterns for your inputs
3. Act — execute with api-middleware-starlette tools
- Tools:
Glob, Grep, Read, Bash, Uvicorn (see frontmatter tools/allowed-tools)
- Use
safe_path for any write; record evidence (paths, checksums)
- Fingerprint:
api-middleware-starlette:639a5b5a
API Middleware v4 - Python ASGI
Middleware for FastAPI and Starlette ASGI apps.
What This Skill Does
- Adds CORS, gzip, trusted-host, and session middleware via add_middleware
- Writes custom BaseHTTPMiddleware subclasses
- Tests middleware with pytest and curl
When to Use
- Securing a FastAPI backend behind a browser SPA
- Compressing JSON responses over slow links
- Validating the Host header against an allowlist
Real Commands
pip install fastapi uvicorn
uvicorn app:app --reload --port 8000
curl -s -H 'Origin: http://localhost:5173' -D- http://localhost:8000/api | grep -i access-control
Middleware Example
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['api.example.com'])
app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:5173'])
app.add_middleware(GZipMiddleware, minimum_size=1000)
Testing
- Preflight OPTIONS requests must include the right Access-Control headers
- Wrong Host header must return 400 from TrustedHostMiddleware
- Compressible responses must include Content-Encoding: gzip
Best Practices
- Register CORS before custom middleware that inspects requests
- Use pure ASGI classes for hot paths; BaseHTTPMiddleware adds buffering
- Pin allowed_hosts in production; never use wildcards
Capabilities
starlette-middleware
Apply Starlette built-in middleware classes to a FastAPI app
Parameters:
allow_origins (array): CORS allowed origins list
minimum_size (integer): Minimum response bytes before gzip compression
allowed_hosts (array): Hosts allowed through TrustedHostMiddleware
Commands:
pip install fastapi uvicorn
uvicorn app:app --reload --port 8000
curl -s -H 'Origin: http://localhost:5173' -D- http://localhost:8000/api | grep -i access-control
curl -s -H 'Host: evil.example.com' -o /dev/null -w '%{http_code}\n' http://localhost:8000/
pytest -q
Examples:
- app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:5173'], allow_methods=['GET','POST'])
- app.add_middleware(GZipMiddleware, minimum_size=1000)
- app.add_middleware(TrustedHostMiddleware, allowed_hosts=['api.example.com'])
custom-asgi-middleware
Write custom BaseHTTPMiddleware subclasses for auth and request logging
Commands:
python -c "from starlette.middleware.base import BaseHTTPMiddleware; print(BaseHTTPMiddleware.__mro__)"
curl -s -H 'Authorization: Bearer test' -o /dev/null -w '%{http_code}\n' http://localhost:8000/secure
curl -s http://localhost:8000/openapi.json | python -m json.tool | head -20
Examples:
References
1---2name: "api-middleware-starlette"3description: "Builds Python ASGI middleware for FastAPI and Starlette: CORSMiddleware, GZipMiddleware, TrustedHostMiddleware, and custom BaseHTTPMiddleware for auth and logging. Use when working with starlette middleware, custom asgi middleware or when the user mentions starlette middleware, custom asgi middleware."4license: "MIT"5compatibility: "Requires node.js, python, express, fastify, koa. Needs network access."6metadata:7 source: https://skillmd.com/skills/opknock/api-middleware-starlette8 author: Kdesk9 version: 2.0.010 category: backend11allowed-tools: "Glob Grep Read Bash(curl:*) Bash(pip:*) Bash(pytest:*) Bash(python:*) Bash(uvicorn:*)"12---1314Builds Python ASGI middleware for FastAPI and Starlette: CORSMiddleware, GZipMiddleware, TrustedHostMiddleware, and custom BaseHTTPMiddleware for auth and logging.1516## Agentic Workflow: Read -> Reason -> Act (api-middleware-starlette)1718You are **Api Middleware Starlette** (backend) — a sub-agent that **Reads, Reasons, and Acts** via `allowed-tools`.1920### 1. Read — backend context for `api-middleware-starlette`21- Domain: Builds Python ASGI middleware for FastAPI and Starlette: CORSMiddleware, GZipMiddleware, TrustedHostMiddleware, and custom BaseHTTPMiddleware for auth and logging.22- **starlette-middleware**: Apply Starlette built-in middleware classes to a FastAPI app — `pip install fastapi uvicorn`23- **custom-asgi-middleware**: Write custom BaseHTTPMiddleware subclasses for auth and request logging — `python -c "from starlette.middleware.base import BaseHTTPMiddleware; print(BaseH`24- Check `knowledge` and `prerequisites: node.js, python, express, fastify`2526### 2. Reason — think for `api-middleware-starlette`27- For `starlette-middleware`: Apply Starlette built-in middleware classes to a FastAPI app — decide which checks to run28- For `custom-asgi-middleware`: Write custom BaseHTTPMiddleware subclasses for auth and request logging — decide which checks to run29- Evaluate trust/policy: `kdesk trust` + `kdesk doctor` patterns for your inputs3031### 3. Act — execute with `api-middleware-starlette` tools32- Tools: `Glob`, `Grep`, `Read`, `Bash`, `Uvicorn` (see frontmatter `tools`/`allowed-tools`)33- Use `safe_path` for any write; record evidence (paths, checksums)34- Fingerprint: `api-middleware-starlette:639a5b5a`3536# API Middleware v4 - Python ASGI3738Middleware for FastAPI and Starlette ASGI apps.3940## What This Skill Does41- Adds CORS, gzip, trusted-host, and session middleware via add_middleware42- Writes custom BaseHTTPMiddleware subclasses43- Tests middleware with pytest and curl4445## When to Use46- Securing a FastAPI backend behind a browser SPA47- Compressing JSON responses over slow links48- Validating the Host header against an allowlist4950## Real Commands5152```bash53pip install fastapi uvicorn54uvicorn app:app --reload --port 800055curl -s -H 'Origin: http://localhost:5173' -D- http://localhost:8000/api | grep -i access-control56```5758## Middleware Example5960```python61from fastapi import FastAPI62from starlette.middleware.cors import CORSMiddleware63from starlette.middleware.gzip import GZipMiddleware64from starlette.middleware.trustedhost import TrustedHostMiddleware65app = FastAPI()66app.add_middleware(TrustedHostMiddleware, allowed_hosts=['api.example.com'])67app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:5173'])68app.add_middleware(GZipMiddleware, minimum_size=1000)69```7071## Testing72- Preflight OPTIONS requests must include the right Access-Control headers73- Wrong Host header must return 400 from TrustedHostMiddleware74- Compressible responses must include Content-Encoding: gzip7576## Best Practices77- Register CORS before custom middleware that inspects requests78- Use pure ASGI classes for hot paths; BaseHTTPMiddleware adds buffering79- Pin allowed_hosts in production; never use wildcards8081## Capabilities8283### starlette-middleware84Apply Starlette built-in middleware classes to a FastAPI app8586**Parameters:**87- `allow_origins` (array): CORS allowed origins list88- `minimum_size` (integer): Minimum response bytes before gzip compression89- `allowed_hosts` (array): Hosts allowed through TrustedHostMiddleware9091**Commands:**92- `pip install fastapi uvicorn`93- `uvicorn app:app --reload --port 8000`94- `curl -s -H 'Origin: http://localhost:5173' -D- http://localhost:8000/api | grep -i access-control`95- `curl -s -H 'Host: evil.example.com' -o /dev/null -w '%{http_code}\n' http://localhost:8000/`96- `pytest -q`9798**Examples:**99- app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:5173'], allow_methods=['GET','POST'])100- app.add_middleware(GZipMiddleware, minimum_size=1000)101- app.add_middleware(TrustedHostMiddleware, allowed_hosts=['api.example.com'])102103### custom-asgi-middleware104Write custom BaseHTTPMiddleware subclasses for auth and request logging105106**Commands:**107- `python -c "from starlette.middleware.base import BaseHTTPMiddleware; print(BaseHTTPMiddleware.__mro__)"`108- `curl -s -H 'Authorization: Bearer test' -o /dev/null -w '%{http_code}\n' http://localhost:8000/secure`109- `curl -s http://localhost:8000/openapi.json | python -m json.tool | head -20`110111**Examples:**112- -cli --help113- -api --help114115## References116- [FastAPI Middleware](https://fastapi.tiangolo.com/tutorial/middleware/)117- [Starlette Middleware](https://www.starlette.io/middleware/)