Claude Code for falcon: Fast Python REST API Framework — Claude Skills 360 Blog
Blog / AI / Claude Code for falcon: Fast Python REST API Framework
AI

Claude Code for falcon: Fast Python REST API Framework

Published: May 31, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free