TIL: Find the size of a response body using curl

Today I needed to inspect how large the body of one of our API end points was. My initial idea was to do this:

curl myurl.com/endpoint.json > endpoint.json  
ls -h endpoint.json  

Which worked. But I didn't want to keep the file in my filesystem just to get it's size. It turns out, curl can do it for you. curl's -w/--write-out flag allows you to display information on stdout about the request you just made. All you need to do is provide a string as an argument to this flag and include one or more of the variables curl provides for you. All variables are specified as %{variable_name} and you can find a list of these variables in curl's man page.

Armed with this new knowledge, my problem was easily solved with the following command (size_download is in bytes):

curl myurl.com/endpoint.json -w 'size: %{size_download}\n` -o /dev/null  

Notice, I set the output to to /dev/null so that the actual response doesn't get written to the screen. You can leave that out if you want to see the response body in addition to the size. I also appended a new line to separate the output of this command from my prompt.

Post written by Levi.