Saltar a contenido

HTTPie

_

HTTPie Cheatsheet

Instalación

Platform Command
Ubuntu/Debian INLINE_CODE_14
Fedora/RHEL INLINE_CODE_15
Arch Linux INLINE_CODE_16
macOS (Homebrew) INLINE_CODE_17
Windows (Chocolatey) INLINE_CODE_18
Windows (Scoop) INLINE_CODE_19
Windows (winget) INLINE_CODE_20
pip (Universal) INLINE_CODE_21
pipx (Isolated) INLINE_CODE_22
Docker INLINE_CODE_23
Snap INLINE_CODE_24

Verificar la instalación:

http --version

Comandos básicos

__TABLE_160_

Advanced Usage

Command Description
INLINE_CODE_46 Create named session (persists cookies/headers)
INLINE_CODE_47 Reuse existing session
INLINE_CODE_48 Use session without updating it
INLINE_CODE_49 Send non-string JSON values (INLINE_CODE_50 for raw JSON)
INLINE_CODE_51 Send nested JSON object
INLINE_CODE_52 Send JSON array
INLINE_CODE_53 Send null value
INLINE_CODE_54 Pipe raw JSON body
INLINE_CODE_55 Send JSON from file
INLINE_CODE_56 Use file content as JSON value
INLINE_CODE_57 Print only request headers
INLINE_CODE_58 Print only response headers
INLINE_CODE_59 Print request and response headers
INLINE_CODE_60 Print only response body
INLINE_CODE_61 Disable formatting and colors
INLINE_CODE_62 Stream large response
INLINE_CODE_63 Use HTTP proxy
INLINE_CODE_64 Proxy with authentication
INLINE_CODE_65 Limit redirect following
INLINE_CODE_66 Upload multiple files
INLINE_CODE_67 Send OPTIONS request
INLINE_CODE_68 Resume interrupted download
INLINE_CODE_69 Multiple headers with same name
INLINE_CODE_70 Digest authentication

Request Item Types

HTT Pie utiliza operadores especiales para distinguir tipos de datos:

Operator Type Example Result
INLINE_CODE_71 String (JSON) INLINE_CODE_72 INLINE_CODE_73
INLINE_CODE_74 Raw JSON INLINE_CODE_75 INLINE_CODE_76
INLINE_CODE_77 Query parameter INLINE_CODE_78 INLINE_CODE_79
INLINE_CODE_80 Header INLINE_CODE_81 INLINE_CODE_82
INLINE_CODE_83 File upload INLINE_CODE_84 Multipart file
INLINE_CODE_85 File as value INLINE_CODE_86 File content as string
INLINE_CODE_87 File as JSON INLINE_CODE_88 File content as JSON

Output Control

__TABLE_163_

Configuración

HTT Configuración de piezas en ubicaciones específicas de plataforma:

Configuración Ubicaciones de archivos: - Linux/macOS: __INLINE_CODE_104_ - Windows: %APPDATA%\httpie\config.json

Configuración del ejemplo:

{
    "default_options": [
        "--style=monokai",
        "--timeout=30"
    ],
    "implicit_content_type": "json",
    "prettify": true
}

Sesion Files Location: - Linux/macOS ~/.config/httpie/sessions/<host>/<session-name>.json - Windows: %APPDATA%\httpie\sessions\<host>\<session-name>.json

Example Session File:

{
    "headers": {
        "Authorization": "Bearer token123",
        "User-Agent": "MyApp/1.0"
    },
    "cookies": {
        "session_id": "abc123"
    }
}

** Variables del medio ambiente: #

# Set default options
export HTTPIE_CONFIG_DIR=~/.config/httpie

# Disable colors
export NO_COLOR=1

# Set default timeout
export HTTPIE_TIMEOUT=60

Common Use Cases

Use Case 1: Testing REST API CRUD Operations

# Create a new user (POST)
http POST api.example.com/users name="John Doe" email="john@example.com" age:=30

# Read user details (GET)
http GET api.example.com/users/123

# Update user (PUT)
http PUT api.example.com/users/123 name="Jane Doe" email="jane@example.com"

# Partial update (PATCH)
http PATCH api.example.com/users/123 email="newemail@example.com"

# Delete user (DELETE)
http DELETE api.example.com/users/123

Use Case 2: API Authentication Flow

# Login and create session
http --session=myapp POST api.example.com/auth/login \
  username="john@example.com" \
  password="secret123"

# Access protected endpoint using session (token/cookies persist)
http --session=myapp GET api.example.com/profile

# Make authenticated requests
http --session=myapp POST api.example.com/posts \
  title="My Post" \
  content="Post content here"

# Logout
http --session=myapp POST api.example.com/auth/logout

Use Case 3: File Upload with Metadata

# Upload file with form data
http -f POST api.example.com/documents \
  file@/path/to/document.pdf \
  title="Q4 Report" \
  category="financial" \
  confidential:=true

# Upload multiple files
http -f POST api.example.com/gallery \
  images[]@photo1.jpg \
  images[]@photo2.jpg \
  images[]@photo3.jpg \
  album="Vacation 2024"

Use Case 4: API Testing with Complex JSON

# Create user with nested profile data
http POST api.example.com/users \
  name="John Doe" \
  email="john@example.com" \
  profile:='{"age":30,"address":{"city":"NYC","zip":"10001"},"tags":["developer","python"]}' \
  settings:='{"notifications":true,"theme":"dark"}' \
  active:=true

# Alternative: Use file for complex JSON
cat > user_data.json <<EOF
{
  "name": "John Doe",
  "email": "john@example.com",
  "profile": {
    "age": 30,
    "address": {
      "city": "NYC",
      "zip": "10001"
    }
  }
}
EOF

http POST api.example.com/users < user_data.json

Use Case 5: Debugging API with Headers and Verbose Output

# View complete request and response
http -v POST api.example.com/debug \
  X-Request-ID:abc-123 \
  X-Debug:true \
  data="test payload"

# Check only headers for troubleshooting
http --print=Hh api.example.com/status

# Test with different user agents
http api.example.com/content \
  User-Agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64)" \
  Accept:"text/html,application/json"

# Debug redirects
http --follow --all --print=Hh api.example.com/redirect

Buenas prácticas

  • Use sesiones para pruebas de estado: Al probar puntos finales autenticados o flujos de trabajo que requieren cookies, utilice --session para persistir el estado entre las solicitudes en lugar de gestionar las fichas manualmente

  • ¿Qué? Pie asume JSON por defecto, por lo que puede omitir Content-Type_ encabezados y citas alrededor de valores simples (name=John en lugar de "name":"John"_)

  • Prefer pipx_ over pip para la instalación: Instalar con pipx aísla a HTTPie en su propio entorno, evitando conflictos de dependencia con otras herramientas de Python

  • Use llamado sesiones para diferentes ambientes: Crear sesiones separadas para el desarrollo, el estancamiento y la producción (--session=dev__, --session=prod_) para evitar accidentalmente golpear entornos erróneos

Guardar solicitudes complejas como scripts de shell: Para solicitudes complejas de uso frecuente, guardarlas como scripts de shell ejecutables con nombres descriptivos para fácil reutilización y documentación

  • Use --print_ banderas para CI/CD: En pruebas automatizadas, utilice --print=b para producir sólo el cuerpo de respuesta para un análisis más fácil, o --check-status para fallar en errores HTTP

  • ** Datos confidenciales de protocolo**: Nunca incluya contraseñas o claves de API directamente en los comandos que se han registrado; use http -a username (promptas para contraseña) o variables ambientales en su lugar

  • Use --timeout para producción: Siempre establece plazos razonables en scripts de producción para evitar solicitudes de colgantes (--timeout=30 es un buen defecto)

Troubleshooting

Issue Solution
INLINE_CODE_123 Ensure HTTPie is installed and in PATH. Try INLINE_CODE_124 or reinstall with INLINE_CODE_125
SSL certificate verification fails Use INLINE_CODE_126 to bypass (testing only), or INLINE_CODE_127 to provide custom CA bundle
Request hangs indefinitely Add INLINE_CODE_128 to set timeout. Check if endpoint is responding with INLINE_CODE_129 or browser first
JSON parsing error Ensure proper syntax: use INLINE_CODE_130 for raw JSON (INLINE_CODE_131), INLINE_CODE_132 for strings (INLINE_CODE_133). Check quotes in nested JSON
Session not persisting Verify session file location with INLINE_CODE_134. Ensure you're using same session name. Check file permissions on config directory
Form upload not working Use INLINE_CODE_135 flag for form data (INLINE_CODE_136). Use INLINE_CODE_137 for files (INLINE_CODE_138), INLINE_CODE_139 for text fields
Colors not displaying Check terminal supports colors. Set INLINE_CODE_140 explicitly or check INLINE_CODE_141 environment variable isn't set
Authentication fails Verify credentials format: INLINE_CODE_142 for Basic auth. For Bearer tokens use INLINE_CODE_143 header
Proxy connection issues Check proxy URL format: INLINE_CODE_144. Test proxy with curl first. Verify proxy credentials if required
Response too large / memory error Use INLINE_CODE_145 flag to stream response instead of buffering: INLINE_CODE_146
Cannot upload large files Use INLINE_CODE_147 for request streaming: INLINE_CODE_148
Headers not being sent Ensure header syntax uses INLINE_CODE_149 separator (INLINE_CODE_150). Check for typos. Use INLINE_CODE_151 to verify headers in request

Quick Referencia: Patrones comunes

** Parámetros de preguntas:**

http api.example.com/search q=="search term" page==1 limit==20

JSON Tipos de datos:**

http POST api.example.com/data \
  string_field="text" \
  number_field:=42 \
  boolean_field:=true \
  null_field:=null \
  array_field:='[1,2,3]' \
  object_field:='{"key":"value"}'

Headers

http api.example.com/api \
  Authorization:"Bearer token" \
  Content-Type:application/json \
  X-Custom-Header:value

** Operaciones financieras:**

# Upload
http -f POST api.example.com/upload file@document.pdf

# Download
http --download api.example.com/files/document.pdf

# Use file content as JSON
http POST api.example.com/config settings:=@config.json

Control de salida:

# Only response body
http -b api.example.com/users

# Only headers
http -h api.example.com/users

# Everything verbose
http -v api.example.com/users

# Save to file
http -o output.json api.example.com/users