API Newbie Question

I would like to pull a list of the categories in SWSD we have so far. Support directed me to use an API. I do not have experience with using an api to pull data. Can anyone direct me on how to get started and connect to our database?

Thanks.

Parents
  • Hearing that you need to pull from the API can be intimidating. It will be easier than you think, use the links to dig into stuff I mention.

    First do you have curl? Its not in windows by default, and the examples provided use it. I downloaded the version for windows.

    The documentation is good, and accurate, but might read like a foreign language to you.

    https://documentation.solarwinds.com/en/success_center/swsd/content/apidocumentation/general%20concepts.htm

    To start go to your instance, find your user account and generate the token you need. In all of the curl examples TOKEN gets replaced by that enormous string they give you. Save that off somewhere so you can copy and paste it as you need.

    Now that you have the key to get inside the API, you can use the commands they provide. Category docs are here:
    https://documentation.solarwinds.com/en/success_center/swsd/content/apidocumentation/categories.htm#kix.9ybal72b7lp

    And the command they give to list them is:
    curl -H "X-Samanage-Authorization: Bearer TOKEN" -H 'Accept: application/xml' -H 'Content-Type:text/xml' -X GET api.samanage.com/.../CATEGORY_ID.xml

    Swap out TOKEN for the token you just made and if curl is in the path you can use that command exactly (or provide the full path to the .exe)
    It will look a little like this. (Data is from a test instance, and the automatically generated categories.)

    If you want a text file with that data, just add something like  > ''c:\folders\output.xml" to the end to get the results in a text file.

    I don't ever use curl, I don't want my data like this. I use PowerShell. And I google extensively for examples when I get confused, which I think is standard for most of us who don't work with API's daily.

    $token = 'TOKEN'
    $apiRoot = "https://api.samanage.com"
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("Accept", 'application/vnd.samanage.v2.1+json')
    $headers.Add("X-Samanage-Authorization", "Bearer $token")
    $contentType = "application/json"
    $response = Invoke-RestMethod -Uri "$apiRoot/categories.json" -Headers $headers -ContentType $contentType -Method Get


    Again, replace TOKEN, and at the end of it you have a variable $response with your results.  I sent the results to a grid with" $response | OGV

    You can see that there are parent and children objects, and you can work on those like anything else in PowerShell. You can send that data as output using lots of the built in commands. If need more assistance, let me know.

  • This is WAY more than you asked for, but here's how I would do it with PowerShell.

    Important Note: This will ONLY work in PowerShell 7.x as the 5.x version of Invoke-RestMethod does not support the ResponseHeadersVariable parameter (which is needed for pagination).

    <#
    .Synopsis
        Convert a hashtable to a query string
    .DESCRIPTION
        Converts a passed hashtable to a query string based on the key:value pairs.
    .EXAMPLE
        $UriParameters = @{}
        PS > $UriParameters.Add("PageSize", 20)
        PS > $UriParameters.Add("PageIndex", 1)
    
        PS > $UriParameters
    
    Name                           Value
    ----                           -----
    PageSize                       20
    PageIndex                      1
    
        PS > $UriParameters | ConvertTo-QueryString
    
        PageSize=20&PageIndex=1
    .OUTPUTS
        string object in the form of "key1=value1&key2=value2..."  Does not include the preceeding '?' required for many URI calls
    .NOTES
        This is bascially the reverse of [System.Web.HttpUtility]::ParseQueryString
    
        This is included here just to have a reference for it.  It'll typically be defined 'internally' within the `begin` blocks of functions
    #>
    function ConvertTo-QueryString {
        param (
            # Hashtable containing segmented query details
            [Parameter(
                Mandatory = $true, 
                ValueFromPipeline = $true)]
            [ValidateNotNull()]
            [ValidateNotNullOrEmpty()]
            [System.Collections.Hashtable]$Parameters
        )
        $ParameterStrings = @()
        $Parameters.GetEnumerator() | ForEach-Object {
            $ParameterStrings += "$( $_.Key )=$( $_.Value )"
        }
        $ParameterStrings -join "&"
    }
    
    
    function Get-SwsdIncident {
        [CmdletBinding(
            SupportsShouldProcess = $true, 
            PositionalBinding = $false,
            HelpUri = 'https://documentation.solarwinds.com/en/success_center/swsd/content/apidocumentation/incidents.htm',
            ConfirmImpact = 'Medium')
        ]
        Param
        (
            # Optional page size grab for the call to the API. (Script defaults to 1000 per batch)
            # Larger page sizes generally complete faster, but consume more memory
            [Parameter(
                Mandatory = $false
            )]
            [ValidateNotNull()]
            [ValidateNotNullOrEmpty()]
            [ValidateRange(1, 100)]
            [int]$BatchSize = 10,
    
            # JSON Web Token
            [Parameter(
                Mandatory = $true
            )]
            [ValidateNotNull()]
            [ValidateNotNullOrEmpty()]
            [string]$JsonWebToken = $Global:JsonWebToken
    
        )
        begin { 
            # Uri Base - set to 'apieu.samanage.com' if you are in the European Union
            # Be sure to include the trailing slash (/)
            $UriBase = "https://api.samanage.com/"
            
            # the API's URI that we'll be connecting to
            # Be sure to OMIT the initial slash (/)
            $Uri = 'incidents.json'
            $Headers = @{}
            $Headers["Accept"] = 'application/vnd.samanage.v2.1+json'
            $Headers["X-Samanage-Authorization"] = "Bearer $JsonWebToken"
            
            $UriParameters = @{}
            $UriParameters["page"] = 1
    
            if ( $BatchSize ) {
                $UriParameters["per_page"] = $BatchSize
            }
        }
        process {
            $TotalReturned = 0
            Write-Progress -Activity "Querying $( $UriBase + $Uri )" -CurrentOperation "Initial Request"
            do {
                $Response = Invoke-RestMethod -Uri ( $UriBase + $Uri + '?' + ( $UriParameters | ConvertTo-QueryString ) ) -Headers $Headers -Method Get -ResponseHeadersVariable ResponseHeaders
                $TotalReturned += $Response.Count # this is just for the counter
                # For some reason I don't know each of the response headers are returned as an array - even if they only have a single element - hence the [0]
                $TotalResults = [int]( $ResponseHeaders.'X-Total-Count'[0] )
                Write-Progress -Activity "Querying $( $UriBase + $Uri )" -CurrentOperation "Found $TotalReturned of $TotalResults" -PercentComplete ( ( $TotalReturned / $TotalResults ) * 100 )
                if ( $Response ) {
                    $Response
                    $UriParameters["page"]++
                }
            } until ( $ResponseHeaders.'X-Current-Page' -eq $ResponseHeaders.'X-Total-Pages' )
            Write-Progress -Activity "Querying $( $UriBase + $Uri )" -Completed
        }
        end {
            # Nothing to see here
        }
    }
    
    $JsonWebToken = 'Your Token Goes Here'
    
    $Incidents = Get-SwsdIncident -JsonWebToken $JsonWebToken

    I've been doing a bunch of other API + PowerShell work recently and that informed my response.  Above are two functions. The one is just a string manipulation function I use a bunch when working with Query Strings to HTML, but the second has the logic.

    What's nice about the Get-SwsdIncident function is that it could easily be copy/pasted for 'categories' and the like. (just change the name and the $Uri and that's 90% of it right there.

    WARNING: This will return EVERY incident with zero filters, so use it with caution.  If I were to continue to develop this I would probably add a bunch of filter options as defined by the Incidents API documentation.

    I used the Incidents API and the bit about pagination is in General Concepts

  • And I went one step further and saved this off to a GitHub public repository.

Reply Children
No Data