API with AHK

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Sweetins
Posts: 117
Joined: 02 Jul 2017, 13:22

API with AHK

Post by Sweetins » 22 Nov 2024, 04:15

So I needed a quick and automated way of updating my database and was advised that an API would be my best bet.
You would write some code - in whatever language you want - that loops through your directory of images, and then calls the 'create-asset' API - documented here: - making sure to include the 'image' attribute, for each one.
I seem to have a handle on all but for the calling of the API, as explained here @teadrinker. Any assistance will be helpful. Thanks in advance

teadrinker
Posts: 4602
Joined: 29 Mar 2015, 09:41
Contact:

Re: API with AHK

Post by teadrinker » 23 Nov 2024, 20:16

As I understand, you at least have to specify the actual id instead of the "id" text.

Sweetins
Posts: 117
Joined: 02 Jul 2017, 13:22

Re: API with AHK

Post by Sweetins » 12 Dec 2024, 15:22

I am attempting to upload a file for a specific hardware ie hardware/2 and my script is as follow:

Code: Select all

oWhr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
oWhr.Open("PATCH", "https://user.snipe-it.io/api/v1/hardware/2", false)
oWhr.SetRequestHeader("Content-Type", "application/json")
oWhr.SetRequestHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9")

; Specify the file path
filePath := "C:\Users\User\Desktop\sample.png"

; Read the image file
FileRead, fileData, %filePath%
if (ErrorLevel) {
    MsgBox, % "Failed to read the file at " filePath ". Ensure the file exists."
    ExitApp
}

; Base64 encode the file data
base64Data := Base64Encode(fileData)

; JSON payload with the base64 image data
jsonData := "
(
{
    ""notes"": null,
    ""assigned_user"": null,
    ""assigned_location"": null,
    ""assigned_asset"": null,
    ""company_id"": null,
    ""serial"": null,
    ""order_number"": null,
    ""warranty_months"": null,
    ""purchase_cost"": null,
    ""purchase_date"": null,
    ""requestable"": false,
    ""archived"": false,
    ""rtd_location_id"": null,
    ""name"": null,
    ""location_id"": null,
    ""image"": " base64Data "
}
)"

; Send the request
oWhr.Send(jsonData)

; Check the status and response
if (oWhr.Status = 200) {
    MsgBox, % "Success! Response: `r`n" oWhr.ResponseText
} else {
    MsgBox, % "Failed with status " oWhr.Status ": `r`n" oWhr.ResponseText
}
return

; Base64 encoding function
Base64Encode(ByRef data) {
    StrPut(data, "utf-8")  ; Convert binary data to UTF-8 encoded string
    DllCall("Crypt32.dll\CryptBinaryToString", "Ptr", &data, "UInt", StrLen(data), "UInt", 1 | 0x40000000, "Ptr", 0, "UIntP", len) ; Get length
    VarSetCapacity(out, len * 2, 0)
    DllCall("Crypt32.dll\CryptBinaryToString", "Ptr", &data, "UInt", StrLen(data), "UInt", 1 | 0x40000000, "Str", out, "UIntP", len) ; Actual encoding
    return out
}
It reports success alright, but the file sample.png doesn't get uploaded. Any help pls

teadrinker
Posts: 4602
Joined: 29 Mar 2015, 09:41
Contact:

Re: API with AHK

Post by teadrinker » 12 Dec 2024, 17:13

Make sure that what you are about to send is truly meant to be sent. MsgBox will show the literal content:

Code: Select all

jsonData := "
(
{
    ""notes"": null,
    ""assigned_user"": null,
    ""assigned_location"": null,
    ""assigned_asset"": null,
    ""company_id"": null,
    ""serial"": null,
    ""order_number"": null,
    ""warranty_months"": null,
    ""purchase_cost"": null,
    ""purchase_date"": null,
    ""requestable"": false,
    ""archived"": false,
    ""rtd_location_id"": null,
    ""name"": null,
    ""location_id"": null,
    ""image"": " base64Data "
}
)"

MsgBox jsonData

Qriist
Posts: 161
Joined: 11 Sep 2016, 04:02

Re: API with AHK

Post by Qriist » 12 Dec 2024, 19:50

Sweetins wrote:
12 Dec 2024, 15:22
It reports success alright, but the file sample.png doesn't get uploaded. Any help pls
The success you see is because the raw transfer was successful. However, as best as I can tell, their API is broken. I am getting a 302 redirect to a login screen... which totally defeats the point of an API, lol.

User avatar
Ragnar
Posts: 831
Joined: 30 Sep 2013, 15:25

Re: API with AHK

Post by Ragnar » 13 Dec 2024, 03:52

I've moved this topic from Ask for Help (v2) to Ask for Help (v1).

Sweetins
Posts: 117
Joined: 02 Jul 2017, 13:22

Re: API with AHK

Post by Sweetins » 13 Dec 2024, 07:35

teadrinker wrote:
12 Dec 2024, 17:13
Make sure that what you are about to send is truly meant to be sent. MsgBox will show the literal content:

Code: Select all

