### Example config.json with default_options Source: https://github.com/ducaale/xh/blob/master/doc/md-template.md Example configuration file for xh. The only configurable option is default_options, a list of default shell arguments passed to xh. ```json { "default_options": ["--native-tls", "--style=solarized"] } ``` -------------------------------- ### Buffer usage examples via command line Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/buffer.md Four command-line examples showing how `Buffer::new` routes output for terminal, redirected, file, and download scenarios. ```console $ xh httpbin.org/json # terminal → Buffer::stdout() → colored output $ xh httpbin.org/json | head # redirected → Buffer::redirect() → --pretty defaults to none $ xh -o out.json httpbin.org/json # file → Buffer::file() $ xh -d -o out.bin httpbin.org/zip # download → Buffer::stderr() (progress + status messages) ``` -------------------------------- ### xh command-line usage examples Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/request-items.md Command-line usage examples for request items. Shows how to send JSON body fields, query strings, headers, multipart files, raw body from file, and JSON-path keys. ```console $ xh httpbin.org/post name=ahmed age:=24 tags:=[1,2,3] # JSON body fields $ xh httpbin.org/post id==5 sort==true # query string $ xh httpbin.org/post x-api-key:12345 connection: # add / unset header $ xh httpbin.org/post header-with-no-value; # empty header value $ xh -f httpbin.org/post name=ahmed pfp@avatar.jpg;type=image/jpeg # multipart file $ xh httpbin.org/post @payload.json # raw body from file $ xh get httpbin.org/json 'nested[0][id]=1' # JSON-path keys ``` -------------------------------- ### NO_COLOR and TERM=dumb examples via command line Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/buffer.md Two command-line examples demonstrating the `NO_COLOR` and `TERM=dumb` behavior affecting formatting and colors. ```console $ NO_COLOR=1 xh httpbin.org/json # formatting yes (json indent), colors no $ TERM=dumb xh httpbin.org/json # same: Pretty::Format ``` -------------------------------- ### Install xh via PowerShell on Windows Source: https://github.com/ducaale/xh/blob/master/README.md Install xh on Windows using PowerShell. Requires PowerShell and internet access. ```powershell iwr -useb https://raw.githubusercontent.com/ducaale/xh/master/install.ps1 | iex ``` -------------------------------- ### Example header with both filename and filename* Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/content-disposition.md Example `Content-Disposition` header showing both the plain `filename` and the RFC 5987 encoded `filename*` parameter. The encoded form is preferred when present. ```text Content-Disposition: attachment; filename="fallback.pdf"; filename*=UTF-8''%E6%B5%8B%E8%AF%95.pdf ``` -------------------------------- ### Install xh via cURL on Linux and macOS Source: https://github.com/ducaale/xh/blob/master/README.md Install xh on Linux and macOS using the official installation script. Requires curl and a POSIX shell. ```bash curl -sfL https://raw.githubusercontent.com/ducaale/xh/master/install.sh | sh ``` -------------------------------- ### Send a GET request with query parameters Source: https://github.com/ducaale/xh/blob/master/doc/md-template.md Sends a GET request to http://httpbin.org/json?id=5&sort=true using request items. ```bash xh get httpbin.org/json id==5 sort==true ``` -------------------------------- ### Typical .netrc file Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/netrc.md Example `.netrc` file with a machine entry and a default entry. The default entry is a fallback when no machine matches. ```text machine api.example.com login alice password s3cret default login guest password guestpw ``` -------------------------------- ### Install xh via package managers Source: https://github.com/ducaale/xh/blob/master/README.md Install xh via various package managers. Each command targets a specific OS or package manager; note that some packages are built with native-tls only and some require additional setup (e.g., enabling the COPR repo). ```bash cargo install xh --locked ``` ```bash huber install xh ``` ```bash mise use xh --global ``` ```bash pkg install xh ``` ```bash mmrl install xhhttp ``` ```bash apk add xh ``` ```bash pacman -S xh ``` ```bash sudo apt install xh ``` ```bash sudo dnf install xh ``` ```bash pkg install xh ``` ```bash pkgin install xh ``` ```bash nix-env -iA nixpkgs.xh ``` ```bash flox install xh ``` ```bash brew install xh ``` ```bash hermit install xh ``` ```bash sudo port install xh ``` ```bash scoop install xh ``` ```bash choco install xh ``` ```bash winget add ducaale.xh ``` -------------------------------- ### xh CLI flag usage examples Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/printer.md Shows various xh invocations with flags like -p, -m, -v, --pretty, --format-options, --response-charset, --response-mime, and --stream to control printer output. Each line is a separate command example. ```console $ xh httpbin.org/json # terminal: color + format $ xh -p b httpbin.org/json # body only $ xh -m httpbin.org/json # metadata only: "Elapsed time: ..." $ xh -v httpbin.org/json # request headers + body + response $ xh --pretty=none httpbin.org/json # raw output $ xh --format-options=json.indent:2,headers.sort:false httpbin.org/json $ xh --response-charset=latin1 --response-mime=application/json httpbin.org/foo $ xh --stream httpbin.org/events # force streaming for non-event-stream bodies ``` -------------------------------- ### Send a GET request Source: https://github.com/ducaale/xh/blob/master/doc/md-template.md Sends a GET request to httpbin.org/json. ```bash xh httpbin.org/json ``` -------------------------------- ### xh command examples Source: https://github.com/ducaale/xh/blob/master/README.md Shows common xh usage: GET/POST/PUT requests, query strings, headers, stdin body, piping output, downloading, and custom user agent. ```sh # Send a GET request xh httpbin.org/json # Send a POST request with body {"name": "ahmed", "age": 24} xh httpbin.org/post name=ahmed age:=24 # Send a GET request with querystring id=5&sort=true xh get httpbin.org/json id==5 sort==true # Send a GET request and include a header named x-api-key with value 12345 xh get httpbin.org/json x-api-key:12345 # Send a POST request with body read from stdin. echo "[1, 2, 3]" | xh post httpbin.org/post # Send a PUT request and pipe the result to less xh put httpbin.org/put id:=49 age:=25 | less # Download and save to res.json xh -d httpbin.org/json -o res.json # Make a request with a custom user agent xh httpbin.org/get user-agent:foobar ``` -------------------------------- ### Generate shell completions and man pages Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/generation.md Usage examples for generating shell completions and man pages. Each command writes the generated output to a file or pipes it to gzip. ```console $ xh --generate=complete-bash > xh.bash $ xh --generate=complete-zsh > /usr/share/zsh/site-functions/_xh $ xh --generate=complete-fish > ~/.config/fish/completions/xh.fish $ xh --generate=man | gzip -9 > xh.1.gz $ xh --generate=man-markdown > xh.1.md ``` -------------------------------- ### Format options examples Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/formatting.md Shows various format options: setting JSON indent, disabling header sorting, using format-only pretty mode, applying a color style, and forcing response MIME type. ```console $ xh --format-options=json.indent:2 httpbin.org/json $ xh --format-options=headers.sort:false httpbin.org/get $ xh --pretty=format httpbin.org/json # format but no color $ xh --style=solarized httpbin.org/json $ xh --response-mime=application/json httpbin.org/opaque ``` -------------------------------- ### xh error-handling examples Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/request-items.md Error-handling behavior examples. Shows that JSON values are not supported in Form fields and that mixing a request body from a file with key=value data is not allowed. ```console $ xh -f httpbin.org/post x:=[1,2] # JSON values are not supported in Form fields $ xh httpbin.org/post foo=bar @file.json # Request body (from a file) and request data (key=value) cannot be mixed. ``` -------------------------------- ### Assembling middleware chain in main.rs Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/middleware.md Assembles the middleware chain per request in main.rs. --all installs the printer, --follow appends RedirectFollower with a default of 10 redirects, and digest auth appends DigestAuthMiddleware. The order of with calls determines execution order. ```rust let mut client = ClientWithMiddleware::new(&client); if args.all { client = client.with_printer(|prev_response, next_request| { /* print */ Ok(()) }); } if args.follow { client = client.with(RedirectFollower::new(args.max_redirects.unwrap_or(10))); } if let Some(Auth::Digest(username, password)) = &auth { client = client.with(DigestAuthMiddleware::new(username, password)); } client.execute(request)?; ``` -------------------------------- ### Session file JSON structure Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/session.md Example of the on-disk session file content written by persist() for the first command above. ```json { "__meta__": { "about": "xh session file", "xh": "0.26.2" }, "auth": { "type": "basic", "raw_auth": "user:pass", "password": null, "username": null }, "cookies": [], "headers": [] } ``` -------------------------------- ### Make a request with a custom user agent Source: https://github.com/ducaale/xh/blob/master/doc/md-template.md Sends a GET request with a custom user-agent header. ```bash xh httpbin.org/get user-agent:foobar ``` -------------------------------- ### URL shorthand examples for xh Source: https://github.com/ducaale/xh/blob/master/README.md Shows how xh resolves URLs when the scheme is omitted. A leading colon is shorthand for localhost, and a leading :// converts a URL into a valid xh or HTTPie command. ```sh xh http://localhost:3000/users # resolves to http://localhost:3000/users xh localhost:3000/users # resolves to http://localhost:3000/users xh :3000/users # resolves to http://localhost:3000/users xh :/users # resolves to http://localhost:80/users xh example.com # resolves to http://example.com xh ://example.com # resolves to http://example.com ``` -------------------------------- ### CLI usage for middleware features Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/middleware.md CLI usage examples for the middleware chain: -F enables redirect following with a custom max-redirects, --all prints every hop, and -A digest with -a enables digest authentication. ```console $ xh -F --max-redirects=5 httpbin.org/redirect/3 # redirect middleware $ xh -F --all httpbin.org/redirect/3 # + print every hop $ xh -A digest -a u:p httpbin.org/digest-auth/auth/u/p # + digest challenge ``` -------------------------------- ### Malformed XML fallback example Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/formatting.md Demonstrates that malformed XML falls back to syntax highlighting instead of failing, with a debug log message. ```console $ xh --response-mime=application/xml httpbin.org/anything # debug log: "Failed to format XML: ..." — output still renders with syntax highlighting ``` -------------------------------- ### xh command examples for internal helpers Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/utils.md These console commands illustrate the behavior of internal helpers: unescape for escaped separators, stdin for request bodies, XH_CONFIG_DIR for sessions, and expand_tilde for file-valued items. The first command shows that `foo\==bar` sends key `foo=`; the second reads the body from stdin; the third uses a custom config directory; the fourth expands `~` in file paths. ```console $ xh example.com foo\==bar # escaped separator — key is "foo=" (unescape) $ echo hi | xh post example.com # request body from stdin (see main.rs) $ XH_CONFIG_DIR=/tmp/cfg xh --session=dev example.com # sessions + config under /tmp/cfg $ xh example.com '~file@/tmp/a' # ~ expansion in file-valued items (expand_tilde) ``` -------------------------------- ### Config file config.json with default_options Source: https://github.com/ducaale/xh/blob/master/_autodocs/configuration.md Example of the optional JSON config file that sets default CLI options. The default_options array is prepended to the real argv, so per-user defaults can be overridden by explicitly passing flags later. A file that fails to read (except NotFound) or fails to parse produces a warning on stderr at startup and is otherwise ignored. ```json { "default_options": ["--https", "--style=solarized"] } ``` -------------------------------- ### Decode error example Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/decoder.md Demonstrates the failure surface when a server sends a mismatched Content-Encoding. The error message starts with the per-codec message and preserves the original error in the source chain. ```console $ xh --raw x example.com/api # forced Content-Encoding mismatch xh: error: error decoding gzip response body # wrapped codec error ``` -------------------------------- ### Create gzip compressed fixture (hello_world.gz) Source: https://github.com/ducaale/xh/blob/master/tests/fixtures/responses/README.md Creates a plain text file 'hello_world' containing 'Hello world', then compresses it with pigz to produce 'hello_world.gz'. ```sh $ echo "Hello world" > hello_world $ pigz hello_world # hello_world.gz ``` -------------------------------- ### Send a GET request with a header Source: https://github.com/ducaale/xh/blob/master/doc/md-template.md Sends a GET request and includes a header named X-Api-Key with value 12345. ```bash xh get Ihttpbin.org/json x-api-key:12345 ``` -------------------------------- ### Highlighter::new Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/formatting.md Constructor for the Highlighter struct. It initializes the highlighter with a syntax extension, theme, and output buffer. The syntax extension must be a valid syntect file extension; otherwise, it panics. ```APIDOC ## Highlighter::new ### Description Creates a new line-oriented syntax highlighter that writes directly into a `Buffer`. The `syntax` parameter is a syntect file extension (e.g., `"json"`, `"xml"`, `"html"`, `"css"`, `"js"`). An unknown extension will panic. ### Method `pub fn new(syntax: &'static str, theme: Theme, out: &'a mut Buffer) -> Self` ### Parameters - **syntax** (`&'static str`) - Required - The syntect file extension to use for highlighting. - **theme** (`Theme`) - Required - The theme to use for highlighting. - **out** (`&'a mut Buffer`) - Required - The output buffer to write highlighted text to. ### Source `src/formatting/mod.rs:76` ``` -------------------------------- ### Create compress (ZZ) compressed fixture (hello_world.zz) Source: https://github.com/ducaale/xh/blob/master/tests/fixtures/responses/README.md Creates a plain text file 'hello_world' containing 'Hello world', then compresses it with pigz -z to produce 'hello_world.zz'. ```sh $ echo "Hello world" > hello_world $ pigz -z hello_world # hello_world.zz ``` -------------------------------- ### Create Brotli compressed fixture (hello_world.br) Source: https://github.com/ducaale/xh/blob/master/tests/fixtures/responses/README.md Creates a plain text file 'hello_world' containing 'Hello world', then compresses it with brotli to produce 'hello_world.br'. ```sh $ echo "Hello world" > hello_world $ brotli hello_world # hello_world.br ``` -------------------------------- ### Create Zstandard compressed fixture (hello_world.zst) Source: https://github.com/ducaale/xh/blob/master/tests/fixtures/responses/README.md Creates a plain text file 'hello_world' containing 'Hello world', then compresses it with zstd to produce 'hello_world.zst'. ```sh $ echo "Hello world" > hello_world $ zstd hello_world # hello_world.zst ``` -------------------------------- ### ClientWithMiddleware::new Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/middleware.md Creates a new `ClientWithMiddleware` builder with no printer and an empty middleware vector. ```APIDOC ## ClientWithMiddleware::new ### Description Creates a new `ClientWithMiddleware` builder with no printer and an empty middleware vector. ### Method Constructor ### Signature ```rust pub fn new(client: &'a Client) -> Self ``` ### Parameters - **client** (`&'a Client`) - Required - The shared `reqwest::blocking::Client` to wrap. ### Returns - `Self` - The new builder instance. ``` -------------------------------- ### Create Highlighter with syntax, theme, and output buffer Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/formatting.md Constructor for Highlighter. syntax is a syntect file extension ("json", "xml", "html", "css", "js"); it calls syntax_set.find_syntax_by_extension(syntax).expect("syntax not found") — an unknown extension panics. The theme is converted via Theme::as_syntect_theme(). ```rust pub fn new(syntax: &'static str, theme: Theme, out: &'a mut Buffer) -> Self ``` -------------------------------- ### Auth failure example Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/auth.md Failure mode example: a wrong or missing password on a non-challenging server ends as a normal server error (401 → exit code 4 by default). The HTTP 401 line is printed as a warning when headers are suppressed. ```console $ xh -a wrong:wrong httpbin.org/basic-auth/user/pass HTTP 401 Unauthorized # printed as warning when headers are suppressed ``` -------------------------------- ### ClientWithMiddleware::execute Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/middleware.md Freezes the current middleware vector into a `Context` with the printer and runs it. ```APIDOC ## ClientWithMiddleware::execute ### Description Freezes the current middleware vector into a `Context` with the printer and runs it. ### Method Method ### Signature ```rust pub fn execute(&mut self, request: Request) -> Result ``` ### Parameters - **request** (`Request`) - Required - The request to execute through the middleware chain. ### Returns - `Result` - The response from the client, or an error if any middleware short-circuits. ``` -------------------------------- ### Password-only netrc entry for bearer auth Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/netrc.md Example of a password-only entry used for bearer token authentication. ```text machine auth.example.com password token-abc123 ``` -------------------------------- ### Automatic decompression example Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/decoder.md Shows how decompression is implicit: xh sends the Accept-Encoding header automatically and decodes the response transparently. ```console $ xh -v --headers httpbin.org/gzip # "Accept-Encoding: gzip, deflate, br, zstd" is sent automatically; # a gzip response is transparently decoded (no Content-Encoding leaks into the output) ``` -------------------------------- ### Digest auth usage Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/auth.md Usage example for digest authentication. Digest requires two round trips; the middleware handles it transparently. ```console $ xh -A digest -a user:pass httpbin.org/digest-auth/auth/user/pass ``` -------------------------------- ### Create and reuse a session with --session Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/session.md Creates a session with basic auth and then reuses it in a second call, persisting auth, cookies, and headers. ```console $ xh --session=user1 -a user:pass httpbin.org/basic-auth/u/1 $ xh --session=user1 httpbin.org/get # sends the saved Authorization + cookies ``` -------------------------------- ### ClientWithMiddleware::with_printer Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/middleware.md Registers the `--all` print callback. Returns `self` for chaining. ```APIDOC ## ClientWithMiddleware::with_printer ### Description Registers the `--all` print callback. Returns `self` for chaining. ### Method Method ### Signature ```rust pub fn with_printer(mut self, printer: T) -> Self ``` ### Parameters - **printer** (`T`) - Required - The callback that prints the previous response and the next request at every hop. ### Returns - `Self` - The builder with the printer set. ``` -------------------------------- ### Explicit output and resume with --continue Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/download.md Use -o to set the output file. The --continue flag resumes an interrupted download by sending a Range header with the current size. ```console $ xh -d -o res.json httpbin.org/json # first attempt (truncated) ``` ```console $ xh -d -o res.json --continue httpbin.org/json # sends Range: bytes=- ``` -------------------------------- ### Usage example: malformed path error Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/nested-json.md Shows the error message when a malformed path is provided. The caret highlights the position where the expected '[' is missing. ```console $ xh post httpbin.org/post 'foo[bar]h[z]=1' xh: error: expected '[' foo[bar]h[z] ^ ``` -------------------------------- ### TypeError display example Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/nested-json.md Shows the formatted error message when a type clash occurs, including the accessor and a caret highlighting the offending component. ```text Can't perform 'index' based access on 'object' which has a type of 'object' but this operation requires a type of 'array'. app[0] ^ ``` -------------------------------- ### RequestItems struct definition Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/request-items.md Defines the RequestItems struct with a vector of RequestItem and a BodyType field. Defaults to BodyType::Json and is installed into Cli via #[clap(skip)]. ```rust #[derive(Default, Debug)] pub struct RequestItems { pub items: Vec, pub body_type: BodyType, } ``` -------------------------------- ### Theme enum Source: https://github.com/ducaale/xh/blob/master/_autodocs/types.md Selects syntax highlighting theme. as_str() maps to syntect theme names "ansi", "solarized", "monokai", "fruity"; as_syntect_theme() looks them up in crate::formatting::THEMES. Accepted by Printer::new / Highlighter::new. ```rust #[derive(Default, ValueEnum, Debug, PartialEq, Eq, Clone, Copy)] pub enum Theme { #[default] Auto, Solarized, Monokai, Fruity, } ``` -------------------------------- ### Reproducible man page generation with SOURCE_DATE_EPOCH Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/generation.md Example for reproducible man page generation by setting SOURCE_DATE_EPOCH to a fixed timestamp, ensuring a deterministic revision date. ```console $ SOURCE_DATE_EPOCH=1700000000 xh --generate=man | head -4 # deterministic revision date ``` -------------------------------- ### Print all redirect hops with --all Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/redirect.md With --all, every intermediate exchange is printed: request headers/body and response headers/body for each hop, controlled by --history-print. ```console $ xh -F --all httpbin.org/redirect/2 # shows: request 1 → response 301, request 2 → response 301, request 3 → final response ``` -------------------------------- ### Make an HTTPS request with xhs Source: https://github.com/ducaale/xh/blob/master/doc/md-template.md Makes an HTTPS request to https://example.com using the xhs binary. ```bash xhs example.com ``` -------------------------------- ### Usage example: type clash error Source: https://github.com/ducaale/xh/blob/master/_autodocs/api-reference/nested-json.md Shows the error message when a type clash occurs, e.g., trying to index an object as an array. The error indicates the required type. ```console $ xh post httpbin.org/post 'foo=1' 'foo[0]=2' --raw '{}' xh: error: Can't perform 'index' based access on 'foo' ... requires a type of 'array'. ```