modal-web-serving
Skill4 starsChanged 3 months agoApache-2.0View on GitHub
Expose Modal Functions as HTTP endpoints using FastAPI, ASGI, WSGI, or raw HTTP. Use when building APIs, web apps, streaming endpoints, or serving ML models over HTTP with custom domains and authentication. For low-latency long-lived servers see modal-servers; for managed LLM APIs see modal-endpoints.
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 6 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Use this skill when exposing Modal Functions as web endpoints, building APIs, or serving web applications.
- Very specific: line 63
Prefer managed recipes over custom @app.server / Function code
- Very specific: line 141
Use FastAPI's StreamingResponse for SSE or chunked responses:
- Distinctive: line 207
Use streaming to keep the connection alive
- Distinctive: line 221
Ensure FastAPI is installed in the image
- Distinctive: line 222
Verify Pydantic models match request schema
- Very specific: line 229
Use media_type="text/event-stream" for SSE
- Distinctive: line 233
Default web timeout is 150s.
- Very specific: line 238
Use modal curl or set Modal-Key / Modal-Secret.
- Very specific: line 252
Use modal serve for development (live-reload), modal deploy for production
- Distinctive: line 256
Do not conflate Function web URLs (often public) with Server/Endpoint auth (proxy tokens by default)
- Very specific: line 257
Prefer @app.server over new @modal.web_server for latency-sensitive port serving (modal-servers)
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Modal Web Serving
Use this skill when exposing Modal Functions as web endpoints, building APIs, or serving web applications.
For Servers (@app.server / modal.Server) — long-lived port-based HTTP with regional routing and default proxy-token auth — see modal-servers. For managed OpenAI-compatible LLM APIs, see modal-endpoints.
When to Use This Skill
- Creating REST/HTTP APIs from Modal Functions
- Serving ML model inference over HTTP
- Building web apps with FastAPI, Django, or Flask on Modal
- Setting up streaming (SSE) endpoints
- Configuring custom domains
- Adding authentication to web endpoints
Quick Start
image = modal.Image.debian_slim().pip_install("fastapi[standard]")
@app.function(image=image)
@modal.fastapi_endpoint()
def hello():
return "Hello world!"Deploy with modal serve (dev) or modal deploy (production).
Function Web Endpoints vs Servers vs Auto Endpoints
Modal has three related HTTP surfaces. Prefer Function web decorators for request/response APIs that fit the Function input model; migrate or start on Servers when latency and in-process concurrency matter; use Auto Endpoints for catalog/custom LLM inference without writing server code.
| Concern | Function web (fastapi_endpoint / asgi / wsgi / web_server) | @app.server (modal-servers) | Auto Endpoints (modal-endpoints) |
| Model | Function inputs / ASGI–WSGI bridge / port via web_server | Reverse proxy → long-lived process on a port | Managed OpenAI-compatible LLM API |
| Cold zero→one | Inputs queue while cold-starting | First requests may 503 until ready | Same Server cold-start behavior |
| Auth default | Often public URL; opt into requires_proxy_auth=True | Proxy tokens required unless unauthenticated=True | Proxy tokens required unless --unauthenticated |
| Best for | Typed APIs, FastAPI/Django/Flask apps, simple inference HTTP | vLLM/SGLang, sticky sessions, low-latency regional HTTP | One-command catalog / custom-weight LLM endpoints |
| Define in | Python Function decorators | @app.server class + @modal.enter | modal endpoint CLI (no app code) |
When to keep Function web endpoints
- Small FastAPI/ASGI/WSGI handlers with typed inputs and Modal’s input queue
- Existing middleware stacks already on
@modal.asgi_app/@modal.wsgi_app - Need Function orchestration (
.remote(),.map(), retries/timeouts) more than raw HTTP latency - Public URLs without proxy tokens (or optional
requires_proxy_auth) are fine
When to migrate to Server (modal-servers)
- Serving a long-lived HTTP process (vLLM, custom uvicorn, raw
http.server) where proxy latency matters - Need
routing_region/ stickyModal-Session-ID/target_concurrencyautoscaling - Want default authenticated ingress (proxy tokens) on
*.modal.direct - Replacing
@modal.web_server— prefer@app.server(seemodal-serversmigration reference)
When to use Auto Endpoints (modal-endpoints)
- Production LLM chat completions against catalog or HF/Volume weights with minimal config
- Prefer managed recipes over custom
@app.server/ Function code
Auth and testing note
Servers and Auto Endpoints default to proxy-token auth (Modal-Key / Modal-Secret). Many Function web URLs are public unless you set requires_proxy_auth=True. For authenticated Server/Endpoint-style testing without pasting headers, use:
modal workspace proxy-tokens create
modal curl "https://<workspace>--<app>-<server>.<region>.modal.direct/path"modal curl injects workspace proxy tokens (experimental; higher latency than raw curl with headers).
Four Ways to Serve HTTP
1. fastapi_endpoint (simplest)
Wraps a function in FastAPI automatically:
@app.function(image=image)
@modal.fastapi_endpoint()
def square(x: int):
return {"square": x**2}Accepts query params, POST bodies (dict or Pydantic models), path params.
2. asgi_app (full framework)
Serve a complete ASGI app (FastAPI, Starlette):
@app.function(image=image)
@modal.asgi_app()
def fastapi_app():
from fastapi import FastAPI
web_app = FastAPI()
@web_app.get("/")
def root():
return {"message": "hello"}
return web_app3. wsgi_app (Django, Flask)
@app.function(image=image)
@modal.wsgi_app()
def flask_app():
from flask import Flask
app = Flask(__name__)
@app.route("/")
def root():
return "hello"
return app4. web_server (raw HTTP)
For any HTTP server listening on a port:
@app.function(image=image)
@modal.web_server(port=8000)
def serve():
import subprocess
subprocess.Popen(["python", "-m", "http.server", "8000"])For new low-latency port-based serving, prefer @app.server (modal-servers) over @modal.web_server.
Streaming Responses
Use FastAPI's StreamingResponse for SSE or chunked responses:
@app.function(image=image)
@modal.fastapi_endpoint()
def stream():
from fastapi.responses import StreamingResponse
def generate():
for i in range(10):
yield f"data: chunk {i}\n\n"
return StreamingResponse(generate(), media_type="text/event-stream")Combine with .remote_gen() for GPU→web streaming:
@app.function(gpu="any")
def gpu_work():
for chunk in process():
yield chunk
@app.function(image=image)
@modal.fastapi_endpoint()
def endpoint():
from fastapi.responses import StreamingResponse
return StreamingResponse(gpu_work.remote_gen(), media_type="text/event-stream")Authentication
Proxy auth (token-based)
@app.function()
@modal.fastapi_endpoint(requires_proxy_auth=True)
def secure_endpoint():
return {"status": "authenticated"}Requests must include Modal-Key and Modal-Secret headers (workspace proxy token). Same header shape as Servers/Endpoints; create tokens with modal workspace proxy-tokens create. For quick tests: modal curl <url>.
Custom domains
@app.function()
@modal.fastapi_endpoint(custom_domains=["api.example.com"])
def my_api():
return {"hello": "world"}Configure DNS CNAME to modal.run. SSL provisioned automatically.
Labels
Control the endpoint URL with label:
@modal.fastapi_endpoint(label="my-api")
# URL: https://<workspace>--my-api.modal.runTimeouts
Web Function request timeout is 150 seconds by default. For long-running requests:
- Use streaming to keep the connection alive
- For >150s work, use
.spawn()+ polling pattern - Webhooks have their own timeout configuration
Go/TypeScript SDK Note
Web endpoint definition (@modal.fastapi_endpoint, @modal.asgi_app, @modal.wsgi_app) is Python-only. The Go and TypeScript SDKs cannot define web endpoints.
However, you can call Functions backing web endpoints from Go/TS via fn.Remote() / fn.remote(). You can also create Sandboxes that run web servers internally (accessible via tunneled ports or within the Modal network).
Symptom Triage
"Endpoint returns 500"
- Inspect logs via
modal-observability(modal app logs/modal container logs) - Ensure FastAPI is installed in the image
- Verify Pydantic models match request schema
"Slow first request"
- Cold start; use
min_containers=1for warm containers - Move model loading to
@modal.enter()lifecycle hook
"Streaming not real-time"
- Use
media_type="text/event-stream"for SSE - Other content types may be buffered by the web server
"Request times out"
- Default web timeout is 150s; use streaming for long responses
- For heavy processing, use
.spawn()+ polling pattern
"401 on Server URL but Function URL works"
- Servers require proxy tokens by default; Function web URLs are often public
- Use
modal curlor setModal-Key/Modal-Secret; orunauthenticated=Trueon the Server
Reference Map
references/web-endpoints.md— endpoint decorators, methods, POST/GET, Pydantic; vs Servers/Endpointsreferences/streaming-responses.md— SSE, StreamingResponse, async streamingreferences/custom-domains-auth.md— custom domains, authenticationreferences/frameworks.md— FastAPI, Django, Flask integration patterns- Sibling skills:
modal-servers,modal-endpoints
Guardrails
@modal.fastapi_endpointrequires FastAPI installed in the image- Web Functions autoscale and scale to zero like regular Functions
- Use
modal servefor development (live-reload),modal deployfor production @modal.web_endpointis the old name; use@modal.fastapi_endpoint(v0.73.82+)requires_proxy_auth=Trueadds token-based auth; not a substitute for user auth- Web request timeout is 150s — use streaming or async patterns for longer work
- Do not conflate Function web URLs (often public) with Server/Endpoint auth (proxy tokens by default)
- Prefer
@app.serverover new@modal.web_serverfor latency-sensitive port serving (modal-servers)
In this repository80 other files it gives its agents.
- a11y-accessibility-designSkill
- agentic-ui-patternsSkill
- ai-native-ui-designSkill
- ai-ui-anti-patternsSkill
- ai-ui-heuristicsSkill
- calm-technology-uiSkill
- conversion-growth-designSkill
- cross-platform-designSkill
- dark-mode-designSkill
- data-visualizationSkill
- design-systemsSkill
- design-thinking-processSkill
- error-empty-statesSkill
- ethical-design-patternsSkill
- form-uxSkill
- information-architectureSkill
- interaction-design-patternsSkill
- internationalization-uiSkill
- mobile-touch-designSkill
- modal-classes-lifecycleSkill
- modal-container-imagesSkill
- modal-dicts-queuesSkill
- modal-endpointsSkill
- modal-fundamentalsSkill
- modal-gpu-computeSkill
- modal-networkingSkill
- modal-observabilitySkill
- modal-parallel-executionSkill
- modal-sandboxesSkill
- modal-scaling-performanceSkill
- modal-schedulingSkill
- modal-secretsSkill
- modal-serversSkill
- modal-storageSkill
- modal-workspace-adminSkill
- motion-design-principlesSkill
- notifications-permissionsSkill
- onboarding-uxSkill
- rust-api-designSkill
- rust-async-programmingSkill
- rust-cargo-masterySkill
- rust-cli-applicationsSkill
- rust-clippy-lintsSkill
- rust-closures-iteratorsSkill
- rust-compiler-internalsSkill
- rust-concurrencySkill
- rust-design-patternsSkill
- rust-editionsSkill
- rust-embeddedSkill
- rust-error-handlingSkill
- rust-game-developmentSkill
- rust-lifetimes-borrowingSkill
- rust-macrosSkill
- rust-performanceSkill
- rust-rustdocSkill
- rust-rustup-toolchainSkill
- rust-smart-pointersSkill
- rust-testing-benchmarkingSkill
- rust-type-systemSkill
- rust-unsafe-ffiSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