jsonData := "
(
{
    ""notes"": null,
    ""assigned_user"": null,
    ""assigned_location"": null,
    ""assigned_asset"": null,
    ""company_id"": null,
    ""serial"": null,
    ""order_number"": null,
    ""warranty_months"": null,
    ""purchase_cost"": null,
    ""purchase_date"": null,
    ""requestable"": false,
    ""archived"": false,
    ""rtd_location_id"": null,
    ""name"": null,
    ""location_id"": null,
    ""image"": " base64Data "
}
)"

MsgBox jsonData
Supposedly, there are other ways to do this that works as shown here. What am attempting was advised as shown in the attached screenshot but they couldn't provide any help because the languages suggested didn't include AHK.
Attachments
Screenshot.png
Screenshot.png (543.18 KiB) Viewed 265 times

Sweetins
Posts: 117
Joined: 02 Jul 2017, 13:22

Re: API with AHK

Post by Sweetins » 13 Dec 2024, 07:43

Qriist wrote:
12 Dec 2024, 19:50
The success you see is because the raw transfer was successful. However, as best as I can tell, their API is broken. I am getting a 302 redirect to a login screen... which totally defeats the point of an API, lol.

Code: Select all

oWhr.SetRequestHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9")
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9" is modified just for the purposes of this post.

Qriist
Posts: 161
Joined: 11 Sep 2016, 04:02

Re: API with AHK

Post by Qriist » 13 Dec 2024, 09:11

Sweetins wrote:
13 Dec 2024, 07:43
"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9" is modified just for the purposes of this post.
I'm aware. I pulled the example from their PATCH method and the example on the page is giving a redirect. I don't know if you were getting a redirect as your example doesn't check anything except the status of the raw transfer, which itself really just means your internet is on.
https://snipe-it.readme.io/reference/hardware-partial-update
Sweetins wrote:
13 Dec 2024, 07:35
Supposedly, there are other ways to do this that works as shown here. What am attempting was advised as shown in the attached screenshot but they couldn't provide any help because the languages suggested didn't include AHK.
The tool that is being used in those example is cURL. I'm very familiar with cURL as I've been writing a library for it. The actual programming language details on that page are irrelevant because the underlying example is broken.

Code: Select all

curl -v -i --request PATCH      --url https://develop.snipeitapp.com/api/v1/hardware/id      --header "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiZTU2MDc0MjVmYjM5YTEwYjFjNTZlZTAxMTBmZDk4ZjQ0ZjVjODMzYjcxZWVhYjZlNDk1NGMwOThlY2YzMzU2MDY4Mzg4MmFhMDMzOTAzNzciLCJpYXQiOjE2MzI4NjU5MTgsIm5iZiI6MTYzMjg2NTkxOCwiZXhwIjoyMjY0MDIxNTE4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.LgGVzyH67IRhXvccHd4j2Dn6TDuIuQTBoo30_wD9jPehy8v_h0xBmE1-dOUBRJyeJOI8B4gwPeALsWaudpGj9Lb5qWAtKV7eYtH9IYQKoLF_iHgOGXnAUcNwID6zBU_YyLNSI6gp8zjutLJias33CBLsHy5ZRNpxVibVrZouJ_HjYuIYbtZyLus-KFFeibtZoPiTWOeHhQFD37MR6ifx4dBqT37fN-xDS99mONtrkAplEIou5aSO1oZ4IlJIPCUyA1lixPgpn1YU7PxiBDZp1teeugD0WEmrAqxRS2I0bH4qPsuTsrVXS_lo87Sf5LBGLW7lGHKqyYH6J47OZOM0K-SrxLKtE1ww8jyLBgnnxH0lJHRLCBiwUnL5ZGTUmiOysUA-wSJ6s78o8Pc-ec6bpBvAlelHdiQ-wslE7gzEJDptbejFg-75b_CEwgJYh7J2D18ul6Qu5EFCUEgt033mm04dgVk0isWTDt6EW5ZvTo5Qhr1LY0YnEIXCTqIRN-BSQjL55sZaCrtwR_21bnBGgniyI5MRDYblFawVmFKroeClCpSjBo9vi66akdD5hjpvx67RL3r33BZQhEXmPifUPNH5wP_U-IHGFUD99TJk2c1awF0RASveZRLSunbJb1x6hGAVUaIvQV4r2quWzXqYyKLph9kGTyJYrb6iJtH5smE"      --header "accept: application/json"      --header "content-type: application/json"       --data "{\"notes\": \"null\",  \"assigned_user\": null,  \"assigned_location\": null,  \"assigned_asset\": null,  \"company_id\": null,  \"serial\": \"null\",  \"order_number\": \"null\",  \"warranty_months\": null,  \"purchase_cost\": null,  \"purchase_date\": \"null\",  \"requestable\": false,  \"archived\": false,  \"rtd_location_id\": null,  \"name\": \"null\",  \"location_id\": \"null\"}"

Code: Select all

