Skip to content

cURL Command Builder — Python source

Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""curl-builder — structured input → copy-paste curl command + reverse parser.
Python port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
Composes a copy-paste curl command from structured input; also parses an
existing command back into the structure (round-trip). Values are single-
quoted with embedded quotes escaped (' → '\'') — safe for POSIX shells. The
flag order is fixed and deterministic: method (-X) → headers (-H, insertion
order) → auth (-u) → data (-d) → boolean flags (-I -k -L --compressed) →
the URL last. Request dicts use the TS field names (method, headers, auth,
headOnly, insecure, followRedirects, compressed; missing key = unset).
Never raises — errors travel in the result dict ("error": None on success).
"""
import re

METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS")
_URL_RE = re.compile(r"^(https?://|/|\$)")
_HEADER_RE = re.compile(r"^[A-Za-z0-9-]+$")


def shell_quote(value):
    """POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen)."""
    return "'" + value.replace("'", "'\\''") + "'"


def build_curl_command(req):
    """Build the curl command. URL required; method/header names validated."""
    url = req.get("url", "").strip()
    if not url:
        return {"command": "", "error": "A URL is required"}
    if not _URL_RE.match(url):
        return {"command": "", "error": "URL must start with http://, https://, / or $ (a variable)"}
    method = req.get("method")
    method = ("GET" if method is None else method).upper()
    if method not in METHODS:
        return {"command": "", "error": "unsupported method %s (use %s)" % (req.get("method"), ", ".join(METHODS))}
    for h in req.get("headers", ()):
        if not _HEADER_RE.match(h.get("key", "")):
            return {"command": "", "error": 'invalid header name "%s" (letters, digits and hyphens only)' % h.get("key", "")}
    parts = ["curl"]
    if method != "GET":
        parts.append("-X " + method)
    for h in req.get("headers", ()):
        parts.append("-H " + shell_quote("%s: %s" % (h.get("key", ""), h.get("value", ""))))
    auth = req.get("auth")
    if auth is not None:
        parts.append("-u " + shell_quote("%s:%s" % (auth.get("user", ""), auth.get("password", ""))))
    data = req.get("data")
    if data is not None and data != "":
        parts.append("-d " + shell_quote(data))
    if req.get("headOnly"):
        parts.append("-I")
    if req.get("insecure"):
        parts.append("-k")
    if req.get("followRedirects"):
        parts.append("-L")
    if req.get("compressed"):
        parts.append("--compressed")
    parts.append(shell_quote(url))
    return {"command": " ".join(parts), "error": None}


def _split_words(line):
    """Shell word-split respecting single and double quotes."""
    words, cur, quote, has = [], "", None, False
    for ch in line:
        if quote:
            if ch == quote:
                quote = None
            else:
                cur += ch
        elif ch in "'\"":
            quote = ch
            has = True
        elif ch in " \t":
            if cur or has:
                words.append(cur)
            cur, has = "", False
        else:
            cur += ch
            has = True
    if has:
        words.append(cur)  # any accumulated characters imply has
    return words


def parse_curl_command(line):
    """Parse a curl command line back into a request (best effort, ordered)."""
    trimmed = line.strip()
    if not trimmed:
        return {"parsed": None, "error": "A command is required"}
    words = _split_words(trimmed.replace("\\\n", " "))
    if words[0] != "curl":
        return {"parsed": None, "error": "command must start with curl"}
    req = {"url": "", "headers": []}
    unknown_flags = []
    i = 1

    def take():
        nonlocal i
        i += 1
        return words[i] if i < len(words) else None

    while i < len(words):
        w = words[i]
        if w in ("-X", "--request"):
            req["method"] = take()
        elif w in ("-H", "--header"):
            raw = take()
            if raw is not None:
                at = raw.find(":")
                if at > 0:
                    req["headers"].append({"key": raw[:at].strip(), "value": raw[at + 1:].strip()})
        elif w in ("-u", "--user"):
            raw = take()
            if raw is not None:
                at = raw.find(":")
                req["auth"] = {"user": raw if at == -1 else raw[:at],
                               "password": "" if at == -1 else raw[at + 1:]}
        elif w in ("-d", "--data"):
            req["data"] = take()
        elif w in ("-I", "--head"):
            req["headOnly"] = True
        elif w in ("-k", "--insecure"):
            req["insecure"] = True
        elif w in ("-L", "--location"):
            req["followRedirects"] = True
        elif w == "--compressed":
            req["compressed"] = True
        elif w.startswith("-"):
            unknown_flags.append(w)
        else:
            req["url"] = w
        i += 1
    if not req["url"]:
        return {"parsed": None, "error": "no URL found in command"}
    return {"parsed": {"request": req, "unknownFlags": unknown_flags}, "error": None}


# Example:
# shell_quote("it's") → "'it'\\''s'"
# build_curl_command({"url": "https://api.example.com", "method": "post",
#                     "headers": [{"key": "X-Tag", "value": "it's"}], "data": "k=v"})
# → {"command": "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'", "error": None}
# parse_curl_command("curl -sL --compressed 'https://x.dev'")
# → {"parsed": {"request": {"url": "https://x.dev", "headers": [], "compressed": True}, "unknownFlags": ["-sL"]}, "error": None}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →