Python requests - invalid paramaters on POST request for record list

Hiya,

I have split this up into what I am trying to do and the issue it's self  for people who wanna jump straight to the issue or want to read on what I

am trying to do first.

what I am trying to do:

I have been recently making a program for our work to intergrate our product stock to our website from crm, upon searching around in SugarCRM I noticed a convinient tool that allowed us to export all of our products (ProductTemplates) into an excel file through a POST request, I replicated this post request in python requests which worked great however I was confused when it all of a sudden didn't work to find that the link (specifically the ID) of the document kept changing, upon seeing this I re analysed for different options and noticed there was a POST request for a "record list" for all of our products which contains requests paramaters for a set of ID's (which I am guessing are sets of products) which returns from the server a single ID to export the excel file

the issue:

The Issue I am having is that when I try to use a post request to get the "record_list" which contains the Main ID needed to get all of our product templates to export them I get the error "No valid authentication for user" even when I have provided the cookie that was given at the time of logging in, I have also tried sending over the login payload again with the following payload {"username": "hidden", "password": "hidden", "client_id": "sugar", "grant_type": "hidden" "client_secret": hidden,"platform": "base"} having no luck with it still saying there is no valid authentication for user (note I am certain the token has not expired as the program it's self takes 10 seconds from login to POST request for record list), this leads me to believe that there is paramaters that I am msising or that are just wrong. If you have any ideas on what I am doing wrong, please let me know.

Thank you for taking your time to read my question.

Parents
  • Hiya Francesca,

    I am able to grab the Oauth token saved which is saved in a text file upon logging in, I am also using sessions to hold the cookies for me which you can see in the code below.

    payload 1 = {hidden}
    
    with requests.session() as a:
        response = a.post('.../rest/v11_5/oauth2/token', data=payload)
        response.raise_for_status()
        file = open(r"auth.txt", "w")
        #opens auth text file (overwrites if file already exists) in write mode
        file.write(response.text)
        # writes response from OAUTH request into auth.txt
        file.close()
        # File close
        file1 = open(r"auth.txt", "r")
        #opens auth.txt in read mode
        authcopy = open(r"authcopy.txt", "r+t")
        #opens authcopy.text in write and read mode
        authcopy.write(file1.readline(54).replace('{"access_token":', ''))
    #writes to authcopy the OAUTH key with nothing else included (token type, refresh token etc)
    
    payload 2 = {hidden}
    
    ### this is the part that had the issue
    
    ID = a.post('../rest/v11_5/ProductTemplates/record_list', data=payload2)
        print(ID.text) ### just to test it's working



    I am not very familiar with the REST API and modules so I'll have to do some reading of the documentation, if there is anything else that
    you think I should know about to help me in my quest, please let me know. Thank you for your help!
  • this is the PHP code I use to test my APIs.

    I am afraid I've not worked with python, but see if this helps you make sense of the process.

    <?php
    /* Test Your GET API Call */
    
    //setting the api and credentials to test up here just makes life a bit easier for reuse
    $rest = "https://your_sugar_server_path/rest/v11";
    $user = "put_user_name_here"; // username of the sugar account you are using to run the API
    $pass = "your_user's_password_here"; // and the password of user “user”
    
    //sample api to test
    // in this example get a Contact by email address 
    $api_to_test = '/Contacts&filter[0][email_addresses.email_address]=myname@myaddress.com';
    
    /*************** NO CHANGES NEEDED below this line  **************************** 
      the code below stays the same and just builds the appropriate call and prints the output 
     *******************************************************************************/
    
    
    /*******************************************************************************
     *Get the Token
     *******************************************************************************/
    
    $url = $rest . "/oauth2/token"; // login
    $oauth2_token_parameters = array(
      "grant_type" => "password",
      "client_id" => "sugar",
      "client_secret" => "",
      "username" => $user,
      "password" => $pass,
    );
    $oauth2_token_result = call($url, '', 'POST', $oauth2_token_parameters);
    echo(print_r($oauth2_token_result, true));
    
    /************************************************************************************
     * Check you have the token
     ***********************************************************************************/
    if (empty($oauth2_token_result->error)){
      //logged in ok
      echo('logged in ok <p>');
      /************************************************************************************
      * Test your API
      ********************************************************************************/
      $url = $rest . $api_to_test; //builds the api url using the parameters set above 
      echo('<pre>');
      echo($url.'<p>');
      $result = call($url, $oauth2_token_result->access_token, 'GET');
      echo('<p>'); var_dump($result);
      $url = $rest . "/oauth2/logout"; // logout
      $oauth2_logout_result = call($url, $oauth2_token_result->access_token, 'GET');
    }else{
      print("<hr>Login Failed<hr>");
    }
    /*******************************************************************************
     * call
     ******************************************************************************/
     /**
    * Generic function to make cURL request.
    * @param $url - The URL route to use.
    * @param string $oauthtoken - The oauth token.
    * @param string $type - GET, POST, PUT. Defaults to GET.
    * @param array $parameters - Endpoint parameters.
    * @return mixed
    */
    function call($url, $oauthtoken='', $type='GET', $parameters=array())
    {
       $type = strtoupper($type);
       $curl_request = curl_init($url);
       if ($type == 'POST')
       {
          curl_setopt($curl_request, CURLOPT_POST, 1);
       }
       elseif ($type == 'PUT')
       {
          curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
       }
       elseif ($type == 'DELETE')
       {
          curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
       }
       curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
       curl_setopt($curl_request, CURLOPT_HEADER, false);
       curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
       curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
       if (!empty($oauthtoken))
       {
          curl_setopt($curl_request, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "oauth-token: {$oauthtoken}"));
       }else
       {
          curl_setopt($curl_request, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
       }
       if (!empty($parameters))
       {
          //encode the parameters
          $jsonEncodedData = json_encode($parameters);
          echo('<p> json parameters <p>:');
          echo($jsonEncodedData);
          curl_setopt($curl_request, CURLOPT_POSTFIELDS, $jsonEncodedData);
       }
       $result = curl_exec($curl_request);
       curl_close($curl_request);
       $response = json_decode($result);
       return $response;
    }
    ?>

Reply
  • this is the PHP code I use to test my APIs.

    I am afraid I've not worked with python, but see if this helps you make sense of the process.

    <?php
    /* Test Your GET API Call */
    
    //setting the api and credentials to test up here just makes life a bit easier for reuse
    $rest = "https://your_sugar_server_path/rest/v11";
    $user = "put_user_name_here"; // username of the sugar account you are using to run the API
    $pass = "your_user's_password_here"; // and the password of user “user”
    
    //sample api to test
    // in this example get a Contact by email address 
    $api_to_test = '/Contacts&filter[0][email_addresses.email_address]=myname@myaddress.com';
    
    /*************** NO CHANGES NEEDED below this line  **************************** 
      the code below stays the same and just builds the appropriate call and prints the output 
     *******************************************************************************/
    
    
    /*******************************************************************************
     *Get the Token
     *******************************************************************************/
    
    $url = $rest . "/oauth2/token"; // login
    $oauth2_token_parameters = array(
      "grant_type" => "password",
      "client_id" => "sugar",
      "client_secret" => "",
      "username" => $user,
      "password" => $pass,
    );
    $oauth2_token_result = call($url, '', 'POST', $oauth2_token_parameters);
    echo(print_r($oauth2_token_result, true));
    
    /************************************************************************************
     * Check you have the token
     ***********************************************************************************/
    if (empty($oauth2_token_result->error)){
      //logged in ok
      echo('logged in ok <p>');
      /************************************************************************************
      * Test your API
      ********************************************************************************/
      $url = $rest . $api_to_test; //builds the api url using the parameters set above 
      echo('<pre>');
      echo($url.'<p>');
      $result = call($url, $oauth2_token_result->access_token, 'GET');
      echo('<p>'); var_dump($result);
      $url = $rest . "/oauth2/logout"; // logout
      $oauth2_logout_result = call($url, $oauth2_token_result->access_token, 'GET');
    }else{
      print("<hr>Login Failed<hr>");
    }
    /*******************************************************************************
     * call
     ******************************************************************************/
     /**
    * Generic function to make cURL request.
    * @param $url - The URL route to use.
    * @param string $oauthtoken - The oauth token.
    * @param string $type - GET, POST, PUT. Defaults to GET.
    * @param array $parameters - Endpoint parameters.
    * @return mixed
    */
    function call($url, $oauthtoken='', $type='GET', $parameters=array())
    {
       $type = strtoupper($type);
       $curl_request = curl_init($url);
       if ($type == 'POST')
       {
          curl_setopt($curl_request, CURLOPT_POST, 1);
       }
       elseif ($type == 'PUT')
       {
          curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
       }
       elseif ($type == 'DELETE')
       {
          curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
       }
       curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
       curl_setopt($curl_request, CURLOPT_HEADER, false);
       curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
       curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
       if (!empty($oauthtoken))
       {
          curl_setopt($curl_request, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "oauth-token: {$oauthtoken}"));
       }else
       {
          curl_setopt($curl_request, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
       }
       if (!empty($parameters))
       {
          //encode the parameters
          $jsonEncodedData = json_encode($parameters);
          echo('<p> json parameters <p>:');
          echo($jsonEncodedData);
          curl_setopt($curl_request, CURLOPT_POSTFIELDS, $jsonEncodedData);
       }
       $result = curl_exec($curl_request);
       curl_close($curl_request);
       $response = json_decode($result);
       return $response;
    }
    ?>

Children
No Data