Search code examples
wordpressrestfile-get-contentswordpress-rest-api

401 error trying to access WP custom endpoint using file_get_contents


I have set up a custom endpoint as so:

function xyz_property_api_route() {
    register_rest_route('xyz/v1', 'property/(?P<slug>[a-zA-Z0-9-]+)', array(
        'methods' => 'GET',
        'callback' => 'get_property_by_slug',
        'permission_callback' => '__return_true'
    ));
}

When I visit the URL directly I get correct JSON output.

However, I have a script on a non WordPress site that I need to access that URL but I get the following error:

( ! ) Warning: file_get_contents(http://my-site-here.com/wp-json/xyz/v1/property/property_slug): Failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in my-script.php on line 8
Call Stack
#   Time    Memory  Function    Location
1   0.0015  422960  {main}( )   .../my-script.php:0
2   0.0015  423072  file_get_contents( $filename = 'hhttp://my-site-here.com/wp-json/xyz/v1/property/property_slug' )   .../my-script.php:8
API Request Failed

This is my script:

<?php
    $property_slug = $_GET['property'];

    // Construct the API URL using the property slug
    $api_url = 'http://my-site-here.com/wp-json/xyz/v1/property/' . $property_slug;

    // Fetch data from the API
    $response = file_get_contents($api_url);

    if ($response !== false) {
        $data = json_decode($response, true);
        if (!empty($data)) {
            echo "GOT STUFF";
        } else {
            echo "NOT GOT STUFF";
        }
    } else {
        echo "API Request Failed";
    }
?>

Any thoughts on this?

Thanks, Neil


Solution

  • Here's a basic cURL that Postman will provide you if you try it in that application

    <?php
      $property_slug = $_GET['property'];
    
      // Construct the API URL using the property slug
      $api_url = 'http://my-site-here.com/wp-json/xyz/v1/property/' . $property_slug;
        
      $curl = curl_init();
    
      curl_setopt_array($curl, array(
        CURLOPT_URL => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
      ));
    
      $response = curl_exec($curl);
      $err = curl_error($curl);
    
      curl_close($curl);
    
      if ($err) {
        echo "cURL Error #:" . $err;
      } else {
        $result = json_decode($response);
        echo '<pre>';
        print_r($result);
        echo '</pre>';
      }
    ?>