How do I use CircuiTree’s API?

This post will explain how to use CircuiTree’s API to send and receive requests. Most of the API requests are submitted and responded to using JSON formatting.

Step 1: Apply for an API Key

In order to start using the API you will an API Key.  An API Key is a unique value created for your company and used to authenticate your credentials.

You can find out more about pricing and how to obtain an API Key by contacting our Support team.

Step 2: Authenticate your credentials

All API requests require you to provide an API Token.  An API Token is an encrypted value that validates and identifies who the request is from.

To obtain an API Token you must authenticate your credentials.  The Authentication request should be sent to https://api.circuitree.com/Authentication/Authenticate.json.

This API method requires you to provide the following information:

  • Username:  This is your CircuiTree login.
  • Password:  The password you use to login to CircuiTree.
  • API Key:  See Step 1 for more information about how to obtain an API Key.
  • Company Code:  This your Company ID.  This value will be provided with your API Key.
Once you have all of the above information, you can submit a request to our API Authentication webservice using JSON.If your request is authenticated the response will include the following information:
  • Status Code: 1 = Success
  • Status Message:  Gives additional information about the StatusCode
  • Api Token:  A unique value that must be used to authenticate subsequent API requests.
  • Company Api Url:  The URL that should be used for to make API requests.  The version of the API that your company uses changes frequently to match the version of CircuiTree you are running.

Step 3:  Send and Receive API Requests

Once you have an API Token and CompanyAPI URL you can now send and receive API requests.
While you don’t have authenticate for every request, it is good practice to authenticate your credentials periodically as your Company API URL will change.

In the diagram below you can see the workflow of how a request is sent to the API.  In this example we are requesting that an Export Query be run.

Note that all responses will includes a StatusCode and a StatusMessage.  You should always check this data for a successful status after a response has been received.

Show Me How

Not quite sure?  Look at the code snippets below for an example on how to make an Authentication API request and subsequently and ExecuteQuery request.   The code was written using VB.NET and the .NET framework 4.0

Public Sub apiExampleCodeTest()
        Dim parameters As New Dictionary(Of String, Object)
        Dim response As Dictionary(Of String, Object)

        'Setup request parameters.  These values should be stored in private storage that is not viewable to the public.
        parameters.Add("Username", "YourCTUsername")
        parameters.Add("Password", "YourPassword")
        parameters.Add("APIKey", "YourAPIKey")
        parameters.Add("CompanyCode", "YourCompanyID")

        'Create a request object using the CircuiTree Authentication Url
        Dim request As HttpWebRequest = _
            CType(HttpWebRequest.Create("https://api.circuitree.com/Authentication/Authenticate.json"), HttpWebRequest)

        request.Method = "POST"
        request.ContentType = "application/json; charset=utf-8"
        request.CookieContainer = New System.Net.CookieContainer

        'Use built in .net serializer to encode parameters to JSON
        Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer
        Using s = request.GetRequestStream
            Using sw As New IO.StreamWriter(s)
                sw.Write(serializer.Serialize(parameters))
            End Using
        End Using

        'Send the request to the API and get the response.
        Using s = request.GetResponse().GetResponseStream
            Using sr As New IO.StreamReader(s)

                'Deseralize the http response back to an object from JSON
                Dim jsonResultString As String = sr.ReadToEnd
                response = serializer.Deserialize(Of Dictionary(Of String, Object))(jsonResultString)
            End Using
        End Using

        'Check the status
        If CInt(response("StatusCode")) <> 1 Then
            Throw New Exception(String.Format("Unable to authenticate request.  " + _
                                "Error: {0} - Code: {1}", response("StatusMessage"), response("StatusCode")))
        End If

        'Get the apiToken and company api url
        Dim apiToken As String = response("ApiToken").ToString
        Dim companyAPIURL As String = response("CompanyAPIURL").ToString

        'Add the parameters for the ExecuteQuery request
        parameters.Clear()
        parameters.Add("ApiToken", apiToken)
        parameters.Add("ExportQueryID", -45) 'AR Category List

        'No export query parameters are required for this query.
        Dim paramValues As New List(Of Dictionary(Of String, Object))
        parameters.Add("QueryParameters", paramValues)

        'Create a request object using the CircuiTree Authentication Url
        request = CType(HttpWebRequest.Create(companyAPIURL + "/Exports/ExecuteQuery.json"), HttpWebRequest)

        request.Method = "POST"
        request.ContentType = "application/json; charset=utf-8"
        request.CookieContainer = New System.Net.CookieContainer

        'Use built in .net serializer to encode parameters to JSON
        serializer = New System.Web.Script.Serialization.JavaScriptSerializer
        Using s = request.GetRequestStream
            Using sw As New IO.StreamWriter(s)
                sw.Write(serializer.Serialize(parameters))
            End Using
        End Using

        'Send the request to the API and get the response.
        Using s = request.GetResponse().GetResponseStream
            Using sr As New IO.StreamReader(s)

                'Deseralize the http response back to an object from JSON
                Dim jsonResultString As String = sr.ReadToEnd
                response = serializer.Deserialize(Of Dictionary(Of String, Object))(jsonResultString)
            End Using
        End Using

        'Check the status
        If CInt(response("StatusCode")) <> 1 Then
            Throw New Exception(String.Format("Unable to execute A/R Categories Export Query request.  " + _
                            "Error: {0} - Code: {1}", response("StatusMessage"), response("StatusCode")))
        End If

        'Using JSON.NET to convert results from JSON to a datatable. http://json.codeplex.com
        Dim json As New Newtonsoft.Json.JsonSerializer
        json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
        json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace
        json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
        json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

        Using sr2 As New StringReader(response("Results").ToString)
            Dim reader As New Newtonsoft.Json.JsonTextReader(sr2)
            Dim result = json.Deserialize(reader, GetType(Data.DataTable))
            reader.Close()
        End Using

    End Sub

