Test typed JSON requests against a local server with xh
Send strings and numeric JSON fields with xh, inspect the echoed payload, and observe HTTP error exit status.
Updated
in short
Use = for string fields and := for JSON values. A disposable localhost echo server lets you inspect the actual request without an external service.
Work through these disposable fixtures before adapting the commands to your own files. Run the steps in the same terminal session.
Tools used
Before you start
- Bash on Linux or macOS
- The listed tools installed and available on PATH
- Python 3 available as python3
Steps
Step 1: Create a local echo server
Python listens only on loopback and selects a free port. The server echoes POST JSON and returns 404 for GET.
shtrmn_guide_dir="$(mktemp -d)" cd "$trmn_guide_dir" cat > echo_server.py <<'EOF' from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path import json class Handler(BaseHTTPRequestHandler): def do_POST(self): data = json.loads(self.rfile.read(int(self.headers['Content-Length']))) body = json.dumps(data, sort_keys=True).encode() self.send_response(200) self.send_header('Content-Type', 'application/json') self.send_header('Content-Length', str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): self.send_error(404) def log_message(self, *args): pass server = HTTPServer(('127.0.0.1', 0), Handler) Path('port.txt').write_text(str(server.server_port)) server.serve_forever() EOF python3 echo_server.py & trmn_echo_pid=$! for trmn_attempt in {1..50}; do test -s port.txt && break sleep 0.1 done test -s port.txt trmn_echo_url="http://127.0.0.1:$(cat port.txt)"Step 2: Send a string and a JSON number
--ignore-stdin avoids accidentally consuming piped input. --pretty=none keeps output suitable for redirection.
shxh --ignore-stdin --pretty=none --body POST "$trmn_echo_url/echo" name=demo count:=3output{"count": 3, "name": "demo"}Step 3: Observe an HTTP error in a conditional
The failed request stays inside an if statement so a shell with errexit can reach cleanup.
shif xh --ignore-stdin --check-status --quiet GET "$trmn_echo_url/missing"; then printf 'unexpected success\n' else printf 'HTTP failure exit: %s\n' "$?" fioutputHTTP failure exit: 4
Step 4: Stop the fixture server
If you stop earlier, run this cleanup step before leaving the terminal.
shkill "$trmn_echo_pid" wait "$trmn_echo_pid" 2>/dev/null || true
Further reading
[xh usage and request item syntax](https://github.com/ducaale/xh) [Python HTTP server reference](https://docs.python.org/3/library/http.server.html)
FAQ
- Why use count:=3 instead of count=3?
- The := syntax parses its value as JSON. count=3 sends the text "3", while count:=3 sends a number.
- Does this call a public API?
- No. Every request in the example targets a server bound to 127.0.0.1 on your own machine.