Search code examples
bashhttpie

How to capture actual response code and response body with HTTPie in bash script?


I have a bash script to call several APIs using HTTPie. I want to capture both the response body AND the HTTP status code.

Here is the best I have managed so far:

rspBody=$( http $URL --check-status --ignore-stdin )
statusCode=$?

Command substitution lets me get the body, and the "--check-status" flag gives me a simplified code (such as 0, 3, 4, etc) corresponding to the code family.

The problem is I need to distinguish between say a 401 and a 404 code, but I only get 4.

Is there a way to get the actual status code without having to do a verbose dump into a file and parse for stuff?

[edit]

This is my workaround in case it helps anyone, but I'd still like a better idea if you have one:

TMP=$(mktemp)
FLUSH_RSP=$( http POST ${CACHE_URL} --check-status --ignore-stdin 2> "$TMP")
STAT_FAMILY=$?

flush_err=$(cat "$TMP" | awk '{
  where = match($0, /[0-9]+/)
  if (where) {
    print substr($0, RSTART, RLENGTH);
  }
}' -)
rm "$TMP"

STDERR contains a (usually) 3-line message with the HTTP code in it, so I dump that to a temp file and am still able to capture the response body (from STDOUT) in a variable.

I then parse that temp file looking for a number, but this seems fragile to me.


Solution

  • There's no ready-made solution as such for this but it's achievable with a bit of scripting. For example:

    STATUS=$(http -hdo ./body httpbin.org/get 2>&1 | grep HTTP/  | cut -d ' ' -f 2)
    BODY=$(cat ./body)
    rm ./body
    echo $STATUS
    # 200
    echo $BODY
    # { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "identity", "Host": "httpbin.org", "User-Agent": "HTTPie/1.0.0-dev" }, "origin": "84.242.118.58", "url": "http://httpbin.org/get" }
    

    Explanation of the command:

    http --headers \               # Print out the response headers (they would otherwise be supressed for piped ouput)
         --download \              # Enable download mode
         --output=./body  \        # Save response body to this file
         httpbin.org/get 2>&1 \    # Merge STDERR into STDOUT (with --download, console output otherwise goes to STDERR)
         | grep HTTP/  \           # Find the Status-Line
         | cut -d ' ' -f 2         # Get the status code
    

    https://gist.github.com/jakubroztocil/ad06f159c5afbe278b5fcfa8bf3b5313