Step-by-Step Guide to Integrating with Vertex Tax RESTful API using Python

By JoeVu, at: 2024年9月29日12:00

Estimated Reading Time: 10 min read

Step-by-Step Guide to Integrating with Vertex Tax RESTful API using Python
Step-by-Step Guide to Integrating with Vertex Tax RESTful API using Python

Integrating with Vertex Tax RESTful API (v2) Using Python


1. Introduction

As we are introducing the VertexCloud Indirect Tax in our previous blog post, in this blog post we will focus on the step-by-step process of integrating with Vertex’s Tax RESTful API using Python. By the end of this tutorial, you’ll be able to make tax calculations and handle transactions programmatically using Vertex’s services.

Since version 1 is deprecated, so we focus on the version 2 which is the supported one now.

 

2. Prerequisites

Before we dive into the integration process, ensure you have the following in place:

  • Python (version 3.6 or higher)
     
  • Vertex Tax API credentials: You will need a valid Vertex account to generate API keys and access the service. Sign up for API access.
     
  • Python Libraries: This guide will use requests for making HTTP calls and json for handling the API responses - pip install requests
     
  • Basic Understanding of RESTful APIs: Knowing how to interact with RESTful APIs (via GET, POST, PUT requests) will help you follow this guide easily.

 

3. Setting Up Your Python Environment

To begin, create a new project folder and set up a virtual environment to keep your dependencies organized. Here’s how you can do that:


Create a Project Directory

mkdir vertex-tax-api
cd vertex-tax-api

 

Set Up a Virtual Environment

python3 -m venv vertex-env
source vertex-env/bin/activate

# For MacOS/Linux
# OR vertex-env\Scripts\activate
# For Windows

 

Install the Required Dependencies

pip install requests


You are now ready to begin writing code to integrate with the Vertex Tax API.

 

4. Authentication with the Vertex Tax API (Version 2)

Before making any API calls, you'll need to authenticate with Vertex’s system using OAuth 2.0. The authentication process requires sending the client_id, client_secret, and grant_type (set to client_credentials) to the authentication endpoint to receive a token.


Authentication Request Example

Here’s how you can authenticate using Python and retrieve the access token from Vertex's API (version 2):

import requests

# URL to obtain the auth token
auth_url = 'https://auth.vertexsmb.com/identity/connect/token'

# Your client credentials
client_id = 'your_client_id'
client_secret = 'your_client_secret'

# Data for token request
data = {
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
}

# Headers
headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

# Send request to get the token
response = requests.post(auth_url, data=data, headers=headers)

if response.status_code == 200:
    token = response.json().get('access_token')
    print(f"Access Token: {token}")
else:
    print("Authentication failed:", response.text)

 


Once you successfully authenticate, the API will return an access token. This token must be included in the Authorization header when making requests to other API endpoints.

 

5. Making a Tax Calculation Request (Version 2)

After obtaining the access token, you can proceed with making tax calculation requests. The following is an example payload for a tax calculation request, which includes details such as the sale message type, transaction type, currency, customer information, line items, and any discounts.


Example Tax Calculation Request

# URL for tax calculation (version 2)
api_url = 'https://calcconnect.vertexsmb.com/vertex-ws/v2/supplies'

# Set headers including the access token
headers = {
    'Authorization': f'Bearer {token}',
    'Content-Type': 'application/json',
}

# Sample payload for tax calculation
payload = {
    "saleMessageType": "QUOTATION",
    "transactionType": "SALE",
    "transactionId": "998822",
    "originalCurrency": {
        "isoCurrencyCodeAlpha": "USD"
    },
    "currency": {
        "isoCurrencyCodeAlpha": "USD"
    },
    "customer": {
        "administrativeDestination": {
            "city": "Joe Vu",
            "country": "US",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": ""
        },
        "customerCode": {
            "classCode": "TAX",
            "value": "GUEST"
        },
        "destination": {
            "city": "Lake Ozark",
            "country": "US",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": ""
        },
        "isTaxExempt": "false"
    },
    "documentDate": "2024-09-04",
    "documentNumber": "3065",
    "lineItems": [
        {
            "lineItemNumber": "0",
            "product": {
                "value": "Stuff:Concrete"
            },
            "quantity": {
                "unitOfMeasure": "UOM",
                "value": 13
            },
            "discount": {
                "discountType": "DiscountAmount",
                "discountValue": "-0"
            },
            "unitPrice": "212.343",
            "vendorSKU": None
        }
    ],
    "discount": {
        "discountType": "DiscountAmount",
        "discountValue": 0,
        "userDefinedDiscountCode": "string"
    }
}

