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

12,139

Solution 1

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")

Solution 2

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 ).

Share:
12,139
shekoufeh
Author by

shekoufeh

Updated on June 04, 2022

Comments

  • shekoufeh
    shekoufeh almost 2 years

    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.

  • shekoufeh
    shekoufeh over 6 years
    good solution. but I've already found that if I want to keep the base url (the ulr which is requested by the user) I can't use the .htaccess file for redirection!! So, how can I force every requested url to be checked by the API using a php file?
  • BSB
    BSB over 6 years
    @shekoufeh you can use above code before routing or in index.php before other codes. Place condition accordingly
  • shekoufeh
    shekoufeh over 6 years
    I just want to do it whenever a video file is requested. there is no php file. I' really confused in this part...