Home » Vinsight API  »  Client Code Examples  »  Python Example

Python Example

import urllib
import base64
import requests

s = requests.Session()

verifyHTTPS = True #Set this to False if you want to use a proxy such as fiddler to decrypt traffic

domain = "https://app.vinsight.net"
username = "abc@example.com"
password = "mypassword"


def login(username, password):
    encodedCredentials = base64.b64encode(urllib.quote(username) + ":" + urllib.quote(password))
        
    url = domain + "/LoginContexts"
    headers = {
        'Accept': 'application/json',
        'Authorization': "Basic " + encodedCredentials
    }
    
    r = s.post(url, 
        headers=headers,
        verify=verifyHTTPS
    )
    
    if (r.status_code == 200):
        loginResult = r.json()
        
        print "Logged in to %s. Connection Name: %s" % (loginResult['OrganisationName'], loginResult['ConnectionName'])
        
        return
        
    raise ValueError('Login failed with status ' + str(r.status_code))

def getAs(path, acceptType):
    url = domain + path
    headers = {
        'Accept': acceptType
    }
    
    r = s.get(url, 
        headers=headers,
        verify=verifyHTTPS
    )
    
    if (r.status_code == 200):
        
        #Fix encoding of response to match that of the server if we are asking for CSV
        if (acceptType == "text/csv"):
            r.encoding = "utf-8-sig"
            
        return r.text
        
    raise ValueError('Request failed with status ' + str(r.status_code))
    
def test(url):
    login(username, password)
    return getAs(url, "text/csv")

csvData = test("/StockItems?$select=StockItemCode,UnitsInStock,UnitsInStockUOM&$top=999")
print csvData