Curl | How to test a Restful web service using curl

Author - Rita

Let’s consider, we have a demo Restful service (created in Java Spring here but you can create in any language) to login user which accepts username and password as input and returns Success/Failure in response.

Request Object : Demo Login Request class :

Response Object :

Here is how to call it in curl :

$service_url = 'type complete service url here’';
$curl = curl_init ( $service_url );
$loginRequest = array 
(
'username' => ‘enter username here’,
'password' => ‘enter password here’,
); // input php array 
$data_string = json_encode ( $loginRequest ); // convert php array to json 
						
$options = array (
                   CURLOPT_RETURNTRANSFER => true,
                   CURLOPT_HTTPHEADER => array 
  (
   'Content-type: application/json' 
  ) 
                );
curl_setopt_array ( $curl, $options );						
curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data_string );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curl, CURLOPT_HTTPHEADER, 

array (
       'Content-Type: application/json',
       'Content-Length: ' . strlen ( $data_string ) 
       ) 
$response_json = curl_exec ( $curl );
$response = json_decode($response_json ,true);
print_r($response); // you get response object in json format in response.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *