API



  • Hi guys,

    I’ve noticed in recent RC’s that an API is being implemented and wondered if there is any basic info on how to use it ?
    I’ve searched google and the forums but can’t seem to find any info.


  • Moderator


  • Senior Developer

    basicconfig.ps1

    <# Config for our scripts.
        .SYNOPSIS
            Just used to store our common variables that we don't want to
            recode for every script.
        .USAGE
            No related usage, just sets variables.
    #>
    $fogApiToken = "TokenFromGUIForAPIAccess";
    $fogUserToken = "TokenFromGUIForUserToken";
    $endpointURL = "http://fogserver/fog/";
    

  • Senior Developer

    @george1421 There’ s a simpler method

    Here’s some scripts that I run.

    This is specific to my needs on a different project, but could be converted as needed.

    buildheaders.ps1

    <# Build headers script help
        .SYNOPSIS
            This powershell script just creates a single point for building headers
            rather than constantly rewriting the same script over and over.
        .USAGE
            This just sources the function so there is no real usage here.
    #>
    function Build-Headers {
        Param(
            [string]$authorizationString,
            [string]$tenantCode,
            [string]$acceptType,
            [string]$contentType
        )
        
        $header = @{
            "fog-api-token" = $fogApiToken;
            "fog-user-token" = $fogUserToken;
            #"Accept" = $accept;
            "Content-Type" = $contentType
        }
    
        Write-Verbose("");
        Write-Verbose("---------- Headers ----------");
        Write-Verbose("Authorization: " + $authorizationString);
        Write-Verbose("fog-api-token: " + $fogApiToken);
        Write-Verbose("fog-user-token: " + $fogUserToken);
        Write-Verbose("Accept: " + $acceptType);
        Write-Verbose("Content-Type: " + $contentType);
        Write-Verbose("-----------------------------");
        Write-Verbose("");
    
        Return $header
    }
    

    Use case script – To create a task for a host with say ID # 10.

    taskhost.ps1

    <# Creates Task for id passed in to script.
        .SYNOPSIS
            Helps create task from command line.
        .PARAMETER id (required)
            This is the ID Of the Host to task.
        .PARAMETER configFile (optional)
            This is not a required file, this allows you to use a different
            basicconfig.ps1 file if need be.
    #>
    [CmdletBinding()]
        Param(
            [Parameter(Mandatory=$True)]
            [string]$id,
    
            [Parameter()]
            [string]$configFile
        )
    
    # Set errors to silent if we are not in verbose mode.
    If (!$PSCmdlet.Myinvocation.BoundParameters["Verbose"].IsPresent) {
        $ErrorActionPreference = "SilentlyContinue"
    }
    
    # Setup up defailt if configFile is not already set.
    If (!$configFile) {
        $configFile = '.\basicconfig.ps1'
    }
    
    # Load our config file.
    . $configFile
    
    # Set our base call (item) for the api.
    $baseURL = $endpointURL + "/host/" + $id + "/task"
    
    # Source build headers function.
    . ".\buildheaders.ps1"
    
    # We know we're using json so set accept/content type as such.
    $contentType = "application/json"
    
    # Get our headers Building off the config file information.
    $headers = Build-Headers $fogApiToken $fogUserToken $contentType $contentType
    
    # Display what url we are calling so somebody could use it later if in verbose.
    Write-Verbose ""
    Write-Verbose "---------- Caller URL ----------"
    Write-Verbose ("URL: " + $baseURL)
    Write-Verbose "--------------------------------"
    Write-Verbose ""
    
    $dataSet = @{
        "taskTypeID" = 1
        "shutdown" = true
    }
    
    $dataToSend = ($dataSet | ConvertTo-JSON)
    
    # Display the data we're sending
    Write-Verbose ""
    Write-Verbose "---------- Sending Body ----------"
    Write-Verbose $dataToSend
    Write-Verbose "----------------------------------"
    Write-Verbose ""
    
    # Perform the request
    $ret = Invoke-RestMethod -Method Post -Uri $baseURL -Headers $headers -ContentType $contentType -Body $dataToSend
    
    # Write our return information if there is anything to see.
    Write-Verbose ""
    Write-Verbose "---------- Returned Data ----------"
    Write-Verbose $ret
    Write-Verbose "-----------------------------------"
    Write-Verbose ""
    
    # All Done
    

    You would have all three files in the same place and call from powershell:
    .\taskhost.ps1 -id 10

    Hopefully this helps. Of course it could be more generalized, but I’m just giving a basic overview.


  • Moderator

    @UWPVIOLATOR Warning: I’m not a programmer (or even know how to program in PS) and sometimes I even question if I know what I doing here…

    But I think I was able to translate one of Wayne’s posts with a curl call into powershell.

    curl --silent -k -H 'Content-Type: application/json' -H 'fog-user-token: ZjBkMmE3YmI5NmUzZDcxYTliYzNkZTc4MmJhNTFiYTQ3Mzc2MTg5MzYxMThmNjA5NDYyMjllMTA5YzE0NWUxMjFiNzkyMTc5OTMwZjFhZGM5NWIxMTc3YWZmNTU2MmMwYjFhNjg0NjVmMTkyMGZkNDQxYmY0MzI1NWNkMzQyM2M=' -H 'fog-api-token: MzI2NDY1NjY2NjM0MzUzMDMzMzA2MzM1MzEzNzYyMzg2NTYyNjQ2MjMxMzczMTM0NjY2NDM0NjUzOTM2NjIzNDM4MzQ2NDM3MzY2MzM2MzMzNjYyMzUzODY0MzUzNDYyMzgzMDY2NjQzNTMxMzI2MzM5NjYzNjYzMzMzMzM0MzA=' http://10.0.0.28/fog/host/testhost1/task -d '{"taskTypeID":1,"shutdown": true}'
    

    would translate into something like this:

    $headers = @{}
    $headers.Add("fog-user-token", "ZjBkMmE3YmI5NmUzZDcxYTliYzNkZTc4MmJhNTFiYTQ3Mzc2MTg5MzYxMThmNjA5NDYyMjllMTA5YzE0NWUxMjFiNzkyMTc5OTMwZjFhZGM5NWIxMTc3YWZmNTU2MmMwYjFhNjg0NjVmMTkyMGZkNDQxYmY0MzI1NWNkMzQyM2M=")
    $headers.Add("fog-api-token", "MzI2NDY1NjY2NjM0MzUzMDMzMzA2MzM1MzEzNzYyMzg2NTYyNjQ2MjMxMzczMTM0NjY2NDM0NjUzOTM2NjIzNDM4MzQ2NDM3MzY2MzM2MzMzNjYyMzUzODY0MzUzNDYyMzgzMDY2NjQzNTMxMzI2MzM5NjYzNjYzMzMzMzM0MzA=")
    
    $mydata = @{}
    $mydata.Add("taskTypeID", "1")
    $mydata.Add("shutdown", "true")
    
    $json = $mydata | ConvertTo-Json
    $Uri = 'http://10.0.0.28/fog/host/testhost1/task'
    
    Invoke-WebRequest -Method Post -Uri $Uri -Header $header -Body $json -ContentType 'application/json'
    
    

  • Moderator

    @UWPVIOLATOR Not the answer you are looking for, but a bit more details that Wayne uses for FOG scripting. https://forums.fogproject.org/topic/9779/can-i-use-some-kind-of-script-to-create-image-and-ghost-my-lab-machines/15



  • @theWizard

    What did your Powershell command look like? I would like to see that example. I am most familiar with it and the one main thing I need to work on is a for each from a csv file with all of our old junked computers and laptops returned from lease. We no longer need them in fog.



  • @Tom-Elliott
    I’m using powershell with Invoke-WebRequest which is alias for curl


  • Senior Developer

    @theWizard I don’t follow.

    What are you using as a test, exactly?



  • @Tom-Elliott said in API:

    curl -H ‘fog-api-token: abcde’ -H ‘fog-user-token: fghij’ -X GET http://fogserver/fog/task/current

    Thankyou perhaps i will have to wait as anything i try results in
    The requested URL /fog/task/current was not found on this server.


  • Senior Developer

    This is just a quick means to represent how you could filter the tasks if you needed to as well.

    Our “List all tasks” works without a body sent, but CAN be filtered to get specific information for active tasks. The example just shows how you might want to get active tasks for host ids of 5 and 6. I’m not trying to show actual payload right now. Just trying to show example use cases.

    So let’s do this command line style:
    Let’s just say your api token is abcde
    Let’s just say your user token is fghij
    List all current/active tasks is a GET request.
    URL for now is just fogserver

    curl -H 'fog-api-token: abcde' -H 'fog-user-token: fghij' -X GET http://fogserver/fog/task/current -o listalltasks.json -d '{"hostID":[5,6]}'
    

  • Moderator

    #wiki worthy


  • Senior Developer

    @theWizard

    List all active tasks:

    header('fog-api-token: <FOG Configuration Page->FOG Settings->API Settings->FOG_API_TOKEN>');
    header('fog-user-token: <User management page->relevant user->API Settings->User API Token>');
    http://fogserverip/fog/task/active
    

    So let’s do this command line style:
    Let’s just say your api token is abcde
    Let’s just say your user token is fghij
    List all current/active tasks is a GET request.
    URL for now is just fogserver

    curl -H 'fog-api-token: abcde' -H 'fog-user-token: fghij' -X GET http://fogserver/fog/task/current -o listalltasks.json
    

    This will list all current/active tasks to a file in the current working directory named listalltasks.json

    For creating a snapin task, this depends how you plan to do it. To be honest, while the option is available, it’s not something I’ve worked overly hard to get working “natively”. It was originally only designed to allow host and group, though I saw the appeal and added capabilities.

    So let’s just say you have a snapin associated to a host.

    The snapin ID is: 6
    The host ID is: 1

    This would be a POST request as per the earlier information.

    The URL you would call would be:

    http://fogserver/fog/host/1/task

    The post requires some information, and luckily I kind of documented the “maximum” and “minimum” information for creating a tasking in this way.

    The “data to send” would be, at minimum:

    {
        "taskTypeID": <IDOFTASKTYPETOUSE>
    }
    

    For a “snapin” task, this is ID’s 12 or 13. important to remember which is a single snapin, vs. all snapin though.

    The “full” information you could send for tasking in a manner as above is:

    {
        "taskTypeID": <IDOFTASKTYPE>,
        "taskName": "NameToGiveTasking",
        "shutdown": <bool>true/false,
        "debug": <bool>true/false,
        "deploySnapins": <bool>/<IDOFSNAPIN or -1 for all>,
        "passreset": "what to change password if passreset task",
        "sessionjoin": "<SessionNameToJoin>",
        "wol": <bool>
    }
    

    In your case, with a specific known host and snapin to send you could do:

    curl -H 'fog-api-token: abcde' -H 'fog-user-token: fghij' -H 'Content-Type: application/json' -X POST -d '{"taskTypeID":13,"deploySnapins":6}' http://fogserver/fog/host/1/task
    

    This should create the tasking for you as you described. (Task Type ID 13 = Single Snapin Task, deploy Snapins is true/false/-1 = all/<IDOFSNAPIN>


  • Moderator

    @theWizard The API is RESTful based. You might want to do a quick read up on RESTful interfaces. https://www.tutorialspoint.com/restful/

    Once the API is finished we will create guidance on using it. Actually what Tom posted below is the first time this information was made publicly available.

    Please give us some time to get the documentation in line with the advances the developers are making in the code.



  • @Tom-Elliott said in API:

    fog-api-token

    Hi Tom
    Thanks you for the detailed response much appreciated, i feel rather stupid asking but i don’t suppose you have a couple of examples to follow do you ?
    Say for instance if i wanted to list all active tasks or even add a snapin task.


  • Senior Developer

    Right now there isn’t much in terms of documentation. We are working toward getting there.

    Understand the API system is very new, but as much as I could “simply” implemented.

    What I mean with this:

    1. Data body or return is done with JSON.
    2. All objects in the core have some ability to managed with the API system with the only exception, so far, being Users.

    There are a few important bits in regards to interacting and using the API System.

    1. API Can be globally enabled/disabled.
    2. API Can be user enabled/disabled. – (You can define which users you want to have access to the api system.)

    Tokens:

    1. API Global token is a header required with the name fog-api-token
    2. API User token is a header that can be used (Highly recommended) being passed as a header in the form fog-user-token
    3. You can not manually create the tokens via the presented text fields. This is what the purpose of the “Reset Token” Buttons are. There’s a Reset Token for the global API as well as one for each user.
    4. Tokens are cryptographically generated so no two tokens will be known regardless of how many FOG Server’s you decide to install. There is no “default” token essentially. This holds true for both User and Main API Tokens.

    Authentication:
    You can use HTTP Basic Authorization (with curl -u <user>:<password> or header with name Authorization: Basic <base64encoded username:password>
    Although I have allowed the ability for this type of authentication, and it will work, I would still recommend using user token system as it cannot be received and decoded to a valid username/password pair to manage your fog server.

    Routes and Methods:

    GET

    1. /fog/system/info Returns 200 if accessible
    2. /fog/system/status Alias for #1
    3. /fog/<objectactivetasktype>/current Returns listing of “active” items. Active referring task types, (Snapin Task, Snapin Job, Task, Scheduled, Multicast)
    4. /fog/<objectactivetasktype>/active Alias for #3
    5. /fog/<object>/search/<whatareyousearchingfor> Idea is similar to the Search Page from GUI.
    6. /fog/<object> Same idea as “List all”
    7. /fog/<object>/<IDOFOBJECT> Same as if clicking edit on an item (only just to get its information).

    PUT (Requires a json body)

    1. /fog/<object>/<IDOFOBJECT>/edit Update the object.
    2. /fog/<object>/<IDOFOBJECT>/update Alias for #1

    POST (Requires a json body)

    1. /fog/<objecttasktype>/<IDOFOBJECT>/task Task object.
    2. /fog/<object>/create Create new object.
    3. /fog/<object>/new Alias of #2.

    DELETE

    1. /fog/<objectactivetasktype>/cancel Cancel specific items (requires json body)
    2. /fog/<objecttasktype>/<IDOFOBJECT>/cancel Cancel specific task for object.
    3. /fog/<object>/<IDOFOBJECT>/delete Delete/Remove object.
    4. /fog/<object>/<IDOFOBJECT>/remove Alias of #3

    HEAD

    1. /fog/system/info Returns 200 if accessible
    2. /fog/system/status Alias for #1

    I realize this is not a full on “here’s everything” but it’s something that should be able to help get you along the path.

    Core <object>

    1. clientupdater
    2. dircleaner
    3. greenfog
    4. group
    5. groupassociation
    6. history
    7. hookevent
    8. host
    9. hostautologout
    10. hostscreensetting
    11. image
    12. imageassociation
    13. imagepartitiontype
    14. imagetype
    15. imaginglog
    16. inventory
    17. ipxe
    18. keysequence
    19. macaddressassociation
    20. module
    21. moduleassociation
    22. multicastsession
    23. multicastsessionsassociation
    24. nodefailure
    25. notifyevent
    26. os
    27. oui
    28. plugin
    29. powermanagement
    30. printer
    31. printerassociation
    32. pxemenuoptions
    33. scheduledtask
    34. service
    35. snapins
    36. snapinassociation
    37. snapingroupassociation
    38. snapinjob
    39. snapintask
    40. storagegroup
    41. storagenode
    42. task
    43. tasklog
    44. taskstate
    45. tasktype
    46. usercleanup
    47. usertracking
    48. virus

    Core <objecttasktype>

    1. group
    2. host
    3. multicastsession
    4. snapinjob
    5. snapintask
    6. task

    Core <objectactivetasktype>

    1. multicastsession
    2. scheduledtask
    3. snapinjob
    4. snapintask
    5. task

    Routes that allow filtering with JSON body passed

    GET

    1. /fog/<object>
    2. /fog/<objectactivetasktype>/active
    3. /fog/<objectactivetasktype>/current

    DELETE

    1. /fog/<objectactivetasktype>/cancel

    Plugin’s Compatibility.

    I have worked relatively hard to implement capability for plugins to also tie in with this. This means hooks can be used to implement API level functionality with plugins or custom elements you’d like to use.

    Hook Event Names what core element it ties in with:

    1. API_VALID_CLASSES, variable to adjust is labeled ‘validClasses’. Ties in with <object> items.
    2. API_TASKING_CLASSES, variable to adjust is labeled ‘validTaskingClasses’. Ties in with <objecttasktype> items.
    3. API_ACTIVE_TASK_CLASSES, variable to adjust is labeled ‘validActiveTasks’. Ties in with <objectactivetasktype> items.
    4. API_MASSDATA_MAPPING, variables to adjust are labeled ‘data’, ‘classname’, and ‘classman’. Operates on the “list” and “search” type routes.
    5. API_INDIVDATA_MAPPING, variables to adjust are labeled ‘data’, ‘classname’, and ‘class’. Operates on individual objects such as /fog/<object>/<IDOFOBJECT>
    6. API_GETTER, variables to adjust are labeled ‘data’, ‘classname’, and ‘class’. Operations for all items and is used to present the return of data in a common way regardless of what object is being called.
    • In regards to #6 of the Hook Event elements, think of it as this:
      If I request information about a task, one of the elements of a task is the “host” object. The data presented in the “Task” return for a specific host will look the same in the task return as it would if you looked the host up individually. For example, if the task is using a hostID of 7, the ‘host’ item in this element would look identical to the return data if you were go to route /fog/host/7

Log in to reply
 

459
Online

38959
Users

10706
Topics

101583
Posts

Looks like your connection to FOG Project was lost, please wait while we try to reconnect.