search-icon

API calls = "incorrect credentials"

started a topic over 7 years ago

I'm struggling to make simple curl requests to the API and I keep getting an "incorrect credentials!" response.  What am I doing wrong?


curl -d '{"auth":{"passwordCredentials":{"api-auth-accountid": "MY-API-AUTH-ACCOUNT-ID", "api-auth-applicationkey": "MY-APPLICATION-KEY"}}}' -H "Content-Type: application/json"


I tested this request with the api explorer and it gives the response I'd expect.



I'm finding the documentation really lacking and confusing - for example the api introduction page seems to list the incorrect (maybe version1?) url.


If anyone has some example API calls in Python they could share I'd be very grateful!

  • I've been trying as well. I'm using 


    import requests

    import json

    import psycopg2

    import sys

    import pprint

     

    #HTTP Header for Dear Systems

    headers = {'Content-Type': 'application/json', 'api-auth-accountid': 'xxxxxx', 'yyyyyy', 'Accept': 'application/json'}

     

    # Dear Systems API URL with Parameters

     

    # Request

    response = requests.get(url, headers=headers)

    status = response.status_code

    print(status)

     

    # Get the response from the API endpoint.

    message = response.content

    print(message)


    But at the moment just getting incorrect credentials????



  • Here you go - This all functions.  Replace the 1234567890 and 0987654321 with your credentials.  


    #!/usr/bin/python

    # -*- coding: iso-8859-15 -*-

    import os, sys


    import requests

    import json


    # define variables

    apiauthaccountid = ‘1234567890’

    apiauthapplicationkey = '0987654321'

    headers = {'api-auth-accountid': apiauthaccountid, 'api-auth-applicationkey': apiauthapplicationkey, 'Accept':'application/json'}


    saleNumber = input('Enter a sale number: ')


    print('Thanks. Lets see what we\'ve got...')


    #search for that sale number

    jsonDataAsPythonValue = json.loads(requests.get(url, headers=headers).text)


    #make the (bad) assumption that the first result is our sale number.  

    #Ideally you would check all returned sales to ensure their sale number is what was searched for

    saleID = (jsonDataAsPythonValue['SaleList'][0]["ID"])


    #use that sale ID to get our actual sale

    jsonSaleDataAsPythonValue = json.loads(requests.get(url, headers=headers).text)



  • Got it working


        headers = {'api-auth-accountid': apiauthaccountid,

               'api-auth-applicationkey': apiauthapplicationkey,

               'Accept': 'application/json'}

      

        response=requests.get(url, headers=headers)

        status=response.status_code

        data=response.json()

        pdata=[data['SaleList'][0]['ID']]


    Thanks for your help

  • Here's a simple example

    from typing import List, MutableMapping, Optional
    import requests
    import datetime as dt
    from unittest import TestCase
    
    class Dear():
        def __init__(self, api_auth_accountid, api_auth_applicationkey):
            self.url = 'https://inventory.dearsystems.com/dearapi/'
            self.headers = {'api-auth-accountid': api_auth_accountid,
                            'api-auth-applicationkey': api_auth_applicationkey,
                            'Content-Type': 'application/json'}
            self.session = requests.Session()
    
        def get_all_products(self,modified_after:dt.datetime=None)-> Optional[List]:
            next_page = 1  # first page is 1
            page_limit = 500  # a constant
            data = []
            if not modified_after:
                modified_after = dt.date(2001,1,1)
    
            modified_after_str = modified_after.strftime('%Y-%m-%d %H:%M:%S')
            while True:
                url = self.url + 'Products?page={page}&limit={limit}&modifiedSince={modifiedSince}'.format(page=next_page, limit=page_limit,
                                                                             modifiedSince=modified_after_str)
                resp = self.session.get(
                    url=url,
                    headers=self.headers)
                try:
                    resp_json = resp.json()
                    result = resp_json.get("Products",[])
                except Exception as e:
                    raise
                if len(result) > 0:
                    data += result
                    next_page += 1
                else:
                    break
            return data

     


    1 person likes this
  • Hi,


    Can someone help me to get this into Google Sheets, 


    I copy and paste the code into scripts but it doesnt work.


    can you use curl in google sheets?


    Thanks

  • I don't think you can make a CURL request from a google sheet, but Google Apps Script is an extremely powerful language which plugs right into different Google services.


    What are you trying to do?

  • Google Apps Script is pretty much javascript. IMO, you will be better off writing the code in javascript.


    There are probably a thousand and one ways to write something like this, but here's some code that will write all of your active products to a sheet named "prodDB". I make no claims as to the efficiency of the code haha but it use it as a starting point and example.


    Also, check out the DEAR API documentation, it's quite good.

    https://dearinventory.docs.apiary.io/#reference/product/product/get


      

    function prodAPIv201 () {
      
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var prods = ss.getSheetByName('prodDB');
      var s = prods;
      var limit = 1000;
      
      var auth = {
      'api-auth-accountid' : 'enter-your-own-accountid-here',
      'api-auth-applicationkey' : 'enter-your-own-applicationkey-here'
      };
      var options = {'headers': auth};
      var url = 'https://inventory.dearsystems.com/ExternalApi/v2/product';
      var r = UrlFetchApp.fetch(url, options);
      var jdata = JSON.parse(r.getContentText());
      var total = jdata.Total;
      
      var prodIndex = 0;
      var prodNumber = 1;
      var currentPage = 1;
      var products = [];
      var currentProd = [];
      var currentRow = [];
      var maxRows = s.getMaxRows(); 
      var lastRow = s.getLastRow();
      
      while (currentPage <= (total/limit)+1) {
        url = 'https://inventory.dearsystems.com/ExternalApi/v2/'+
          'product?'+
            'Page=' + currentPage + 
              '&Limit=' + limit +
                '&IncludeDeprecated=false'+
                  '&IncludeSuppliers=false'+
                    '&IncludeMovements=false'+
                      '&IncludeReorderLevels=false';
        
        r = UrlFetchApp.fetch(url, options);
        
        if (r.getResponseCode() != 200) {
          break;
        }
        
        jdata = JSON.parse(r.getContentText());
        products = jdata.Products;
        
        while (prodIndex < limit && prodNumber <= total) {
          currentProd = products[prodIndex];
                
          currentRow.push([
            currentProd.SKU,
            currentProd.Name,
            currentProd.Brand,
            currentProd.Category,
            currentProd.Tags,
            currentProd.PriceTier1,
            currentProd.Description,
            currentProd.Status,
            currentProd.AttributeSet,
            currentProd.AdditionalAttribute1,
            currentProd.AdditionalAttribute2,
            currentProd.AdditionalAttribute3,
            currentProd.AdditionalAttribute4,
            currentProd.AdditionalAttribute5,
            currentProd.AdditionalAttribute6,
            currentProd.AdditionalAttribute7,
            currentProd.AdditionalAttribute8,
            currentProd.AdditionalAttribute9,
            currentProd.AdditionalAttribute10,
            currentProd.ID])
          
          s.getRange(5+prodNumber,1,1,20).setValues(currentRow);
    
          currentRow = [];
          prodIndex++;
          prodNumber++;
        }
        
        currentPage++;
        prodIndex = 0;
      }
    
      var maxRows = s.getMaxRows(); 
      var lastRow = s.getLastRow();
      if(maxRows > lastRow){
        s.deleteRows(lastRow+1, maxRows-lastRow);
      }
      else{
      }  
    
    }  
     

      

  • @Ryan : Thanks, I tried that script and got a few errors......

    TypeError: Cannot call method "getMaxRows" of null. (line 24, file "urlfetch")


    @Tristan : I am trying to pull a product availability list into google sheets; i then look this up against a certain list of products (ie no all) and then send out to my reps on a daily basis. The reason im using google sheets is that i can configure automatic sending on a daily basis.



  • The typeError you're getting is probably because the script isn't picking up the active spreadsheet from line 3.  Try using SpreadsheetApp.openById() with your spreadsheet ID.  Docs are available here:

    https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app


    Otherwise you should be able to easily modify Ryan's script to do what you need and then set it up on a trigger to run on a daily basis.

  • By the way - the Dear API has come a looong way since I posted this question 3 years ago.  The v2 API is really good and the documentation that Ryan linked to works well.

  • @ryan - i managed to get the script to work thanks, now to try and get the product availability in similar way

  • Glad it was helpful :) Tristan could not be more right about the state of the API. API v1 was...rough. API v2 is light years better.


    Availability will be located at a different API endpoint, so you'll need to change line 29 from product to productavailability (see the API documentation). Some of the same properties are available under productavailability, but not all. 


    For example, line 50 (currentProd.SKU) will still work, but line 52 (currentProd.Brand) will not. The productavailability endpoint does not provide access to the Brand for a given product. Alternatively, it does have properties that the product endpoint does not have; OnHand, Allocated, Available, OnOrder, etc.


    Also to note, the maximum response per page is 1000. I have over 10,000 products in DEAR, so I can't call them all at the same time and instead, need to call them in chunks of 1000 products. This is why I have the limit of 1000 and the while loop that iterates through page numbers.


    1 person likes this
Login or Signup to post a comment
Log in or Sign up to post a comment