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.

  1. #!/bin/bash
  2.  
  3. if http --check-status --ignore-stdin --timeout=2.5 HEAD example.org/health &> /dev/null; then
  4. echo 'OK!'
  5. else
  6. case $? in
  7. 2) echo 'Request timed out!' ;;
  8. 3) echo 'Unexpected HTTP 3xx Redirection!' ;;
  9. 4) echo 'HTTP 4xx Client Error!' ;;
  10. 5) echo 'HTTP 5xx Server Error!' ;;
  11. 6) echo 'Exceeded --max-redirects=<n> redirects!' ;;
  12. *) echo 'Other Error!' ;;
  13. esac
  14. 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.