v10 REST API Javascript

Hello Everyone,

I am working on the SugarCRM 7.7 and I need help for V10 Rest Api. I have searched for it and found useful link on SugarCRM Suport as below.

https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.7/Integration/Web_Services/v10

In above link we are able to make API call through CURL.

What I need actually is Javascript Class or any JS source through which I able to make V10 Rest API call.

So is there any JS class or any source in which Rest API is working with Javascript ?

Any help is appreciated.

  • Hi Stephen,

    This is common question about REST. Rest actually does not related to platform. You can use with any programming language as long as you can request on internet.

    I assume you are going to develop something inside of the sugar. You can make API calls with this code block that i shared in another post (See: app.api.call and buildUrl Filter list of results in v7.6.1);

    var url = app.api.buildURL("Accounts", null, null, {  
        //user this part if you need to define filters
        // "filter": [{  
        //     "psc": "3"  
        // }]  
    });  
      
      
    app.api.call('read', url, null, {  
        success: _.bind(function(response) {  
            // here is your success code  
            console.log("Response", response)  
        }, this),  
        error: _.bind(function(error) {  
            // here is your error code  
            console.log("Error", error)  
        }, this),  
    });
    

    But if your implementation outside of Sugar, you would need to make a simple post call to /oauth2/token POST end point using AJAX(such as jQuery; $.ajax() ) and then use the token you receive in all other rest calls.

    Hope this makes clear on your mind.

    Best Regards

    Tevfik Tümer

    Developer Support Engineer

  • Hi Tevfik,

    Thanks for your reply.

    I implement REST API outside of Sugar. Once I used  /oauth2/token and it gives me access_token and refresh_token. But access_token will expired after sometime then through JS, how can we identify that the token is expired. Should we check that the token is still valid or not before every ajax call ? Or else there is any JS Class which automatically takes care of token as we make REST ajax call for record create or fetch ?

    I am not visualize things largely thats why asking this question.

    Again thanks for your help and time.

  • Hi Stephen,

    Almost all the apps work with rest simply have this algorithm;

    1. Check Access token

    1.1. If there is already a token use it

    1.2. If there is no token then grant Access token

    2. Make Api Call

    2.1. On Success, Render

    2.2. On Error

    2.2.1. If it fails due to token, return step 1.2

    2.2.2. If it is some other reason, show a message

    So simply, you would need to make your oauth/token call. Then use it in your api call. If your api call gives an error, like 401;

    {"error":"invalid_grant","error_message":"The access token provided is invalid."}
    

    You can check the error in your error:function() of your API Call. If error == "invalid_grant" then you can repeat the steps from granting the access.

    Hope this make sense.

    Let me know, if you have any more question about this.

    Best Regards

    Tevfik Tümer

    Developer Support Engineer

  • Hi Tevfik,

    Thanks for your detailed information. Will work with steps you have mentioned. Need another guidance/help for finding records with email address. Previously we can search with the "search_by_module" method with the selected module. How can we do this search with 7X version. I need records find from different modules with the Email Address.

    Again Thanks.

  • Hi Tevfik,

    While implement the v10 REST API, I need to search the records from different modules which has same Email Address. Is there a way to find records from different modules with the same Email Address ?

    Thanks.

  • Hi Stephen,


    Try like this;

    var url = app.api.buildURL("Leads", null, null, {    
        //user this part if you need to define filters 
        "filter": [{   
            "$or":[{
                "email1": "info.hr@example.tv"
            },
            {
                "email2": "info.hr@example.tv"
            }]
        }]   
    });   
       
       
    app.api.call('read', url, null, {   
        success: _.bind(function(response) {   
            // here is your success code   
            console.log("Response", response)   
        }, this),   
        error: _.bind(function(error) {   
            // here is your error code   
            console.log("Error", error)   
        }, this),   
    }); 

    Best Regards
    Tevfik Tümer
    Developer Support Engineer

  • Hi,

    I am trying to call  /oauth2/token POST endpoint from outside Javascript. I am not able to go through. From the Postman it works fine but there is not Same Origin Policy applied so it works fine. 

    I have simple ajax call where I am adding CORS headers but in the debugger, I can still see that I got back 404 with the message the OPTIONS 

    I am including snippets of my code

    function setRequestHeaders(xhr) {
      xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
      xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
      xhr.setRequestHeader(
        'Access-Control-Allow-Headers',
        'Content-Type, Origin, X-Auth-Token'
      );


    }


    ..
        const payload = {
          grant_type: 'password',
          client_id: 'sugar',
          client_secret: '',
          username: 'username',
          password: 'password',
          platform: ''
        };
        const token = this.postCall(
          'https://squmrdxxxxxx.trial.sugarcrm.eu/rest/v10/oauth2/token',
          'POST',
          payload
        );
        token.then(result => {
          Log.debug(TAG, result);
        });



    postCall(url, payload = {}) {

        Log.debug(TAG, 'postCall()', url, payload, 'going to send ');
        const ajaxPromise = $.ajax({
          url,
          type: 'POST',
          dataType: 'json',
          contentType: 'application/json',
          traditional: true,
          data: payload,
          beforeSend: xhr => {
            setRequestHeaders(xhr);
          }
        });

        return new EmberPromise((resolve, reject) => {
          ajaxPromise
            .then(result => {
              Log.debug(TAG, 'postCall in the Promise', result);
              resolve(result);
            })
            .catch(error => {
              Log.debug(TAG, 'catch error', error);
            });
        });
      }

    When I call this code I can see in the Chrome debugger I can see that the request method OPTIONS returns 404.

    The browser calls at the OPTIONS and then it should call POST. But I always get back 404

    In the Firefox debug console I can see a message but I am setting these headers. 

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://squmrd7363.trial.sugarcrm.eu/rest/v10/oauth2/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

     

    I tried to find some example how to call it from javascript but I didn't find anything.

     

    Do you think you can give me some hints? 

     

    thanks

     

    Pavel