Can I use curl to execute an API and download the returned image in a single operation?

It is not possible to perform both operations in a single command, since curl can only write the contents of the response object while the URL to the transformed image is embedded inside the Response object. However, using a utility called "jq" it is possible to pipe the Response object to jq which can then, extract the url and execute a second curl command to download the transformed image.
 
Here is shell script that lists all files with .jpg, .jpeg or .png format in the current directory, runs /removebg on each entry in the list and pipes the output to jq which parses the url from the output. The second curl command fetches the transformed image and saves it to a local file. 
apikey = "Your API key goes here"
for entry in `ls *.{jpg,jpeg,png}` do echo "$entry" url=`curl -X 'POST' \ 'https://api.picsart.io/tools/1.0/removebg' \ -H 'accept: application/json' \ -H 'X-Picsart-API-Key:'$apikey \ -H 'Content-Type: multipart/form-data' \ -F 'image=@'$entry \ -F 'output_type=cutout' \ -F 'format=JPG' | jq -r .data.url` echo $url `curl -o output/$entry"_picsart_removebg.jpg" $url` done
 
Was this article helpful?