Ruby on Rails

Thanks to Evan from Forest Home for submitting this method for connecting using Ruby on Rails.

CONTROLLER PART 

def makeRequestBody
    beginDate = Date.new(2017, 4, 20)
    endDate = Date.new(2017, 4, 28)
    param1 = {
      'ParameterID' => 8,
      'ParameterValue' => beginDate
    }
    param2 = {
      'ParameterID' => 9,
      'ParameterValue' => endDate
    }

    #   - Initializes paramArray as array and adds param1 and param2 to it. 
    paramArray = [] << param1 << param2 data = { 'ApiToken' => @ApiToken,
      'ExportQueryID' => @ExportQueryId,
      'QueryParameters' => paramArray
    }
    sendRequest(data)
  end
  
  private
  
  def initVariables
    # -47 for requests without parameters.
    @ExportQueryId = 197
    @Url = "https://api.circuitree.com/Exports/ExecuteQuery.json"
    @ApiToken = “secretcodegoeshere"
  end

  def sendRequest(data)
    #   - Creates a URI object with the CircuiTree API as parameter.
    uri = URI(@Url)
    #   - Creates a new HTTP object with the URI host and port as parameters.
    http = Net::HTTP.new(uri.host, uri.port)
    #   - CircuiTree API uses SSL, so we active it.
    http.use_ssl = true
    #   - Creates a new Post object with the URI path and content-type json as parameters.
    req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
    #   - Sets the request body to the data that is created in 'makeRequestBody'.
    req.body = data.to_json
    #   - This makes the actually request to the CircuiTree API.
    res = http.request(req)
    #   - Giving @variable the value of res.body and parse it as JSON.
    @variable = JSON.parse(res.body)
    #   - Iterating over @variable to process results.
    @variable.each do |key,value|

    end
    #   - Only use 1 render method from below.
    #   - Renders the response body (the json rails gets back from the CircuiTree API).
   # render :json => res.body
    #   - Renders some html instead of the JSON response.
    # render :html => "Hello world"
    #   - Renders a html file from the views folder.
    # render file: "test.html.erb"
  End

VIEW PART

<% @variable.each do |key,value| %>
    
    <% if key == "Results" %>
   <% JSON.parse(value).each do |val| %>

  <%= "ItineraryID: #{val['ItineraryID']}" %>
          
     <% end %>
    <% end %>
   <% end %>
   <%= @variable.size %>

Related Topics