shekoufeh
shekoufeh

Reputation: 639

how to call an api via php and get a json file from it

I want to check all of the requested urls and if the url contains "video" folder in it, redirect it to an API file. then the API gives me a json files which only contains "respond:true" or "respond:false". In case of having respond:true in the json file the url must be showed and if the json file contains respond:false a predefined simple 403 page must be showed to the user.

I know that the fist part is possible with a simple code in .htaccess file like this:

RewriteRule ^your/special/folder/ /specified/url [R,L]

But I don't know how to do the second part. I mean how to get the result of API, which is in form of a json file and check it.

Upvotes: 4

Views: 23028

Answers (2)

BSB
BSB

Reputation: 2468

You can execute second part (Calling API and response): Call API using curl and process based on its response:

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_POST, false);
 curl_setopt($ch, CURLOPT_URL, "api_url_here");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $api_response_json = curl_exec($ch);
 curl_close($ch);
 //convert json to PHP array for further process
 $api_response_arr = json_decode($api_response_json);

 if($api_response_arr['respond'] == true ){
    //code for success here
 }else{
    // code for false here
 }

Please note: Json response from API is depend on API Response, If API is giving response in json format ( can be based on params also ).

Upvotes: 1

M Arfan
M Arfan

Reputation: 4575

You can use CURL..

GET REQUEST

$url = 'http://example.com/api/products';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_json = curl_exec($ch);
curl_close($ch);
$response=json_decode($response_json, true);

POST REQUEST

    $postdata = array(
        'name' => 'Arfan'
    );

    $url = "https://example.com/api/user/create";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);

    $json_response = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

You can also use file_get_content to get API data.

$json = file_get_contents("$url")

Upvotes: 11

Related Questions