en

Python FastAPI Application as Tor Hidden Service

FastAPI is Python's fastest-growing web framework, combining async support, automatic OpenAPI documentation, and Pydantic data validation in a single package. Deploying FastAPI behind a Tor hidden service gives Python developers access to anonymous API hosting with the developer experience advantages of automatic documentation generation, request validation, and modern async Python. This guide covers the complete FastAPI .onion deployment workflow, from ASGI server configuration through operational security.

Need this done for your project?

We implement, you ship. Async, documented, done in days.

Start a Brief

Uvicorn and Gunicorn Configuration for Onion Hosting

FastAPI requires an ASGI server. Uvicorn is the standard choice, optionally managed by Gunicorn as a process manager. For single-server deployment: uvicorn main:app --host 127.0.0.1 --port 8000 --workers 4. The --host 127.0.0.1 flag restricts binding to localhost. For production, use Gunicorn with Uvicorn workers: gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 127.0.0.1:8000. This provides Gunicorn's process management (worker restart on crash) with Uvicorn's async performance. Configure as a systemd service with Restart=always and RestartSec=3. The Tor hidden service maps port 80 to 127.0.0.1:8000. Add nginx as an optional intermediary for static file serving and HTTP header manipulation. The number of workers should be 2 * CPU_cores + 1 for I/O-bound applications (typical for web APIs).

FastAPI Router Structure for .onion Services

Organize the FastAPI application with APIRouter for separation of concerns. Create routers for different API sections (auth, users, content, admin) and include them in the main app. For .onion services, add a health check endpoint at /health that returns system status (uptime, version, database connectivity) - useful for monitoring via local cron scripts. The FastAPI automatic OpenAPI documentation (/docs and /redoc endpoints) is extremely useful during development but should be disabled in production .onion services to prevent schema exposure: app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None). CORS configuration: for a .onion API consumed by a .onion frontend, configure CORSMiddleware with allow_origins=[http://youronion.onion'] to restrict cross-origin access. For APIs intended to be called by any Tor Browser client, allow_origins=['*'] is acceptable since .onion services are inherently local to Tor network.

Pydantic Models and Input Validation Security

FastAPI's Pydantic integration provides automatic request body validation. Define strict Pydantic models for all API inputs with appropriate field validators. Use constr (constrained string) types to limit string lengths and patterns: from pydantic import constr; username: constr(min_length=3, max_length=50, regex='^[a-zA-Z0-9_]+$'). Validate email addresses using EmailStr from pydantic[email]. For numeric fields, use constrained types: from pydantic import confloat, conint; price: confloat(gt=0, le=10000). These validators reject malformed input before application code processes it, preventing injection attacks and unexpected data shapes. Custom validators using @validator decorator for complex business logic validation. Pydantic V2 (used in FastAPI 0.100+) uses @field_validator with different syntax - ensure validator syntax matches the Pydantic version installed. ValidationError responses automatically return 422 Unprocessable Entity with detailed field-level error messages - review these messages to ensure they do not expose server-side implementation details.

Background Tasks and Async Patterns for .onion APIs

FastAPI's BackgroundTasks enable async processing without blocking HTTP responses. Use for: sending notifications after requests, updating caches, or processing uploaded files. Example: async def process_upload(file: UploadFile, background_tasks: BackgroundTasks): ... background_tasks.add_task(analyze_file, file). For heavier background processing, use Celery with Redis as a broker (both Redis and Celery workers run locally, bound to localhost). The task queue itself is not exposed externally. Async database operations: use async SQLAlchemy (sqlalchemy.ext.asyncio) or async database drivers (databases library for PostgreSQL). Async file I/O: use aiofiles instead of Python's built-in open() to avoid blocking the event loop. For periodic background tasks within FastAPI: use the APScheduler library or define async startup events with asyncio.create_task for continuous background loops. These background tasks handle maintenance operations (log rotation, session cleanup, cache warming) without external cron dependency.

Dependency Injection for Authentication in .onion FastAPI

FastAPI's dependency injection system is the recommended way to implement authentication. Define a security scheme and create a dependency that validates tokens or sessions. For JWT authentication: from fastapi.security import HTTPBearer; security = HTTPBearer(); async def get_current_user(token: str = Depends(security)): ... - validate the token and return the user object. Inject this dependency into protected endpoints: @app.get('/protected'); async def protected(user: User = Depends(get_current_user)). For session-based authentication: use itsdangerous for signed session cookies with the SECRET_KEY stored as an environment variable. Rate limit dependencies: create a dependency that checks request rate using an in-memory store (for single-instance) or Redis (for multi-worker). Inject into sensitive endpoints: @app.post('/login', dependencies=[Depends(rate_limit)]). Dependency injection makes authentication consistent across all endpoints and easy to test (inject mock dependencies in tests).

Why Anubiz Host

100% async — no calls, no meetings
Delivered in days, not weeks
Full documentation included
Production-grade from day one
Security-first approach
Post-delivery support included

Ready to get started?

Skip the research. Tell us what you need, and we'll scope it, implement it, and hand it back — fully documented and production-ready.

Anubiz Chat AI

Online