Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL Post request: get response and status code

Tags:

curl

I make a cURL request using:

PATCH=$(curl -i -F file=@$FILE -F path="${STORAGE_PATH}" -F name="${NAME}" -F description="${DESC}" "${SERVER}/api/patches")

If the response goes through and the data is property formatted, then PATCH would be a JSON of the response.

I also want to get the HTTP response code (like 200, 422) at the same time, so I can verify that the process went through.

how do I do that? I just want to get a number (like 200).

like image 700
Kousha Avatar asked Mar 24 '15 21:03

Kousha


2 Answers

I used this post to solve my problem and thought I'd share my results. My goal was to create a script to make sure my accesstoken endpoint was working. So I had to make a POST call and extract the response code, here was my end result:

status=$(curl -w "%{http_code}\\n" -H "Accept:application/json" -H "Content-Type:application/x-www-form-urlencoded" --data "client_id=blah&client_secret=blah&grant_type=password&user_name=user&password=pass" https://api.company.com/v1/accessToken -s -o /dev/null)

Explanation

  • status=$({curlRequest}) will store the output into a bash variable
  • -w will extract the status code from the response
  • -H configures my HTTP header request
  • --data sets the payload data that I want to POST (this flag also automatically sets the request to POST
  • -s will silence progress meter of the request
  • -o this will extract the response body and put it into a file. By setting the value to /dev/null, the output is discarded

The key values here are -w and -o if you only want a response code. Remove the -o flag to keep the response body.

like image 135
Cyrois Avatar answered Oct 14 '22 17:10

Cyrois


You can use:

PATCH=$(curl -L -w "%{http_code} %{url_effective}\\n" -X POST -d @filename.txt ${server}/api/patches --header "Content-Type:application/json")

It will give you both the response code and body.

like image 25
Saket Saurabh Avatar answered Oct 14 '22 17:10

Saket Saurabh