HTTP/1.1 302 Found
Server: nginx
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=0, must-revalidate, no-cache, no-store, private
Date: Fri, 13 Dec 2024 13:55:55 GMT
Location: https://develop.snipeitapp.com/login
Access-Control-Allow-Origin: *
Pragma: no-cache
Expires: Sun, 02 Jan 1990 00:00:00 GMT
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Feature-Policy: accelerometer 'none';autoplay 'none';camera 'none';display-capture 'none';document-domain 'none';encrypted-media 'none';fullscreen 'none';geolocation 'none';sync-xhr 'none';usb 'none';xr-spatial-tracking 'none'
Referrer-Policy: same-origin
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self';style-src 'self' 'unsafe-inline';script-src 'self' 'unsafe-inline' 'unsafe-eval';connect-src 'self';object-src 'none';font-src 'self' data:;img-src 'self' data: https://develop.snipeitapp.com  https://snipe-flysystem-public-test.s3-us-west-2.amazonaws.com/ https://secure.gravatar.com http://gravatar.com maps.google.com maps.gstatic.com *.googleapis.com
Set-Cookie: snipeitv5demo_session=H998ENFAFO8Nh7ShtP7mbuHFXdNPXydQ7uBqESY4; path=/; domain=develop.snipeitapp.com; secure; httponly

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='https://develop.snipeitapp.com/login'" />

        <title>Redirecting to https://develop.snipeitapp.com/login</title>
    </head>
    <body>
        Redirecting to <a href="https://develop.snipeitapp.com/login">https://develop.snipeitapp.com/login</a>.
    </body>
</html>
Now, I had consider that it's possible that the page just has an outdated sample token. Sure, it happens. The obvious next move of making an account to acquire my own account token didn't work. As far as I can tell, there's no free signup on the site, despite a free account being listed on their feature comparison table. The "Free" option lacks a clickable link and the drop down menus on the paid links do not list a Free tier. https://snipeitapp.com/pricing

I'd be willing to troubleshoot further but right now everything on that site that I have access to is broken. If you're willing to trust your private Bearer token to the random stranger on the internet trying to help you then you can DM me and we can go from there. You can also try inserting your Bearer token into my sample curl command above to see if you get anything besides a redirect to a login.

Edit: I tried again after replying and I got a completely different response. So idk.

Code: Select all

HTTP/1.1 404 Not Found
Server: nginx
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=0, must-revalidate, no-cache, no-store, private
date: Fri, 13 Dec 2024 14:32:15 GMT
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 9
Access-Control-Allow-Origin: *
Pragma: no-cache
Expires: Sun, 02 Jan 1990 00:00:00 GMT
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Feature-Policy: accelerometer 'none';autoplay 'none';camera 'none';display-capture 'none';document-domain 'none';encrypted-media 'none';fullscreen 'none';geolocation 'none';sync-xhr 'none';usb 'none';xr-spatial-tracking 'none'
Referrer-Policy: same-origin
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self';style-src 'self' 'unsafe-inline';script-src 'self' 'unsafe-inline' 'unsafe-eval';connect-src 'self';object-src 'none';font-src 'self' data:;img-src 'self' data: https://develop.snipeitapp.com  https://snipe-flysystem-public-test.s3-us-west-2.amazonaws.com/ https://secure.gravatar.com http://gravatar.com maps.google.com maps.gstatic.com *.googleapis.com
Set-Cookie: snipeitv5demo_session=e6I7toZ5lIOTPk79RaiQUvf4HLsgdVlKmxwNMEmr; path=/; domain=develop.snipeitapp.com; secure; httponly

<!DOCTYPE html>
<html lang="en-US">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Snipe-IT Asset Management Demo</title>

    <link rel="shortcut icon" type="image/ico" href="https://develop.snipeitapp.com/favicon.ico">
    
    <link rel="stylesheet" href="https://develop.snipeitapp.com/css/dist/all.css?id=fa28de72acfa72bfdd7ad4206a65d4eb">

    <script nonce="ZlYzDbjmtGQy6punlfqaoU5fPg3zHbyLDED4qWbX">
        window.snipeit = {
            settings: {
                "per_page": 50
            }
        };
    </script>


    
    
</head>

<body class="hold-transition login-page">

            <center>
            <a href="https://develop.snipeitapp.com"><img id="login-logo" src="https://develop.snipeitapp.com/uploads/snipe-logo.png"></a>
        </center>
      <!-- Content -->
  


<div class="row">
  <div class="col-md-8 col-md-offset-2">

    <div style="padding-top: 200px">
      <img src="https://develop.snipeitapp.com/img/sad-panda.png" style="width: 200px; height: 200px;" class="pull-left">
            <div class="error-content">
              <h2><i class="fas fa-exclamation-triangle text-yellow" aria-hidden="true"></i> 404 Page not found.</h2>
              <p>
                Sad panda. We could not find the page you were looking for.
                You should maybe <a href="https://develop.snipeitapp.com">return to the dashboard</a>.
              </p>

    </div>
</div>



    <div class="text-center" style="padding-top: 100px;">
            </div>

    
    <script src="https://develop.snipeitapp.com/js/dist/all.js?id=074c4b862b013dbffef2b075b6aae802" nonce="ZlYzDbjmtGQy6punlfqaoU5fPg3zHbyLDED4qWbX"></script>


    </body>

</html>
I'm convinced that their examples are broken.

Post Reply

Return to “Ask for Help (v1)”