Salta ai contenuti

xh - Cheat Sheet per HTTP Client Moderno

xh - Cheat Sheet per HTTP Client Moderno

Installazione

PiattaformaComando
Ubuntu/Debian`curl -sfL https://raw.githubusercontent.com/ducaale/xh/master/install.sh \
Arch Linuxpacman -S xh
Fedora/RHELdnf install xh
macOS (Homebrew)brew install xh
macOS (MacPorts)sudo port install xh
Windows (Scoop)scoop install xh
Windows (Chocolatey)choco install xh
Cargo (All platforms)cargo install xh
Dockerdocker pull ducaale/xh
Snapsnap install xh

Comandi Base

ComandoDescrizione
xh httpbin.org/getRichiesta GET semplice
xh POST httpbin.org/post name=JohnRichiesta POST con dati JSON
xh PUT httpbin.org/put status=activeRichiesta PUT con dati
xh PATCH httpbin.org/patch email=new@email.comRichiesta PATCH per aggiornare la risorsa
xh DELETE httpbin.org/deleteRichiesta DELETE
xh HEAD httpbin.org/getRichiesta HEAD (solo intestazioni)
xh OPTIONS httpbin.org/getRichiesta OPTIONS
xh httpbin.org/get search==rustGET con parametro di query
xh httpbin.org/get page==1 limit==10Parametri di query multipli
xh -a user:pass httpbin.org/basic-auth/user/passAutenticazione di base
xh -A bearer -a token123 api.example.comAutenticazione con bearer token
xh httpbin.org/get User-Agent:CustomAgentIntestazione personalizzata
xh -b httpbin.org/jsonStampa solo il corpo della risposta
xh -h httpbin.org/jsonStampa solo gli header della risposta
xh -v httpbin.org/jsonOutput dettagliato (intestazioni + corpo)
xh httpbin.org/json -o response.jsonScarica risposta in file
xh --follow=0 httpbin.org/redirect/3Non seguire i reindirizzamenti
xh -f POST httpbin.org/post name=JohnPOST con dati del form
xh POST httpbin.org/post < data.jsonPOST con contenuto del file
xh httpbin.org/get Authorization:"Bearer token"Header di autorizzazione

Utilizzo Avanzato

ComandoDescrizione
xh POST httpbin.org/post age:=30 active:=trueJSON con conversione di tipo (numero/booleano)
xh POST httpbin.org/post tags:='["rust","cli"]'Invia array JSON
xh POST httpbin.org/post user[name]=John user[age]:=30Oggetti JSON annidati
xh --session=mysession httpbin.org/cookies/set/token/abcCrea sessione denominata (mantieni cookie)
xh --session=mysession httpbin.org/cookiesRiutilizza sessione
xh --session-read-only=mysession httpbin.org/getUtilizzare la sessione senza aggiornarla
xh -f POST httpbin.org/post file@/path/to/file.txtCarica file come multipart form
xh POST httpbin.org/post @file.jsonCarica file come corpo della richiesta
xh --proxy=http:http://proxy.example.com:8080 httpbin.org/getUtilizzare un proxy HTTP
xh --proxy=all:socks5://localhost:1080 httpbin.org/getUsa proxy SOCKS5
xh --verify=no https://self-signed.badssl.com/Ignora verifica SSL (non sicuro)
xh --cert=/path/to/ca-cert.pem https://api.example.comCertificato CA personalizzato
xh --cert=/path/to/client.crt --cert-key=/path/to/client.key https://api.example.comAutenticazione del certificato client
xh --timeout=30 httpbin.org/delay/5Imposta timeout richiesta (secondi)
xh --pretty=none httpbin.org/jsonDisabilita output colorato/formattato
xh --style=monokai httpbin.org/jsonUtilizzare uno schema di colori specifico
xh --stream httpbin.org/stream/100Risposta stream
xh --download httpbin.org/image/png -o image.pngScarica con barra di avanzamento
xh --continue httpbin.org/stream/100 -o stream.txtRiprendi download parziale
xh --http-version=1.1 https://httpbin.org/getForza HTTP/1.1
xh --method=CUSTOM httpbin.org/anythingMetodo HTTP personalizzato
xh --multipart POST httpbin.org/post name=John file@doc.pdfModulo multipart con dati misti
xh httpbin.org/get Cookie:session=abc123Invia cookies
xh --auth-type=digest -a user:pass httpbin.org/digest-auth/auth/user/passAutenticazione digest

Tipi di Dati JSON

Quando si inviano dati JSON, xh supporta la conversione dei tipi con una sintassi speciale:

SintassiTipoEsempio
key=valueStringname=John{"name":"John"}
key:=numberNumeroage:=30{"age":30}
key:=trueBooleanactive:=true{"active":true}
key:=nullNullmiddle:=null{"middle":null}
key:='[...]'Arraytags:='["a","b"]'{"tags":["a","b"]}
key:='{...}'Oggettometa:='{"v":1}'{"meta":{"v":1}}
key[sub]=valueNidificatouser[name]=John{"user":{"name":"John"}}

Configurazione

Posizioni di Archiviazione Sessione

# Linux/macOS
~/.config/xh/sessions/

# Windows
%APPDATA%\xh\sessions\

Variabili di Ambiente

# Set default proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080

# Disable proxy for specific hosts
export NO_PROXY=localhost,127.0.0.1,.example.com

# Default timeout
export XH_TIMEOUT=30

Alias Comuni

# Add to ~/.bashrc or ~/.zshrc

# HTTPie compatibility
alias http='xh'
alias https='xh --default-scheme=https'

# Quick shortcuts
alias xhj='xh --pretty=all'  # Force JSON pretty-print
alias xhn='xh --pretty=none' # No formatting
alias xhv='xh -v'            # Verbose by default
alias xhd='xh --download'    # Download mode

Casi d’Uso Comuni

Caso d’Uso: Test di REST API con Autenticazione

# Login and save session
xh --session=api POST https://api.example.com/login \
  username=admin password=secret

# Make authenticated requests using saved session
xh --session=api GET https://api.example.com/users

# Update resource
xh --session=api PUT https://api.example.com/users/123 \
  name="John Doe" email=john@example.com status=active

# Delete resource
xh --session=api DELETE https://api.example.com/users/123

Caso d’Uso: Caricamento File con Metadati

# Upload file with additional form fields
xh -f POST https://api.example.com/upload \
  file@/path/to/document.pdf \
  title="Important Document" \
  category=legal \
  tags:='["contract","2024"]'

# Multiple file upload
xh -f POST https://api.example.com/batch-upload \
  file1@image1.jpg \
  file2@image2.jpg \
  album="Vacation 2024"

Caso d’Uso: Test API con Ambienti Diversi

# Development environment
xh --session=dev POST https://dev-api.example.com/test \
  Authorization:"Bearer dev-token-123" \
  data=test

# Staging environment
xh --session=staging POST https://staging-api.example.com/test \
  Authorization:"Bearer staging-token-456" \
  data=test

# Production environment (with SSL verification)
xh --session=prod POST https://api.example.com/test \
  Authorization:"Bearer prod-token-789" \
  data=test

Caso d’Uso: Debug di Payload Webhook

# Capture webhook payload to file
xh POST https://webhook.site/your-unique-url \
  event=user.created \
  user[id]:=12345 \
  user[email]=new@example.com \
  timestamp:=$(date +%s) \
  -v -o webhook-debug.txt

# Test webhook with retry logic (in script)
for i in {1..3}; do
  xh POST https://your-app.com/webhook \
    event=test \
    attempt:=$i && break || sleep 5
done

Caso d’Uso: Download e Elaborazione di Dati API

# Download JSON data
xh GET https://api.github.com/users/octocat/repos \
  -o repos.json

# Download with authentication and save
xh -a token:ghp_your_token \
  GET https://api.github.com/user/repos \
  visibility==private \
  -o private-repos.json

# Stream large dataset
xh --stream GET https://api.example.com/export/data \
  format==json \
  | jq '.[] | select(.active == true)' \
  > active-records.json

Migliori Pratiche

  • Utilizzare sessioni per flussi di lavoro autenticati: Le sessioni mantengono i cookie e le intestazioni, eliminando la necessità di ri-autenticarsi per ogni richiesta. Utilizzare --session=nameper interazioni API multi-step.

  • Sfruttare la conversione dei tipi per JSON: Utilizzare :=per numeri e booleani (age:=30, active:=true) invece di valori stringa per garantire tipi JSON corretti nelle richieste API.

  • Preferire xh a curl per test API: La sintassi intuitiva (xh POST api.com name=value) è più leggibile dei flag verbosi di curl, rendendolo ideale per documentazione e test rapidi.

  • Utilizzare la modalità dettagliata per il debug: Aggiungere -vper vedere le intestazioni complete di richiesta e risposta durante la risoluzione di problemi API o di autenticazione.

  • Archiviare token sensibili nelle variabili di ambiente: Invece dixh -a token:secret_key, utilizzare xh -a token:$API_TOKENper evitare di esporre le credenziali nella cronologia della shell.

  • Utilizzare il reindirizzamento dell’output per l’automazione: Salvare le risposte con -o file.jsonper l’elaborazione o il confronto in pipeline CI/CD e script di test automatizzati.

  • Impostare timeout appropriati: Utilizzare --timeout=30per API lente per prevenire richieste bloccate. Impostare --timeout=0solo per operazioni di streaming o a esecuzione prolungata.

  • Organizzare le sessioni per ambiente: Creare sessioni separate per sviluppo, staging e produzione (--session=prod-api) per evitare di utilizzare accidentalmente credenziali errate.

Risoluzione dei problemi

ProblemaSoluzione
SSL certificate verification failedUse --verify=no to skip verification (insecure) or --cert=/path/to/ca.pem to provide custom CA certificate
Connection timeoutIncrease timeout with --timeout=60 or check network connectivity and proxy settings
401 UnauthorizedVerify authentication method: use -a user:pass for basic auth, -A bearer -a token for bearer tokens, or check session validity
JSON parsing errorEnsure proper syntax: use := for non-strings (age:=30), quote arrays (tags:='["a","b"]'), and check for unescaped special characters
Command not found: xhVerify installation path is in $PATH, reinstall using preferred method, or use full path /usr/local/bin/xh
Session not persistingCheck session directory permissions (~/.config/xh/sessions/), ensure using same session name, verify not using --session-read-only
Proxy connection failedVerify proxy URL format --proxy=http:http://host:port, check proxy authentication if required, ensure proxy allows target host
File upload failsUse -f or --multipart flag for form uploads, verify file path is correct, check file permissions and size limits
Response not formatted/coloredForce formatting with --pretty=all, check terminal supports colors, or pipe through jq for JSON formatting