Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

Getting a cURL command to work in Xbasic

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Getting a cURL command to work in Xbasic

    I'm struggling to get an API call to work in Alpha. I'm using it to create a draft email in the Front app (https://dev.frontapp.com/reference/p...nnel-id-drafts). I finally was able to get it to work in Postman, but now I need to be get this cURL command working in Xbasic, and progress is painfully slow. Here is the cURL command, which works perfectly in Postman:

    curl --location --request POST 'https://api2.frontapp.com/channels/cha_123/drafts' \
    --header 'Authorization: Bearer <token>' \
    --form 'author_id="tea_123"' \
    --form 'to[]="[email protected]"' \
    --form 'subject="test subject 3"' \
    --form 'body="test message 3"' \
    --form 'attachments=@"/E:/myfiles/test.jpg"'

    How can I make this work in Xbasic? The CURL to Xbasic genie doesn't seem to help much.
    Last edited by Lenny Forziati; 07-12-2022, 04:46 PM. Reason: removed authorization token

    #2
    The CURL to Xbasic genie doesn't seem to help much.
    Where is this falling down for you?
    Sarah Mitchell
    Director of Customer Success | [URL="https://www.alphasoftware.com"]Alpha Software Corporation[/URL]
    [B]Get in the know! [/B] Join us for our Weekly Webinars: [URL="https://www.alphasoftware.com/weekly-transform-tuesday-webinar"]TransForm Tuesday[/URL] and [URL="https://www.alphasoftware.com/weekly-alpha-anywhere-overview-webinar"]Wednesday's Alpha Anywhere Demo and Q&A[/URL]
    Connect with us: [URL="https://www.instagram.com/alpha_software_corp/"]Instagram[/URL] | [URL="https://twitter.com/AlphaSoftware"]Twitter[/URL] | [URL="https://www.facebook.com/AlphaSoftware/"]Facebook[/URL] | [URL="https://www.linkedin.com/company/alpha-software"]LinkedIn[/URL] | [URL="https://www.youtube.com/user/AlphaSoftwareInc"]YouTube[/URL]

    Comment


      #3
      If I use the genie, it generates this code:

      dim cf_1 as extension::CurlFile
      dim flag_1 as l
      dim slist1[0] as c = [ "Authorization: Bearer <token>" ]
      dim ce as extension::Curl

      ce = extension::Curl.Init()
      ce.setOpt("BUFFERSIZE",102400)
      ce.setOpt("URL","https://api2.frontapp.com/channels/cha_123/drafts")
      dim posted_fields as c = ("--form 'author_id="tea_123"' --form 'to[]="[email protected]"' --form 'subject="test subject 3"' --form 'body="test message 3"' --form 'attachments=@"/E:/myfiles/test.jpg"'")
      ce.setOpt("POSTFIELDS",posted_fields)
      ce.setOpt("POSTFIELDSIZE_LARGE", len(posted_fields) )
      ce.setOpt("HTTPHEADER",slist1)
      ce.setOpt("USERAGENT","curl/7.81.0")
      ce.setOpt("MAXREDIRS",50)
      ce.setOpt("CAINFO",a5.Get_Exe_Path()+"\caroot\ca-cert.pem")
      ce.setOpt("CAPATH",a5.Get_Exe_Path()+"\caroot")
      ce.setOpt("PROXY_CAPATH", a5.get_exe_path() + "\caroot")
      ce.setOpt("FTP_SKIP_PASV_IP",1)
      ce.setOpt("TCP_KEEPALIVE",1)
      ce.SetOpt("FILE",cf_1)
      flag_1 = ce.Exec()
      if flag_1 then

      dim headers as c
      dim contents as c
      headers = cf_1.GetHeaders()
      contents = cf_1.GetContent()

      'BE SURE TO COMMENT OUT THIS CODE IN A WEB APPLICATION AS showVar() CANNOT BE USED IN WEB APPLICATIONS
      dim msg as c
      msg = "Headers: " + crlf() + headers + crlf() + "Content: " + contents
      showvar( msg)


      else
      dim errors as c
      errors = ce.error()

      'BE SURE TO COMMENT OUT THIS CODE IN A WEB APPLICATION AS showVar() CANNOT BE USED IN WEB APPLICATIONS
      showvar("error: " + errors)
      end if
      ce.close()
      When I make the API call, this returns "Content: {"_error":{"status":400,"title":"Bad request","message":"Body did not satisfy requirements","details":["body.author_id: missing","body.body: missing"]}}"

      If I don't use the genie, but just use the "Generate Xbasic" button, I get this code, which is obviously inadequate:

      dim ce as extension::Curl

      ce = extension::Curl.Init()
      ce.setOpt("BUFFERSIZE",102400)
      ce.setOpt("URL","https://api2.frontapp.com/channels/cha_123/drafts")
      ce.close()

      Comment


        #4
        Hi Nathan,
        The code shown below is the base you'll need for using the http_fetch function.
        I'm available to help if you still need it.
        I usually ask that you show a successful test call with the api (preferably using the http option from their documentation site).

        Code:
        POST /channels/cha_123/drafts HTTP/1.1
        Accept: application/json
        Content-Type: application/json
        Host: api2.frontapp.com
        {"mode":"shared"}
        Gregg
        https://paiza.io is a great site to test and share sql code

        Comment


          #5
          It looks to be the way you are using posted fields with Xbasic curl looking at the error you are getting. the format of the curl

          HTML Code:
          curl --request POST \
          --url https://api2.frontapp.com/channels/cha_123/drafts \
          --header 'Accept: application/json' \
          --header 'Content-Type: application/json' \
          --data '
          {
           "mode": "private",
           "author_id": "tea_123"
          ...
          }
          '
          Alex Collier

          "The spread of computers and the Internet will put jobs in two categories. People who tell computers what to do, and people who are told by computers what to do"

          AA Builds from 5221_5152 to Pre-releases >> Deploying to IIS in AWS

          Comment


            #6
            I'm trying this again using http_fetch(). I can get this to work using the following function (with items in <>brackets replaced with actual data):

            Code:
            FUNCTION testAPI3 AS C ( )
            dim settings as p
            settings.host = "api2.frontapp.com"
            settings.page = "/channels/<channel_id>/drafts"
            settings.method = "POST"
            settings.ssl_on = .t.
            settings.header = <<%txt%
            Accept: application/json
            Content-Type: application/json
            Authorization: Bearer <token>
            %txt%
            settings.body = <<%json%
            {
            "author_id": "<auth_id>",
            "to": [
            "<email>"
            ],
            "subject": "Test subject",
            "body": "Test body"
            }
            %json%
            result = http_fetch(settings)
            if (result.error_code <> 0) then
            showvar(result)
            else if (result.parsed_headers.status_code == 201) then
            ' API returns 201 (Created) if successful
            showvarjson(result.body)
            else
            showvar(result)
            end if
            END FUNCTION
            This creates a draft email in Front. However, I also want to include attachments, and according to their documentation, I have to use "Content-Type: multipart/form-data" in order to do that. If I change the Content-Type to that, it returns "Bad request: content-type missing boundary". So I added the boundary, as in the following function, which works, but the file does not get uploaded:

            Code:
            FUNCTION testAPI3 AS C ( )
            dim settings as p
            settings.host = "api2.frontapp.com"
            settings.page = "/channels/<channel_id>/drafts"
            settings.method = "POST"
            settings.ssl_on = .t.
            settings.header = <<%txt%
            Content-Type: multipart/form-data;boundary="boundary"
            Authorization: Bearer <token>
            %txt%
            settings.body = <<%txt2%
            --boundary
            Content-Disposition: form-data; name="author_id"
            
            <auth_id>
            --boundary
            Content-Disposition: form-data; name="to[]"
            
            <email>
            --boundary
            Content-Disposition: form-data; name="subject"
            
            Test Subject
            --boundary
            Content-Disposition: form-data; name="body"
            
            Test body
            --boundary
            Content-Disposition: form-data; name="attachments"; filename="example.jpg"
            
            @<filepath>
            --boundary--
            %txt2%
            result = http_fetch(settings)
            if (result.error_code <> 0) then
            showvar(result)
            else if (result.parsed_headers.status_code == 201) then
            ' API returns 201 (Created) if successful
            showvarjson(result.body)
            else
            showvar(result)
            end if
            END FUNCTION

            Comment


              #7
              Any advice on how to get file attachments to work, either with http_fetch() or cURL?

              Comment


                #8
                Hi Nathan,

                I can't stress enough how valuable the sample is in their documentation.
                Run it through that, and then look at the code they provide.
                Gregg
                https://paiza.io is a great site to test and share sql code

                Comment


                  #9
                  Thanks for your response. Unfortunately, so far I've been unsuccessful in working through this using their documentation (https://dev.frontapp.com/reference/p...nnel-id-drafts). When I put in all the data in the fields, and then use the "CURL command to Xbasic" genie to generate the Xbasic needed to run it, it works, except that the attachment is not uploaded. I expect this is because the documentation states that if attachments are used, then I must use Content-Type: multipart/form-data, and a link is given to another page which provides an example (https://gist.github.com/hdornier/e04...f46ff8a539a4cb). If I use the example given there to create an API call in PostMan, it works great. If I use the "CURL command to Xbasic" genie to generate the Xbasic needed to run the code produced by Postman, I get this response, as described in my second post on this thread:
                  Code:
                  Content: {"_error":{"status":400,"title":"Bad request","message":"Body did not satisfy requirements","details":["body.author_id: missing","body.body: missing"]}}

                  Comment


                    #10
                    Use the html option.
                    Based on what I saw lookng at the documentation screen, you need to put data into the
                    author_id box and the body box.

                    I'm more than willing to do a screen-sharing / phone session to work through this.
                    Gregg
                    https://paiza.io is a great site to test and share sql code

                    Comment


                      #11
                      This issue still has me stumped. A week ago Sarah told me that the Alpha team identified the issue in the CURL to Xbasic genie, that it does not generate the Xbasic to include the form values, and they are working on a solution. In the meantime, if anyone has had success using Xbasic to make an API call that uses "Content-Type: multipart/form-data" and successfully uploads a file, I would be glad to hear from you!

                      Comment


                        #12
                        Code:
                        dim yourToken    as c = "your API token goes here"
                        dim attachment    as c = "c:\dev\socket.txt" '"E:\myfiles\test.jpg"
                        dim formdata[0]    as p
                        formdata[].name = "author_id"
                        formdata[..].value = "tea_123"
                        formdata[].name = "to[]"
                        formdata[..].value = "[email protected]"
                        formdata[].name = "subject"
                        formdata[..].value = "test subject 3"
                        formdata[].name = "body"
                        formdata[..].value = "test message 3"
                        formdata[].name = "attachements"
                        formdata[..].filename = file.filename_parse(attachment, "NE")
                        formdata[..].value = file.to_blob(attachment)
                        
                        dim boundary    as c = "--------------------------" + remspecial(api_uuidcreate())
                        dim req            as p
                        dim resp        as p
                        dim req.host    as c = "api2.frontapp.com"
                        dim req.page    as c = "/channels/cha_123/drafts"
                        dim req.method    as c = "POST"
                        dim req.header    as c = "Authorization: Bearer " + yourToken + crlf() + "Content-Type: multipart/form-data; boundary=" + boundary
                        dim req.ssl_on    as l = .t.
                        dim req.body    as b
                        dim element        as p
                        for each element in formdata
                            req.body = req.body + boundary + crlf()
                            req.body = req.body + "Content-Disposition: form-data; name=" + s_quote(element.name)
                            if eval_valid("element.filename")
                                req.body = req.body + "; filename=" + s_quote(element.filename)
                            end if
                            req.body = req.body + crlf() + element.value + crlf()
                        next element
                        req.body = req.body + crlf() + "--" + boundary + "--"
                        
                        resp = http_fetch(req)
                        showvar(resp)
                        Last edited by Lenny Forziati; 11-23-2022, 01:30 PM. Reason: Edited script to include fixes discussed below

                        Lenny Forziati
                        Vice President, Internet Products and Technical Services
                        Alpha Software Corporation

                        Comment


                          #13
                          Thanks, Lenny! Unfortunately, it's still not working. The response I get is:

                          Code:
                          {
                          "body": "{\"_error\":{\"status\":400,\"title\":\"Bad request\",\"message\":\"stream ended unexpectedly\"}}",
                          "error_text": "",
                          "error_code": 0,
                          "headers": "HTTP/1.1 400 Bad Request\r\nDate: Tue, 02 Aug 2022 16:00:44 GMT\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 85\r\nConnection: close\r\nx-protected-by: Sqreen\r\nx-ratelimit-limit: 100\r\nx-ratelimit-remaining: 99\r\nx-ratelimit-reset: 1659456104.223\r\netag: W/\"55-dQzmMfSvcU8y7m7hPkkDPbls3U0\"\r\nX-Front-Time: 193",
                          "parsed_headers": {
                          "status_code": 400,
                          "reason_phrase": "Bad Request",
                          "http_version": "HTTP/1.1",
                          "Date": "Tue, 02 Aug 2022 16:00:44 GMT",
                          "ContentType": "application/json; charset=utf-8",
                          "ContentLength": "85",
                          "Connection": "close",
                          "xprotectedby": "Sqreen",
                          "xratelimitlimit": "100",
                          "xratelimitremaining": "99",
                          "xratelimitreset": "1659456104.223",
                          "etag": "W/\"55-dQzmMfSvcU8y7m7hPkkDPbls3U0\"",
                          "XFrontTime": "193"
                          },
                          "http_version": "0"
                          }

                          Comment


                            #14
                            After careful debugging, I made a few adjustments as follows:

                            Code:
                            dim yourToken as c = "your API token goes here"
                            dim attachment as c = "c:\dev\socket.txt" '"E:\myfiles\test.jpg"
                            dim formdata[0] as p
                            formdata[].name = "author_id"
                            formdata[..].value = "tea_123"
                            formdata[].name = "to[]"
                            formdata[..].value = "[email protected]"
                            formdata[].name = "subject"
                            formdata[..].value = "test subject 3"
                            formdata[].name = "body"
                            formdata[..].value = "test message 3"
                            formdata[].name = "attachements"
                            formdata[..].filename = file.filename_parse(attachment, "NE")
                            formdata[..].value = get_from_file(attachment)
                            
                            dim boundary as c = "--------------------------" + remspecial(api_uuidcreate())
                            dim req as p
                            dim resp as p
                            dim req.host as c = "api2.frontapp.com"
                            dim req.page as c = "/channels/cha_123/drafts"
                            dim req.method as c = "POST"
                            dim req.header as c = "Content-Type: multipart/form-data; boundary=\"" + boundary + "\"" + crlf() + "Authorization: Bearer " + yourToken
                            dim req.ssl_on as l = .t.
                            dim req.body as b
                            dim element as p
                            for each element in formdata
                            req.body = req.body + "--" + boundary + crlf()
                            req.body = req.body + "Content-Disposition: form-data; name=" + s_quote(element.name)
                            if eval_valid("element.filename")
                            req.body = req.body + "; filename=" + s_quote(element.filename)
                            end if
                            req.body = req.body + crlf() + crlf() + element.value + crlf()
                            next element
                            req.body = req.body + crlf() + "--" + boundary + "--"
                            
                            resp = http_fetch(req)
                            showvar(resp)
                            This now generates a 200 response, and a draft message is created. However, the attachment part still does not work. It appears to create an attachment, but it's very small (6B), and when debugging it shows only a few characters ("ؿ͊"). How do I get it to upload the attachment as binary data?

                            Comment


                              #15
                              Try changing get_from_file() to file.to_blob()

                              Lenny Forziati
                              Vice President, Internet Products and Technical Services
                              Alpha Software Corporation

                              Comment

                              Working...
                              X