falcon is a minimalist Python framework for fast REST APIs. pip install falcon. App: import falcon; app = falcon.App(). Route: app.add_route("/users", UserResource()). Responder: class UserResource: def on_get(self, req, resp): resp.media = {"users": []}. POST: def on_post(self, req, resp): body = req.get_media(). Params: req.params["page"]. Query: req.get_param("q"). Query int: req.get_param_as_int("page", default=1). Headers: req.get_header("Authorization"). Path: def on_get(self, req, resp, user_id): — URI template "/users/{user_id}". Media: resp.media = {"key": "value"} — auto-JSON. Status: resp.status = falcon.HTTP_201. resp.status = "404 Not Found". Error: raise falcon.HTTPNotFound(). raise falcon.HTTPBadRequest(title="Bad", description="detail"). raise falcon.HTTPError(falcon.HTTP_422, title="Unprocessable"). Middleware: app = falcon.App(middleware=[AuthMiddleware()]). Method: class M: def process_request(self, req, resp): .... Hook: @falcon.before(check_auth). Streaming: resp.stream = file_like_obj. ASGI: import falcon.asgi; app = falcon.asgi.App(). CORSMiddleware: falcon.CORSMiddleware(allow_origins=["*"]). Testing: from falcon import testing; client = testing.TestClient(app). Run WSGI: gunicorn "myapp:app" -w 4. Run ASGI: uvicorn myapp:app. Claude Code generates falcon REST APIs, middleware chains, auth decorators, and ASGI microservices.
CLAUDE.md for falcon
## falcon Stack
- Version: falcon >= 3.1 | pip install falcon
- App: app = falcon.App(middleware=[...]) | falcon.asgi.App() for ASGI
- Route: app.add_route("/path/{id}", Resource()) | Resource.on_get/on_post/on_put/on_delete
- Request: req.get_param("q") | req.get_param_as_int("page") | req.get_media() | req.get_header("Auth")
- Response: resp.media = dict | resp.status = falcon.HTTP_201 | raise falcon.HTTPNotFound()
- Test: testing.TestClient(app).simulate_get("/path")
falcon REST API Pipeline
# app/api.py — falcon routes, middleware, auth, CRUD, validation, error handling
from __future__ import annotations
import json
import logging
import time
from dataclasses import dataclass, asdict, field
from functools import wraps
from typing import Any, Callable
import falcon
from falcon import Request, Response
log = logging.getLogger(__name__)
app = falcon.App()
# ─────────────────────────────────────────────────────────────────────────────
# 1. Response helpers
# ─────────────────────────────────────────────────────────────────────────────
def ok(resp: Response, data: Any, status: str = falcon.HTTP_200) -> None:
"""Set resp.media and status in one call."""
resp.media = data
resp.status = status
def created(resp: Response, data: Any) -> None:
"""201 Created shorthand."""
ok(resp, data, falcon.HTTP_201)
def no_content(resp: Response) -> None:
"""204 No Content."""
resp.status = falcon.HTTP_204
def paginate(items: list, page: int = 1, per_page: int = 20) -> dict:
"""Return a paginated result envelope."""
total = len(items)
offset = (page - 1) * per_page
return {
"items": items[offset: offset + per_page],
"total": total,
"page": page,
"per_page": per_page,
"pages": (total + per_page - 1) // per_page,
}
# ─────────────────────────────────────────────────────────────────────────────
# 2. Request parsing helpers
# ─────────────────────────────────────────────────────────────────────────────
def get_body(req: Request, required: list[str] | None = None) -> dict:
"""
Parse JSON body from request.
Raises HTTPBadRequest on missing body or HTTPUnprocessableEntity on missing keys.
Example:
body = get_body(req, required=["name", "email"])
"""
media = req.get_media()
if media is None:
raise falcon.HTTPBadRequest(description="JSON body required")
if not isinstance(media, dict):
raise falcon.HTTPBadRequest(description="JSON object expected")
for key in required or []:
if key not in media:
raise falcon.HTTPUnprocessableEntity(description=f"Missing required field: {key}")
return media
def get_page_params(req: Request) -> tuple[int, int]:
"""Parse page/per_page query params with defaults."""
page = req.get_param_as_int("page", default=1, min_value=1)
per_page = req.get_param_as_int("per_page", default=20, min_value=1, max_value=200)
return page, per_page
# ─────────────────────────────────────────────────────────────────────────────
# 3. Middleware
# ─────────────────────────────────────────────────────────────────────────────
class RequestLogMiddleware:
"""
Log every incoming request and its response time.
"""
def process_request(self, req: Request, resp: Response) -> None:
req.context.start_time = time.monotonic()
log.debug("%s %s", req.method, req.path)
def process_response(self, req: Request, resp: Response, resource, req_succeeded: bool) -> None:
elapsed = time.monotonic() - req.context.start_time
resp.set_header("X-Response-Time", f"{elapsed*1000:.1f}ms")
log.info(
"%s %s %s %.1fms",
req.method, req.path, resp.status, elapsed * 1000,
)
class CORSMiddleware:
"""
Simple CORS middleware for browser clients.
"""
def __init__(self, allow_origins: list[str] | str = "*") -> None:
self.allow_origins = allow_origins if isinstance(allow_origins, str) else ", ".join(allow_origins)
def process_response(self, req: Request, resp: Response, resource, req_succeeded: bool) -> None:
resp.set_header("Access-Control-Allow-Origin", self.allow_origins)
resp.set_header("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept")
resp.set_header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
class AuthMiddleware:
"""
Bearer token auth middleware.
Whitelists paths (e.g. /health) from auth requirement.
"""
SKIP = {"/health", "/", "/docs"}
VALID_TOKENS: set[str] = {"dev-token-123", "api-key-abc"}
def process_request(self, req: Request, resp: Response) -> None:
if req.method == "OPTIONS" or req.path in self.SKIP:
return
auth = req.get_header("Authorization") or ""
if not auth.startswith("Bearer "):
raise falcon.HTTPUnauthorized(description="Bearer token required")
token = auth[len("Bearer "):]
if token not in self.VALID_TOKENS:
raise falcon.HTTPForbidden(description="Invalid token")
req.context.token = token
# ─────────────────────────────────────────────────────────────────────────────
# 4. Hooks
# ─────────────────────────────────────────────────────────────────────────────
def require_json(req: Request, resp: Response, resource, params: dict) -> None:
"""Before hook: require Content-Type application/json for mutating methods."""
if req.method in ("POST", "PUT", "PATCH"):
ct = req.content_type or ""
if "application/json" not in ct:
raise falcon.HTTPUnsupportedMediaType(description="Content-Type must be application/json")
def validate_int_id(req: Request, resp: Response, resource, params: dict) -> None:
"""Before hook: ensure {id} path param is a positive integer."""
id_val = params.get("item_id") or params.get("user_id")
if id_val is not None:
try:
int_id = int(id_val)
if int_id < 1:
raise ValueError
params[list(params.keys())[0]] = int_id
except (ValueError, TypeError):
raise falcon.HTTPBadRequest(description="ID must be a positive integer")
# ─────────────────────────────────────────────────────────────────────────────
# 5. CRUD resources
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class Item:
id: int
name: str
tags: list[str] = field(default_factory=list)
active: bool = True
_items: dict[int, Item] = {}
_next_id = 1
def _new_id() -> int:
global _next_id
nid = _next_id
_next_id += 1
return nid
class ItemCollection:
"""
/items — list and create.
Example:
GET /items?page=1&per_page=20&q=widget
POST /items {"name": "Widget", "tags": ["new"]}
"""
@falcon.before(require_json)
def on_post(self, req: Request, resp: Response) -> None:
body = get_body(req, required=["name"])
item = Item(
id=_new_id(),
name=body["name"],
tags=body.get("tags", []),
active=body.get("active", True),
)
_items[item.id] = item
created(resp, asdict(item))
def on_get(self, req: Request, resp: Response) -> None:
page, per_page = get_page_params(req)
q = req.get_param("q", default="").lower()
items = list(_items.values())
if q:
items = [i for i in items if q in i.name.lower()]
ok(resp, paginate([asdict(i) for i in items], page, per_page))
class ItemResource:
"""
/items/{item_id} — get, update, delete.
"""
@falcon.before(validate_int_id)
def on_get(self, req: Request, resp: Response, item_id: int) -> None:
item = _items.get(item_id)
if not item:
raise falcon.HTTPNotFound(description=f"Item {item_id} not found")
ok(resp, asdict(item))
@falcon.before(validate_int_id)
@falcon.before(require_json)
def on_put(self, req: Request, resp: Response, item_id: int) -> None:
item = _items.get(item_id)
if not item:
raise falcon.HTTPNotFound(description=f"Item {item_id} not found")
body = get_body(req)
if "name" in body: item.name = body["name"]
if "tags" in body: item.tags = body["tags"]
if "active" in body: item.active = body["active"]
ok(resp, asdict(item))
@falcon.before(validate_int_id)
def on_delete(self, req: Request, resp: Response, item_id: int) -> None:
if item_id not in _items:
raise falcon.HTTPNotFound(description=f"Item {item_id} not found")
del _items[item_id]
ok(resp, {"deleted": item_id})
class HealthResource:
"""GET /health — liveness check."""
def on_get(self, req: Request, resp: Response) -> None:
ok(resp, {"status": "ok", "items": len(_items)})
class SearchResource:
"""GET /items/search?q=<query>"""
def on_get(self, req: Request, resp: Response) -> None:
q = req.get_param("q", default="").strip()
if not q:
raise falcon.HTTPBadRequest(description="Query param 'q' required")
matched = [asdict(i) for i in _items.values() if q.lower() in i.name.lower()]
ok(resp, {"results": matched, "count": len(matched)})
# ─────────────────────────────────────────────────────────────────────────────
# 6. Error handlers
# ─────────────────────────────────────────────────────────────────────────────
def handle_generic_error(req: Request, resp: Response, ex: Exception, params: dict) -> None:
"""Catch-all for unexpected exceptions."""
log.exception("Unhandled exception: %s %s", req.method, req.path)
raise falcon.HTTPInternalServerError(description="An unexpected error occurred")
# ─────────────────────────────────────────────────────────────────────────────
# 7. App wiring
# ─────────────────────────────────────────────────────────────────────────────
def create_app(auth: bool = False) -> falcon.App:
"""
Factory function: build and return the falcon App.
Usage:
# With auth
app = create_app(auth=True)
# Without auth (for tests)
app = create_app(auth=False)
Deploy:
gunicorn "myapp:create_app()" -w 4 --worker-class gthread -b 0.0.0.0:8000
uvicorn myapp:app # ASGI variant — use falcon.asgi.App()
"""
middleware = [RequestLogMiddleware(), CORSMiddleware()]
if auth:
middleware.append(AuthMiddleware())
application = falcon.App(middleware=middleware)
application.add_error_handler(Exception, handle_generic_error)
# Routes — /items/search must come BEFORE /items/{item_id}
application.add_route("/health", HealthResource())
application.add_route("/items/search", SearchResource())
application.add_route("/items", ItemCollection())
application.add_route("/items/{item_id}", ItemResource())
return application
app = create_app(auth=False)
# ─────────────────────────────────────────────────────────────────────────────
# Demo (uses falcon.testing)
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
from falcon import testing
# Seed
_items[1] = Item(id=1, name="Widget", tags=["hardware"])
_items[2] = Item(id=2, name="Gadget", tags=["electronics"])
_items[3] = Item(id=3, name="Doohickey", tags=["misc"])
_next_id = 4
client = testing.TestClient(app)
print("=== GET /health ===")
r = client.simulate_get("/health")
print(f" {r.status}: {r.json}")
print("\n=== GET /items ===")
r = client.simulate_get("/items?page=1&per_page=10")
print(f" total={r.json['total']}, names={[i['name'] for i in r.json['items']]}")
print("\n=== POST /items ===")
r = client.simulate_post(
"/items",
json={"name": "SuperWidget", "tags": ["new"]},
)
print(f" {r.status}: {r.json}")
print("\n=== GET /items/1 ===")
r = client.simulate_get("/items/1")
print(f" {r.status}: {r.json}")
print("\n=== PUT /items/1 ===")
r = client.simulate_put(
"/items/1",
json={"name": "Widget Pro", "active": False},
)
print(f" {r.status}: {r.json}")
print("\n=== GET /items/search?q=widget ===")
r = client.simulate_get("/items/search?q=widget")
print(f" {r.status}: count={r.json['count']}, results={[i['name'] for i in r.json['results']]}")
print("\n=== DELETE /items/2 ===")
r = client.simulate_delete("/items/2")
print(f" {r.status}: {r.json}")
print("\n=== 404 ===")
r = client.simulate_get("/items/999")
print(f" {r.status}")
print("\nRun with:")
print(" gunicorn 'api:create_app()' -w 4 -b 0.0.0.0:8000")
print(" uvicorn api:app # ASGI: swap falcon.App → falcon.asgi.App")
For the FastAPI alternative — FastAPI uses Pydantic models for automatic request/response validation and generates OpenAPI Swagger docs with zero config; falcon is 2–5× faster in raw throughput benchmarks because it does minimal automatic processing — use FastAPI when type safety, auto-validation, and interactive API docs matter for the team, falcon when you need the lowest-latency Python WSGI/ASGI possible and are willing to handle validation manually. For the Flask alternative — Flask has a massive ecosystem (Flask-Login, Flask-SQLAlchemy, Flask-WTF, Blueprints), a larger community, and an application-factory pattern for modular apps; falcon has a stricter design with no global app object, explicit middleware chains, and a responder-method convention (on_get, on_post) that maps cleanly to REST resources — use Flask for feature-rich web applications and admin UIs, falcon for dedicated REST microservices where response latency is a first-class concern. The Claude Skills 360 bundle includes falcon skill sets covering create_app() factory, ok()/created()/no_content() response helpers, get_body()/get_page_params() parsing, RequestLogMiddleware/CORSMiddleware/AuthMiddleware, require_json/validate_int_id hooks, ItemCollection/ItemResource CRUD responders, HealthResource/SearchResource, handle_generic_error catch-all, route ordering for static vs template paths, and TestClient simulation tests. Start with the free tier to try fast Python REST API microservice code generation.