Saltar al contenido principal

Clase 01 — Métodos HTTP con curl

Los métodos HTTP

MétodoAcciónIdempotenteBody
GETObtener datos✅ Sí❌ No
POSTCrear recurso❌ No✅ Sí
PUTReemplazar recurso✅ Sí✅ Sí
PATCHActualizar parcial❌ No✅ Sí
DELETEEliminar recurso✅ SíOpcional
HEADSolo headers (sin body)✅ Sí❌ No
OPTIONSMétodos permitidos✅ Sí❌ No

GET — Obtener datos

# GET es el método por defecto
curl -s https://httpbin.org/get | jq '.'

# Con query parameters
curl -s "https://httpbin.org/get?nombre=Ana&edad=28" | jq '.args'

# Codificar parámetros automáticamente
curl -s -G \
--data-urlencode "query=nombre con espacios" \
https://httpbin.org/get | jq '.args'

GET con PokéAPI

curl -s https://pokeapi.co/api/v2/pokemon/pikachu | jq '{
id: .id, nombre: .name,
tipos: [.types[].type.name],
peso_kg: (.weight / 10)
}'

# Lista paginada
curl -s "https://pokeapi.co/api/v2/pokemon?limit=5" | jq '.results[].name'

POST — Crear recursos

# POST con JSON
curl -s -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-d '{"nombre": "Ana", "rol": "DevOps"}' | jq '.json'

# POST desde archivo
curl -s -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-d @/tmp/datos.json | jq '.json'

# POST con form data
curl -s -X POST https://httpbin.org/post \
-d "nombre=Ana" -d "edad=28" | jq '.form'

-d vs --data-raw vs --data-binary

# -d: Envía datos (quita newlines)
# --data-raw: Igual que -d pero no interpreta @
# --data-binary: Preserva newlines
# --data-urlencode: Codifica los datos

PUT — Reemplazar recurso completo

curl -s -X PUT https://httpbin.org/put \
-H "Content-Type: application/json" \
-d '{"id": 1, "nombre": "Ana García", "rol": "Senior DevOps"}' | jq '.json'

PATCH — Actualización parcial

curl -s -X PATCH https://httpbin.org/patch \
-H "Content-Type: application/json" \
-d '{"rol": "Lead DevOps"}' | jq '.json'

PUT vs PATCH

# PUT → Enviar TODO el objeto (reemplaza)
curl -X PUT https://api.com/users/1 \
-d '{"nombre":"Ana","email":"ana@dev.com","rol":"DevOps","activo":true}'

# PATCH → Enviar SOLO lo que cambia
curl -X PATCH https://api.com/users/1 \
-d '{"rol":"Lead DevOps"}'

DELETE — Eliminar recurso

curl -s -X DELETE https://httpbin.org/delete | jq '.url'

# DELETE con body (algunos APIs lo requieren)
curl -s -X DELETE https://httpbin.org/delete \
-H "Content-Type: application/json" \
-d '{"reason": "Recurso obsoleto"}' | jq '.json'

HEAD — Solo headers

# Ver headers sin descargar el body
curl -I https://httpbin.org/get

# Verificar si un archivo existe sin descargarlo
curl -sI https://releases.ubuntu.com/22.04/ubuntu-22.04-live-server-amd64.iso | head -1

OPTIONS — Métodos permitidos

curl -s -X OPTIONS https://httpbin.org/get -i | grep -i "allow"

Códigos de estado HTTP

# 2xx Éxito: 200 OK, 201 Created, 204 No Content
# 3xx Redirección: 301 Moved, 302 Found, 304 Not Modified
# 4xx Error cliente: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Rate Limit
# 5xx Error servidor: 500 Internal, 502 Bad Gateway, 503 Unavailable, 504 Timeout

for code in 200 201 301 404 500; do
status=$(curl -s -o /dev/null -w "%{http_code}" "https://httpbin.org/status/$code")
echo "Pedido: $code → Recibido: $status"
done

Ejemplo: CRUD completo

#!/bin/bash
BASE="https://httpbin.org"

echo "=== CREATE (POST) ==="
curl -s -X POST "$BASE/post" \
-H "Content-Type: application/json" \
-d '{"id":1,"nombre":"Pikachu","tipo":"electric"}' | jq '.json'

echo "=== READ (GET) ==="
curl -s "$BASE/get?id=1" | jq '.args'

echo "=== UPDATE (PUT) ==="
curl -s -X PUT "$BASE/put" \
-H "Content-Type: application/json" \
-d '{"id":1,"nombre":"Raichu","tipo":"electric","nivel":36}' | jq '.json'

echo "=== PARTIAL UPDATE (PATCH) ==="
curl -s -X PATCH "$BASE/patch" \
-H "Content-Type: application/json" \
-d '{"nivel":42}' | jq '.json'

echo "=== DELETE ==="
curl -s -X DELETE "$BASE/delete" \
-H "Content-Type: application/json" \
-d '{"id":1}' | jq '.json'

Ejercicios

  1. Hacé una petición GET a PokéAPI y extraé nombre, tipos y stats
  2. Usá POST para enviar un JSON a httpbin y verificá que los datos llegaron
  3. Demostrá la diferencia entre PUT y PATCH usando httpbin
  4. Creá un script que haga peticiones a todos los métodos y muestre el código HTTP