Scripting
When using HTTPie from shell scripts, it can be handy to set the—check-status
flag. It instructs HTTPie to exit with an error if theHTTP status is one of 3xx
, 4xx
, or 5xx
. The exit status willbe 3
(unless —follow
is set), 4
, or 5
,respectively.
- #!/bin/bash
- if http --check-status --ignore-stdin --timeout=2.5 HEAD example.org/health &> /dev/null; then
- echo 'OK!'
- else
- case $? in
- 2) echo 'Request timed out!' ;;
- 3) echo 'Unexpected HTTP 3xx Redirection!' ;;
- 4) echo 'HTTP 4xx Client Error!' ;;
- 5) echo 'HTTP 5xx Server Error!' ;;
- 6) echo 'Exceeded --max-redirects=<n> redirects!' ;;
- *) echo 'Other Error!' ;;
- esac
- fi
Best practices
The default behaviour of automatically reading stdin
is typically notdesirable during non-interactive invocations. You most likely want touse the —ignore-stdin
option to disable it.
It is a common gotcha that without this option HTTPie seemingly hangs.What happens is that when HTTPie is invoked for example from a cron job,stdin
is not connected to a terminal.Therefore, rules for redirected input apply, i.e., HTTPie starts to read itexpecting that the request body will be passed through.And since there's no data nor EOF
, it will be stuck. So unless you'repiping some data to HTTPie, this flag should be used in scripts.
Also, it might be good to set a connection —timeout
limit to preventyour program from hanging if the server never responds.