Textus
Textus

Reputation: 109

How to make a JSON Curl request to an api url, getting null

This should be simple I think but I just can't fathom it.

I need to make a request to a url in the following format:

http://ratings.api.co.uk/business/{lang}/{fhrsid}/{format} where lang will be set to en-GB the fhrsid is an identifier and format is json.

I tried the following but I am just getting null in return:

$data = array("lang" => "en-GB", "fhrsid" => "80928");                                                                    
$data_string = json_encode($data);            


$ch = curl_init('http://ratings.api.co.uk/business/json');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))                                                 );                                                                                                                   

$Jsonresult = curl_exec($ch);
curl_close($ch);

var_dump(json_decode($Jsonresult));

Any help gratefully received

Upvotes: 1

Views: 2203

Answers (2)

Kristian
Kristian

Reputation: 21840

Sending data as arguments is different than sending it within the URL.

If you require a url format of http://ratings.api.co.uk/{lang}/{fhrsid}/{format}, then you must make your curl_init string match that format.

Upvotes: 2

Sjoerd
Sjoerd

Reputation: 75679

You are currently posting the data to the URL, while you say you want to put the data in the URL itself.

I.e. now you submit {"lang:"en-GB","fhrsid":80928} to the URL http://ratings.api.co.uk/business/json, but instead you want to retrieve the URL http://ratings.api.co.uk/business/en-GB/80928/json.

Don't use POST as request type, don't specify postfields, don't specify content-length, and do put the data in your URL.

Upvotes: 2

Related Questions