Missing API file error on AJAX call

Hi,

I've been struggling with the v10 AJAX framework in Sugar 7.6 and I've got it nearly there I think.

Having tackled authentication, and a number of other problems, I'm stuck with it stating my GET request has a "Missing API File" with a 400 error.

Looking in the console, the URL looks right to me by going to: http://%MY LOCAL SITE%/rest/v10/Accounts/VatCheck?vatReg=123&countryCode=GB

The full object returned by the error in the AJAX is:

readyState: 4,

responseText: "{"error":"unknown_exception","error_message":"Missing API file."}", status: 400, statusText: "Bad Request"}

My code is as follows:

custom/modules/Accounts/clients/base/views/record.js

({
    // Extends from RecordView
    extendsFrom: 'AccountsRecordView',


    initialize: function(options) {
        this._super('initialize', [options]);
  console.log('Custom Record JS in use.');
    },

  saveClicked: function(callback) {
  console.log('save was clicked');


  var vatRegNumber = document.getElementsByName('vat_reg_number_c')[0].value;        
  var countryCodeValue = document.getElementsByName('country_code_c')[0].value;


  console.log("Preparing the Ajax Call");


  $.ajax
  ({
  beforeSend: function (request)
  {
  request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());
  },
  url: "rest/v10/Accounts/VatCheck",
  type: "GET",
  contentType: "application/json",
  data: { "vatReg" : vatRegNumber , "countryCode" : countryCodeValue },
  dataType: "json",
  success: function(data)
  {
  console.log("AJAX Call successful");
  console.log(data);
  if (data.success == 1)
  {
  console.log("Result succeeded");
  }
  else
  {
  app.alert.show('test', {
  level: 'error',
  title: 'Error:',
  messages: data.error,
  });
  }
  },
  error: function (xhr, ajaxOptions, thrownError) {
  console.log(xhr);
  console.log(ajaxOptions);
  console.log(thrownError);
  }
  });
    },
})

custom/modules/Accounts/clients/base/api/VatCheck.php

<?php


require_once 'include/api/SugarApi.php';

class VatCheck extends SugarApi
{

    public function registerApiRest() 
  {
        return array(
            'VatCheck' => array(
                'reqType' => 'GET',
                'path' => array('Accounts', 'VatCheck'),
                'pathVars' => array('vatReg', 'countryCode'),
                'method' => 'checkVatCode',
                'shortHelp' => 'Returns whether the VAT code entered is valid',
                'longHelp' => '',
            ),
        );
    }



  public function checkVatCode($api,$args)
  {
  global $db;


  $sql = "call AA_CHECK_VAT_NUMBER_S ('?','?')";


  $params = array($_REQUEST["vatReg"], $_REQUEST["countryCode"]);
   
  $result = $db->pQuery($sql, $params);


  $row = $db->fetchByAssoc($result);


  if ($row)
  {
  $json = array( 'success' => $row['LS_Success'], 'code' => $row['PS_VAT_Number'], 'error' => $row['errorMessage']);


  return json_encode($json);
  }
  else
  {
  return $db->lastDbError();
  }
  }
}
?>

I hope someone can point out where I've likely just done something silly here. I've had to make some changes for where it was working in 6.5 using a custom entry point.