# Make the POST request
response = requests.post(api_url, json=payload, headers=headers)

if response.status_code == 200:
    tax_info = response.json()
    print("Tax Calculation Result:", tax_info)
else:
    print("Error in API call:", response.text)


In this example, you’re sending a detailed transaction to the Vertex API. The payload contains essential fields such as the transaction type, customer details, and line items, including their quantity, price, and any discounts applied.

 

Sample response

{
  "data": {
    "currency": {
      "isoCurrencyCodeAlpha": "USD",
      "isoCurrencyCodeNum": 0,
      "isoCurrencyName": "US Dollar"
    },
    "customer": {
      "administrativeDestination": {
        "city": "Joe Vu",
        "country": "US",
        "locationCode": "",
        "mainDivision": "MO",
        "postalCode": "65049",
        "streetAddress1": "",
        "taxAreaId": "260294565"
      },
      "customerCode": {
        "classCode": "TAX",
        "isBusinessIndicator": false,
        "value": "GUEST"
      },
      "destination": {
        "city": "Joe Vu",
        "country": "US",
        "locationCode": "",
        "mainDivision": "MO",
        "postalCode": "65049",
        "streetAddress1": "",
        "taxAreaId": "260294565"
      },
      "isTaxExempt": false,
      "taxRegistrations": []
    },
    "discount": {
      "userDefinedDiscountCode": "string"
    },
    "documentDate": "2024-09-04",
    "documentNumber": "998822",
    "lineItems": [
      {
        "customer": {
          "administrativeDestination": {
            "city": "Joe Vu",
            "country": "US",
            "locationCode": "",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": "",
            "taxAreaId": "260294565"
          },
          "customerCode": {
            "classCode": "TAX",
            "isBusinessIndicator": false,
            "value": "GUEST"
          },
          "destination": {
            "city": "Lake Ozark",
            "country": "US",
            "locationCode": "",
            "mainDivision": "MO",
            "postalCode": "65049",
            "streetAddress1": "",
            "taxAreaId": "260294565"
          },
          "isTaxExempt": false,
          "taxRegistrations": []
        },
        "discount": {
          "userDefinedDiscountCode": "string"
        },
        "extendedPrice": 2760.459,
        "fairMarketValue": 2760.459,
        "lineItemNumber": 0,
        "locationCode": "",
        "product": {
          "value": "book 1"
        },
        "quantity": {
          "unitOfMeasure": "UOM",
          "value": 13
        },
        "taxIncludedIndicator": false,
        "taxes": [
          {
            "calculatedTax": 116.62,
            "calculationRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v301028065"
            },
            "effectiveRate": 0.04225,
            "exempt": 0,
            "imposition": {
              "impositionId": "1",
              "jurisdictionId": "19873",
              "userDefined": false,
              "value": "Sales and Use Tax"
            },
            "impositionType": {
              "impositionTypeId": "v1",
              "userDefined": false,
              "value": "General Sales and Use Tax"
            },
            "inclusionRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v315534188"
            },
            "isService": false,
            "jurisdiction": {
              "effectiveDate": "1900-01-01",
              "expirationDate": "9999-12-31",
              "jurisdictionId": "19873",
              "jurisdictionType": "STATE",
              "value": "MISSOURI"
            },
            "maxTaxIndicator": false,
            "nominalRate": 0.04225,
            "nonTaxable": 0,
            "notRegisteredIndicator": false,
            "situs": "DESTINATION",
            "taxCollectedFromParty": "BUYER",
            "taxResult": "TAXABLE",
            "taxStructure": "SINGLE_RATE",
            "taxType": "SALES",
            "taxable": 2760.46
          },
          {
            "calculatedTax": 41.41,
            "calculationRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v309207820"
            },
            "effectiveRate": 0.015,
            "exempt": 0,
            "imposition": {
              "impositionId": "1",
              "jurisdictionId": "20023",
              "userDefined": false,
              "value": "Local Sales and Use Tax"
            },
            "impositionType": {
              "impositionTypeId": "v1",
              "userDefined": false,
              "value": "General Sales and Use Tax"
            },
            "inclusionRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v302021096"
            },
            "isService": false,
            "jurisdiction": {
              "effectiveDate": "1900-01-01",
              "expirationDate": "9999-12-31",
              "jurisdictionId": "20023",
              "jurisdictionType": "COUNTY",
              "value": "CAMDEN"
            },
            "maxTaxIndicator": false,
            "nominalRate": 0.015,
            "nonTaxable": 0,
            "notRegisteredIndicator": false,
            "situs": "DESTINATION",
            "taxCollectedFromParty": "BUYER",
            "taxResult": "TAXABLE",
            "taxStructure": "SINGLE_RATE",
            "taxType": "SALES",
            "taxable": 2760.46
          },
          {
            "calculatedTax": 41.41,
            "calculationRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v301032380"
            },
            "effectiveRate": 0.015,
            "exempt": 0,
            "imposition": {
              "impositionId": "1",
              "jurisdictionId": "20035",
              "userDefined": false,
              "value": "Local Sales and Use Tax"
            },
            "impositionType": {
              "impositionTypeId": "v1",
              "userDefined": false,
              "value": "General Sales and Use Tax"
            },
            "inclusionRuleId": {
              "salesTaxHolidayIndicator": false,
              "userDefined": false,
              "value": "v302021099"
            },
            "isService": false,
            "jurisdiction": {
              "effectiveDate": "1900-01-01",
              "expirationDate": "9999-12-31",
              "jurisdictionId": "20035",
              "jurisdictionType": "CITY",
              "value": "VILLAGE OF FOUR SEASONS"
            },
            "maxTaxIndicator": false,
            "nominalRate": 0.015,
            "nonTaxable": 0,
            "notRegisteredIndicator": false,
            "situs": "DESTINATION",
            "taxCollectedFromParty": "BUYER",
            "taxResult": "TAXABLE",
            "taxStructure": "SINGLE_RATE",
            "taxType": "SALES",
            "taxable": 2760.46
          }
        ],
        "totalTax": 199.44,
        "transactionType": "SALE",
        "unitPrice": 212.343
      }
    ],
    "originalCurrency": {
      "isoCurrencyCodeAlpha": "USD",
      "isoCurrencyCodeNum": 0,
      "isoCurrencyName": "US Dollar"
    },
    "returnAssistedParametersIndicator": true,
    "roundAtLineLevel": false,
    "saleMessageType": "QUOTATION",
    "subTotal": 2760.46,
    "total": 2959.9,
    "totalTax": 199.44,
    "transactionId": "998822",
    "transactionType": "SALE"
  },
  "meta": {
    "app": "vertex-ws.war v9.0.17.1.3",
    "timeElapsed(ms)": 3,
    "timeReceived": "2024-09-04T22:57:19.594Z"
  }
}

 

6. Conclusion

Integrating with the Vertex Tax RESTful API using Python allows businesses to automate complex tax calculations efficiently. In this guide, we walked through the essential steps, from authenticating with the Vertex API to making a tax calculation request. By leveraging the power of Python and the flexibility of Vertex’s version 2 API, you can streamline tax compliance in your applications, reducing manual work and ensuring accuracy in tax reporting.

Key takeaways from this guide include:

  • Setting up authentication using OAuth 2.0 to retrieve access tokens.
     
  • Constructing and sending a tax calculation request, including customer details, transaction information, and line items.
     
  • Handling API responses and ensuring you can manage transactions programmatically.

With this integration in place, you can now scale your tax operations, provide real-time tax calculations for your customers, and ensure compliance across multiple jurisdictions. As you continue to develop your solution, be sure to explore other features of the Vertex API, such as tax exemptions, return filing, and auditing functionalities, to further enhance your tax workflows.

If you need more advanced configurations or further details, the Vertex API Documentation is an excellent resource for exploring the full range of capabilities Vertex offers.


Subscribe

Subscribe to our newsletter and never miss out lastest news.