Curl write http code to stderr or to file

curl

I'm writing some scripts for testing an API. I'm interested in the JSON response as well as the HTTP status code of the request. I definitely want to pretty-print the JSON response in order to make it easier to read.

I'm using curl to perform the request and want to use python -m json.tool to pretty-print the json result.

Curl has a nice option -w that can be used to surface information about the request, like %{http_code}. Unfortunately, that information prints to stdout and confuses python -m json.tool. It seems it isn't possible to configure it to ignore trailing non-json data.

When I do

curl \
'--silent' \
'--insecure' \
'-L' \
'-w' \
'\n%{http_code}\n' \
'--user' \
<REDACTED> \
'-X' \
'GET' \
'--' \
'https://somecompany.com/some_api_endpoint' \
| python -m json.tool

I get

$ bash call_api_endpoint_script.sh 
Extra data: line 2 column 1 - line 3 column 1 (char 203 - 207)
Exit 1

Is there a way to configure curl to write the status code to a file? The -w option in the man page doesn't seem to mention the possibility of redirecting this information elsewhere.

Best Answer

$ curl -s -k -w '%{stderr}%{http_code}\n%{stdout}\n' \
  http://www.mocky.io/v2/5e13eae9310000598ad4792b |\
  tee /dev/stderr | jq -r '.name'
200
{
    "name": "Grape"
}
Grape

stderr From this point on, the -w, --write-out output will be written to standard error. (Added in 7.63.0)

stdout From this point on, the -w, --write-out output will be written to standard output. This is the default, but can be used to switch back after switching to stderr. (Added in 7.63.0)

Related Question