Parents
  • Hi Richard,

    I am not sure,I understood your question correctly,If you are trying to call api in js.

    you should try call like below,

    app.api.call('GET', app.api.buildURL("Accounts/VatCheck/+vatRegNumber+/+countryCodeValue"),null,{
        success :function (data){
            console.log("api responded");
    },
    });
    

    Then your api return array will look like this    

     return array(  
                'getAtRisk' => array(  
                    'reqType' => 'GET',  
                    'path' => array('Accounts', 'VatCheck','?','?'),  
                    'pathVars' => array('','','vatReg', 'countryCode'),  
                    'method' => 'checkVatCode',  
                    'shortHelp' => 'Returns whether the VAT code entered is valid',  
                    'longHelp' => '',  
                ), 
    

    these varReg and countrycode variables you will be able to access by $args['vatReg'] and $args['countryCode'] in api method(checkVatCode).

    Hope it helps!.

  • Hi Ajay,

    Yes, I realised a couple of things. I have made a few modifications to my code as per your suggestions, but I still get the same error.

    I changed my Requests to reference the args variable:

         $params = array($args["vatReg"], $args["countryCode"]);

    I also changed the number of arguments in the methods:

         'path' => array('Accounts', 'VatCheck','?','?'),

         'pathVars' => array('','','vatReg', 'countryCode'),

    I modified your suggestion for the method as per this:

         call('GET', app.api.buildURL("Accounts/VatCheck/"+vatRegNumber+"/"+countryCodeValue)

  • Make sure your api is getting called by printing something to log.Can you paste code that you tried.

    Hope you could have given repair and rebuild.

  • Thanks Ajay,

    I think I've got it working. I think I'd excluded the setRequestHeader, so I suppose it wasn't authenticating.

    I think my main problems were solved by my misunderstanding of the routes, and the path Vars.

    Here is my final code:

    record.js

    ({
        // Extends from RecordView
        extendsFrom: 'AccountsRecordView',
    
    
        initialize: function(options) {
            this._super('initialize', [options]);
      console.log('Custom Record JS in use.');
        },
    
      saveClicked: function(callback) {
      console.log('save was clicked');
    
    
      var vatRegNumber = document.getElementsByName('vat_reg_number_c')[0].value;        
      var countryCodeValue = document.getElementsByName('country_code_c')[0].value;
    
    
      console.log("Preparing the Ajax Call to " + app.api.buildURL("Accounts/VatCheck/"+vatRegNumber+"/"+countryCodeValue));
      app.api.call('GET', app.api.buildURL("Accounts/VatCheck/"+vatRegNumber+"/"+countryCodeValue),null,{  
      beforeSend: function (request)  
      {  
       request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());  
      },  
      success :function (data)
      {  
      data = JSON.parse(data);
      console.log("AJAX Call successful");
      console.log(data);
      if (data.valid == 1)
      {
      console.log("Result is valid");
      }
      else
      {
      app.alert.show('ErrorVAT', {
      level: 'error',
      title: 'Error:',
      messages: data.error,
      });
      }
      },  
      error: function (xhr, ajaxOptions, thrownError) {
      console.log(xhr);
      console.log(ajaxOptions);
      console.log(thrownError);
      }
      });  
        },
    })
    

    VatCheck.php

    <?php
    
    
    require_once 'include/api/SugarApi.php';
    
    class VatCheck extends SugarApi
    {
    
        public function registerApiRest() 
      {
            return array(
                'VatCheck' => array(
                    'reqType' => 'GET',
                    'path' => array('Accounts', 'VatCheck','?','?'),
                    'pathVars' => array('','','vatReg', 'countryCode'),
                    'method' => 'checkVatCode',
                    'shortHelp' => 'Returns whether the VAT code entered is valid',
                    'longHelp' => '',
                ),
            );
        }
    
    
    
      public function checkVatCode($api,$args)
      {
      global $db;
    
    
      $sql = "call AA_CHECK_VAT_NUMBER_S ('?','?')";
    
    
      $params = array($args["vatReg"], $args["countryCode"]);
       
      $result = $db->pQuery($sql, $params);
    
    
      $row = $db->fetchByAssoc($result);
    
    
      if ($row)
      {
      $json = array( 'valid' => $row['LS_Success'], 'code' => $row['PS_VAT_Number'], 'error' => $row['errorMessage']);
    
    
      return json_encode($json);
      }
      else
      {
      return $db->lastDbError();
      }
      }
    }
    ?>
    
Reply
  • Thanks Ajay,

    I think I've got it working. I think I'd excluded the setRequestHeader, so I suppose it wasn't authenticating.

    I think my main problems were solved by my misunderstanding of the routes, and the path Vars.

    Here is my final code:

    record.js

    ({
        // Extends from RecordView
        extendsFrom: 'AccountsRecordView',
    
    
        initialize: function(options) {
            this._super('initialize', [options]);
      console.log('Custom Record JS in use.');
        },
    
      saveClicked: function(callback) {
      console.log('save was clicked');
    
    
      var vatRegNumber = document.getElementsByName('vat_reg_number_c')[0].value;        
      var countryCodeValue = document.getElementsByName('country_code_c')[0].value;
    
    
      console.log("Preparing the Ajax Call to " + app.api.buildURL("Accounts/VatCheck/"+vatRegNumber+"/"+countryCodeValue));
      app.api.call('GET', app.api.buildURL("Accounts/VatCheck/"+vatRegNumber+"/"+countryCodeValue),null,{  
      beforeSend: function (request)  
      {  
       request.setRequestHeader("OAuth-Token", SUGAR.App.api.getOAuthToken());  
      },  
      success :function (data)
      {  
      data = JSON.parse(data);
      console.log("AJAX Call successful");
      console.log(data);
      if (data.valid == 1)
      {
      console.log("Result is valid");
      }
      else
      {
      app.alert.show('ErrorVAT', {
      level: 'error',
      title: 'Error:',
      messages: data.error,
      });
      }
      },  
      error: function (xhr, ajaxOptions, thrownError) {
      console.log(xhr);
      console.log(ajaxOptions);
      console.log(thrownError);
      }
      });  
        },
    })
    

    VatCheck.php

    <?php
    
    
    require_once 'include/api/SugarApi.php';
    
    class VatCheck extends SugarApi
    {
    
        public function registerApiRest() 
      {
            return array(
                'VatCheck' => array(
                    'reqType' => 'GET',
                    'path' => array('Accounts', 'VatCheck','?','?'),
                    'pathVars' => array('','','vatReg', 'countryCode'),
                    'method' => 'checkVatCode',
                    'shortHelp' => 'Returns whether the VAT code entered is valid',
                    'longHelp' => '',
                ),
            );
        }
    
    
    
      public function checkVatCode($api,$args)
      {
      global $db;
    
    
      $sql = "call AA_CHECK_VAT_NUMBER_S ('?','?')";
    
    
      $params = array($args["vatReg"], $args["countryCode"]);
       
      $result = $db->pQuery($sql, $params);
    
    
      $row = $db->fetchByAssoc($result);
    
    
      if ($row)
      {
      $json = array( 'valid' => $row['LS_Success'], 'code' => $row['PS_VAT_Number'], 'error' => $row['errorMessage']);
    
    
      return json_encode($json);
      }
      else
      {
      return $db->lastDbError();
      }
      }
    }
    ?>
    
Children
No Data