Naveen Prasath
Naveen Prasath

Reputation: 59

How to post JSON body and header to RESTFUL API in php?

Kindly help me with, how to post JSON Body and header to RESTFUL API in php? of following data.

 HTTP POST url : http://webapi.test.com/Bus/BlockSeat
 ConsumerKey : KEY
 ConsumerSecret: SECRETKEY

 bODY(json) : {"IsOfflineBooking": "false",
"TripId": "5927-0",
"BoardingId": "6",
"NoofSeats": "1",
"Fares": "717.5",
"SeatNos": "R5",
 "Titles": "Mr",
 "Names": "vijaykumar",
 "Ages": "27",
 "Genders": "M",
 "Address": "hyderabad",
 "UserType": "5",
 "Servicetax": "0"} 

Kindly help with solving my problem.

Upvotes: 1

Views: 2772

Answers (1)

Thibault Henry
Thibault Henry

Reputation: 841

Here is your code, using CURL :

$body = json_encode(array(
    "IsOfflineBooking" => "false",
    "TripId" => "5927-0",
    "BoardingId" => "6",
    "NoofSeats" => "1",
    "Fares" => "717.5",
    "SeatNos" => "R5",
    "Titles" => "Mr",
    "Names" => "vijaykumar",
    "Ages" => "27",
    "Genders" => "M",
    "Address" => "hyderabad",
    "UserType" => "5",
    "Servicetax" => "0"
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://webapi.test.com/Bus/BlockSeat");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                        
    'Content-Length: '.strlen($body)                                                                              
    'ConsumerKey: '.KEY,
    'ConsumerSecret: '.SECRETKEY                                                                        
));  

$output = curl_exec($ch);

curl_close($ch);

And do what you want with the respons in $output

Upvotes: 1

Related Questions